title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python Tkinter While Thread
39,689,940
<p>Well i am a bit of newb at python, and i am getting hard to make a thread in Tkinter , as you all know using while in Tkinter makes it Not Responding and the script still running.</p> <pre><code> def scheduler(): def wait(): schedule.run_pending() time.sleep(1) return Hours = ScheduleTest() if len(Hours) == 0: print("You need to write Hours, Example: 13:30,20:07") if len(Hours) &gt; 0: print("Scheduled: ", str(Hours)) if len(Hours) == 1: schedule.every().day.at(Hours[0]).do(Jumper) print("Will jump 1 time") elif len(Hours) == 2: schedule.every().day.at(Hours[0]).do(Jumper) schedule.every().day.at(Hours[1]).do(Jumper) print("Will jump 2 times") elif len(Hours) == 3: schedule.every().day.at(Hours[0]).do(Jumper) schedule.every().day.at(Hours[1]).do(Jumper) schedule.every().day.at(Hours[2]).do(Jumper) print("Will jump 3 times") while True: t = threading.Thread(target=wait) t.start() return scheduler() </code></pre> <p>i have tried to do something like this but it still makes tkinter not responding Thanks in advance.</p>
1
2016-09-25T17:52:11Z
39,719,410
<h3>When to use the after method; faking while without threading</h3> <p>As mentioned in a comment, In far most cases, you do not need threading to run a "fake" while loop. You can use the <code>after()</code> method to schedule your actions, using <code>tkinter</code>'s <code>mainloop</code> as a "coat rack" to schedule things, pretty much exactly like you would in a while loop.</p> <p>This works in all situations where you can simply throw out commands with e.g. <code>subprocess.Popen()</code>, update widgets, show messages etc.</p> <p>It does <em>not</em> work when the scheduled process takes a lot of time, running <em>inside</em> the mainloop. Therefore <code>time.sleep()</code> is a bummer; it will simply hold the <code>mainloop</code>.</p> <h3>How it works</h3> <p>Within that limitation however, you can run complicated tasks, schedule actions even set <code>break</code> (-equivalent) conditions.</p> <p>Simply create a function, initiate it with <code>window.after(0, &lt;function&gt;)</code>. Inside the function, (re-) schedule the function with <code>window.after(&lt;time_in_milliseconds&gt;, &lt;function&gt;)</code>.</p> <p>To apply a break- like condition, simply rout the process (inside the function) not to be scheduled again.</p> <h3>An example</h3> <p>This is best illustrated with a simplified example:</p> <p><a href="http://i.stack.imgur.com/pj8bS.png" rel="nofollow"><img src="http://i.stack.imgur.com/pj8bS.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/5s8Ux.png" rel="nofollow"><img src="http://i.stack.imgur.com/5s8Ux.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/kO16M.png" rel="nofollow"><img src="http://i.stack.imgur.com/kO16M.png" alt="enter image description here"></a></p> <pre><code>from tkinter import * import time class TestWhile: def __init__(self): self.window = Tk() shape = Canvas(width=200, height=0).grid(column=0, row=0) self.showtext = Label(text="Wait and see...") self.showtext.grid(column=0, row=1) fakebutton = Button( text="Useless button" ) fakebutton.grid(column=0, row=2) # initiate fake while self.window.after(0, self.fakewhile) self.cycles = 0 self.window.minsize(width=200, height=50) self.window.title("Test 123(4)") self.window.mainloop() def fakewhile(self): # You can schedule anything in here if self.cycles == 5: self.showtext.configure(text="Five seconds passed") elif self.cycles == 10: self.showtext.configure(text="Ten seconds passed...") elif self.cycles == 15: self.showtext.configure(text="I quit...") """ If the fake while loop should only run a limited number of times, add a counter """ self.cycles = self.cycles+1 """ Since we do not use while, break will not work, but simply "routing" the loop to not being scheduled is equivalent to "break": """ if self.cycles &lt;= 15: self.window.after(1000, self.fakewhile) else: # start over again self.cycles = 0 self.window.after(1000, self.fakewhile) # or: fakebreak, in that case, uncomment below and comment out the # two lines above # pass TestWhile() </code></pre> <p>In the example above, we run a scheduled process for fifteen seconds. While the loop runs, several simple tasks are performed, in time, by the function <code>fakewhile()</code>. </p> <p>After these fivteen seconds, we can start over again or "break". Just uncomment the indicated section to see...</p>
1
2016-09-27T08:09:19Z
[ "python", "multithreading", "tkinter", "python-multithreading", "schedule" ]
asynchronous subprocess Popen python 3.5
39,689,975
<p>I am trying to asynchronously run the Popen command from subprocess, so that I can run other stuff in the background.</p> <pre><code>import subprocess import requests import asyncio import asyncio.subprocess async def x(message): if len(message.content.split()) &gt; 1: #output = asyncio.create_subprocess_shell(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) output = subprocess.Popen(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) return output.communicate()[0].decode('utf-8') </code></pre> <p>I have tried to understand <a href="https://docs.python.org/3/library/asyncio-subprocess.html" rel="nofollow">https://docs.python.org/3/library/asyncio-subprocess.html</a> but i am not sure what a protocol factory is.</p>
-1
2016-09-25T17:55:15Z
39,746,135
<p>Tested with python 3.5. Just ask if you have questions.</p> <pre><code>import threading import time import subprocess import shlex from sys import stdout # Only data wihtin a class are actually shared by the threads. # Let's use a class as communicator (there could be problems if you have more than # a single thread) class Communicator(object): counter = 0 stop = False arg = None result = None # Here we can define what you want to do. There are other methods to do that # but this is the one I prefer. class ThreadedFunction(threading.Thread): def run(self, *args, **kwargs): super().run() command = c.arg # Here what you want to do... command = shlex.split(command) print(time.time()) # this is just to check that the command (sleep 5) is executed output = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print('\n',time.time()) c.result = output if c.stop: return None # This is useful only within loops within threads # Create a class instance c = Communicator() c.arg = 'time sleep 5' # Here I used the 'time' only to have some output # Create the thread and start it t = ThreadedFunction() t.start() # Start the thread and do something else... # ...for example count the seconds in the mean time.. try: for j in range(100): c.counter += 1 stdout.write('\r{:}'.format(c.counter)) stdout.flush() time.sleep(1) if c.result != None: print(c.result) break except: c.stop = True </code></pre>
0
2016-09-28T11:27:54Z
[ "python", "asynchronous", "subprocess", "python-3.5" ]
asynchronous subprocess Popen python 3.5
39,689,975
<p>I am trying to asynchronously run the Popen command from subprocess, so that I can run other stuff in the background.</p> <pre><code>import subprocess import requests import asyncio import asyncio.subprocess async def x(message): if len(message.content.split()) &gt; 1: #output = asyncio.create_subprocess_shell(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) output = subprocess.Popen(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) return output.communicate()[0].decode('utf-8') </code></pre> <p>I have tried to understand <a href="https://docs.python.org/3/library/asyncio-subprocess.html" rel="nofollow">https://docs.python.org/3/library/asyncio-subprocess.html</a> but i am not sure what a protocol factory is.</p>
-1
2016-09-25T17:55:15Z
39,746,464
<p>This one is much simpler, I found it after the other reply that could, anyway, be interesting... so I left it.</p> <pre><code>import time import subprocess import shlex from sys import stdout command = 'time sleep 5' # Here I used the 'time' only to have some output def x(command): cmd = shlex.split(command) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return p # Start the subprocess and do something else... p = x(command) # ...for example count the seconds in the mean time.. try: # This take care of killing the subprocess if problems occur for j in range(100): stdout.write('\r{:}'.format(j)) stdout.flush() time.sleep(1) if p.poll() != None: print(p.communicate()) break except: p.terminate() # or p.kill() </code></pre> <p>The asynchronism is evident from the fact that the python script prints the counter value on the stdout while the background process runs the <code>sleep</code> command. The fact that the python script exit after ~5sec printing the output of the bash <code>time</code> command printing the counter in the meanwhile is an evidence that the script works.</p>
0
2016-09-28T11:42:29Z
[ "python", "asynchronous", "subprocess", "python-3.5" ]
asynchronous subprocess Popen python 3.5
39,689,975
<p>I am trying to asynchronously run the Popen command from subprocess, so that I can run other stuff in the background.</p> <pre><code>import subprocess import requests import asyncio import asyncio.subprocess async def x(message): if len(message.content.split()) &gt; 1: #output = asyncio.create_subprocess_shell(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) output = subprocess.Popen(message.content[3:], shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) return output.communicate()[0].decode('utf-8') </code></pre> <p>I have tried to understand <a href="https://docs.python.org/3/library/asyncio-subprocess.html" rel="nofollow">https://docs.python.org/3/library/asyncio-subprocess.html</a> but i am not sure what a protocol factory is.</p>
-1
2016-09-25T17:55:15Z
39,754,330
<p>I eventually found the answer to my question, which utilizes async. <a href="http://pastebin.com/Zj8SK1CG" rel="nofollow">http://pastebin.com/Zj8SK1CG</a></p>
0
2016-09-28T17:43:53Z
[ "python", "asynchronous", "subprocess", "python-3.5" ]
My HyperlinkedImage subclass of reportlab Image class is not working
39,689,977
<p>I'm trying to export a PDF with hyperlinked images for a report. I have images throughout my report, and wanted to add a hyperlink to that picture added in the PDF to open up the jpg in the folder where I grabbed the image. I found great solutions from @Meilo <a href="http://stackoverflow.com/questions/19596300/reportlab-image-link/26294527#26294527">ReportLab Image Link</a> and @missmely <a href="http://stackoverflow.com/questions/18114820/is-it-possible-to-get-a-flowables-coordinate-position-once-its-rendered-using">Is it possible to get a Flowable's coordinate position once it's rendered using ReportLab.platypus?</a></p> <p>But, I keep getting errors when attempting to create an object from the HyperlinkClass. Could someone help me create the object and reference it correctly?</p> <pre><code>from reportlab.lib.enums import TA_JUSTIFY from reportlab.lib.pagesizes import letter from reportlab.platypus import Flowable, SimpleDocTemplate, Paragraph, Spacer from reportlab.platypus import Image, PageBreak, KeepTogether, ListFlowable, from reportlab.platypus import ListItem, Table, ListItem, Table from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch class HyperlinkedImage(Image, object): """ Class reportlab.platypus.flowables has a class called Flowable that Image inherits from. Flowable has a method called drawOn(self, canvas, x, y, _sW=0) that I override in a new class I created called HyperlinkedImage...Now instead of creating a reportlab.platypus. Image as your image flowable, use the new HyperlinkedImage instead. See original post: http://stackoverflow.com/questions/18114820/is-it-possible-to-get-a-flowables-coordinate-position-once-its-rendered-using """ # The only variable I added to __init__() is hyperlink. I default it to None # for the if statement I use later. def __init__(self, filename, hyperlink=None, width=None, height=None, kind='direct', mask='auto', lazy=1): super(HyperlinkedImage, self).__init__(filename, width, height, kind, mask, lazy) self.hyperlink = hyperlink def drawOn(self, canvas, x, y, _sW=0): if self.hyperlink: # If a hyperlink is given, create a canvas.linkURL() x1 = self.hAlignAdjust(x, _sW) # This is basically adjusting the x # coordinate according to the # alignment given to the # flowable (RIGHT, LEFT, CENTER) y1 = y x2 = x1 + self._width y2 = y1 + self._height canvas.linkURL(url=self.hyperlink, rect=(x1, y1, x2, y2), thickness=0, relative=1) super(HyperlinkedImage, self).drawOn(canvas, x, y, _sW) # Create PDF doc = SimpleDocTemplate( "myHyperlinkedPics.pdf", pagesize=letter, rightMargin=60, leftMargin=60, topMargin=60, bottomMargin=80) Story = [] styleSheet = getSampleStyleSheet() logo = "IamZeroInjury.png" im = Image(logo, 1 * inch, 1 * inch) Story.append(KeepTogether(im)) myHyperlinkedImage = HyperlinkedImage(logo, hyperlink=logo) Story.append(KeepTogether(myhyperlinkedImage(hyperlink=logo, 1*inch, 1*inch, 1*inch, 1*inch))) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) Story.append(PageBreak()) doc.build(Story) </code></pre> <p>When I run this code, I get the error:</p> <pre class="lang-none prettyprint-override"><code>in __getattr__ raise AttributeError("&lt;Image @ 0x%x&gt;.%s" % (id(self),a)) AttributeError: &lt;Image @ 0x3752990&gt;.hAlignAdjust </code></pre>
0
2016-09-25T17:55:18Z
39,727,013
<p>The answer is actually proposed in @Dennis Golomazov's post on the second answer for the modified HyperlinkedImage subclass <a href="http://stackoverflow.com/questions/19596300/reportlab-image-link/39134216#39134216">ReportLab Image Link</a>. I knew something wasn't working with the hAlign parameter, and @Dennis Golmazov proposed a simple fix by adding the hAlign parameter into the <strong>init</strong> method.</p> <p>For those wondering what the code is to use the HyperlinkedImage subclass, here's what works:</p> <pre><code>from reportlab.lib.enums import TA_JUSTIFY from reportlab.lib.pagesizes import letter from reportlab.platypus import Flowable, SimpleDocTemplate, Paragraph from reportlab.platypus import Image, KeepTogether, ListFlowable, from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch doc = SimpleDocTemplate("myHyperlinkedPics.pdf", pagesize=letter, rightMargin=60, leftMargin=60, topMargin=60, bottomMargin=80) Story = [] styleSheet = getSampleStyleSheet() logo = "mypic.png" im = Image(logo, 1 * inch, 1 * inch) myHyperlinkedImage = HyperlinkedImage(logo, hyperlink='http://www.google.com', width=1*inch, height=1*inch) Story.append(KeepTogether(myHyperlinkedImage)) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) doc.build(Story) </code></pre>
0
2016-09-27T14:13:02Z
[ "python", "image", "hyperlink", "reportlab" ]
relation "hello_greeting" does not exist
39,690,005
<p>I'm trying the python tutorial on Heroku app (<a href="https://devcenter.heroku.com/articles/getting-started-with-python#introduction" rel="nofollow">https://devcenter.heroku.com/articles/getting-started-with-python#introduction</a>) and I got that error when I appended \db on the main app but it works with the localhost.</p> <pre><code>Environment: Request Method: GET Request URL: https://&lt;appname&gt;.herokuapp.com/db Django Version: 1.9.2 Python Version: 2.7.11 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/app/.heroku/python/lib/python2.7/site- packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/hello/views.py" in db 17. greeting.save() File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py" in save 700. force_update=force_update, update_fields=update_fields) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py" in save_base 728. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py" in _save_table 812. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert 851. using=using, raw=raw) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method 122. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in _insert 1039. return query.get_compiler(using=using).execute_sql(return_id) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 1060. cursor.execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py" in __exit__ 95. six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) Exception Type: ProgrammingError at /db Exception Value: relation "hello_greeting" does not exist LINE 1: INSERT INTO "hello_greeting" ("when") VALUES ('2016-09-25T17... ^ </code></pre> <p>Thank you for your help.</p>
1
2016-09-25T17:58:15Z
39,690,175
<p>Sorry, my mistake. I was not able to migrate thus the issue was solved using</p> <pre><code>heroku run python manage.py migrate </code></pre>
0
2016-09-25T18:13:46Z
[ "python", "heroku" ]
PyQt QPushButton signal handling
39,690,243
<p>I have a <code>repeat</code> python function and a <em>test.ui</em> which has only one push-button. My doubt is how to loop the same function exactly once for every time the button is clicked. Because for me whenever I perform:</p> <pre><code>self.pushButton.clicked.connect(self.repeat) </code></pre> <p>it loops many times into the function instead of a single time. I found this by incrementing a value for every time we reach the function. How to reach the function <code>repeat</code> exactly once for every click on the push-button?</p> <pre><code>import sys from PyQt4 import QtCore, QtGui, uic qtCreatorFile = "test.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class Login(QtGui.QMainWindow, Ui_MainWindow): i=1 def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.pushButton.setText("iam in init") self.pushButton.clicked.connect(self.repeat) def repeat(self): self.pushButton.setText("iam in repeat"+str(self.i)) self.i=self.i+1 self.pushButton.clicked.connect(self.repeat) if __name__ == "__main__": app=QtGui.QApplication(sys.argv) main = Login() main.show() sys.exit(app.exec_()) </code></pre>
0
2016-09-25T18:21:33Z
39,703,796
<p>Loooking at your code, you have established the connection multiple times. You should establish it with <code>self.pushButton.clicked.connect(self.repeat)</code> only in your <code>__init__</code> but not in <code>repeat()</code> function. In other words, delete the second occurrence (i.e. in <code>repeat()</code>) and you should be fine. The connection should be established only once because once established it lasts till <code>disconnect()</code> is called on it or till the <code>slot</code> or the <code>signal</code> are destroyed.</p>
1
2016-09-26T13:09:51Z
[ "python", "pyqt4", "signals-slots", "qpushbutton" ]
Django rest framework one to one relation Create serializer
39,690,267
<p>I'm a beginner to the Django Rest Frame work. I want to create a custom user but I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me </p> <p>models.py</p> <pre><code>class Account(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) image=models.ImageField(upload_to='Images/',default='Images/user.png') date=models.DateField(auto_now=True,auto_now_add=False) </code></pre> <p>Serializers.py</p> <pre><code> class AccountCreateUpdateSerializer(serializers.ModelSerializer): user=UserListSerializers() image=serializers.ImageField() class Meta: model= Account fields=['id','user','image'] def create(self,validated_data): user_data=validated_data.pop('user') account=Account.objects.create(**validated_data) User.objects.create(account=account,**user_data) return account </code></pre> <p>the error : <a href="http://i.stack.imgur.com/Rgovf.png" rel="nofollow">enter image description here</a></p>
1
2016-09-25T18:23:13Z
39,691,374
<p>Your problem is here:</p> <pre><code> user_data = validated_data.pop('user') account = Account.objects.create(**validated_data) User.objects.create(account=account, **user_data) </code></pre> <p>You're trying to create an Account before creating a User, which won't work because an Account requires a value for <code>user_id</code>. If your User model had a foreign key to Account, instead of the other way around, then creating the account first would be the right way to do it.</p> <p>Switching to:</p> <pre><code> user_data = validated_data.pop('user') user = User.objects.create(**user_data) account = Account.objects.create(user=user, **validated_data) </code></pre> <p>should fix the problem as long as your <code>UserListSerializers()</code> is providing the correct data to create a User instance.</p> <p>Hope that helps.</p>
1
2016-09-25T20:14:13Z
[ "python", "django", "rest", "django-rest-framework" ]
How to split string with different phones using re?
39,690,301
<p>For example there are such phones:</p> <pre><code>phones = '+35(123) 456 78 90 (123) 555 55 55 (908)985 88 89 (593)592 56 95' </code></pre> <p>I need to get:</p> <pre><code>phones_list = ['+35(123) 456 78 90', '(123) 555 55 55', '(908)985 88 89', (593)592 56 95] </code></pre> <p>Trying to solve using <code>re</code>, but quite a hard task to me.</p>
2
2016-09-25T18:26:25Z
39,690,425
<p>This approach uses the <code>+</code> or <code>(</code> to signal the beginning of a phone number. It does not require multiple-spaces:</p> <pre><code>&gt;&gt;&gt; phones = '+35(123) 456 78 90 (123) 555 55 55 (908)985 88 89 (593)592 56 95' &gt;&gt;&gt; re.split(r' +(?=[(+])', phones) ['+35(123) 456 78 90', '(123) 555 55 55', '(908)985 88 89', '(593)592 56 95'] </code></pre> <p>This splits the string based on one-or-more spaces followed by either <code>(</code> or <code>+</code>.</p> <p>In the regular expression, <code>+</code> matches one or more spaces. <code>(?=[(+])</code> is a look-ahead. It requires that the spaces be followed by either <code>(</code> or <code>+</code> but does not consume the <code>(</code> or <code>+</code>. Because we are using a look-ahead instead of a plain match, the the leading <code>(</code> and <code>+</code> remain part of the phone number.</p>
5
2016-09-25T18:38:10Z
[ "python", "regex", "python-3.x" ]
PHP openssl AES in Python
39,690,400
<p>I am working on a project where PHP is used for decrypt AES-256-CBC messages</p> <pre><code>&lt;?php class CryptService{ private static $encryptMethod = 'AES-256-CBC'; private $key; private $iv; public function __construct(){ $this-&gt;key = hash('sha256', 'c7b35827805788e77e41c50df44441491098be42'); $this-&gt;iv = substr(hash('sha256', 'c09f6a9e157d253d0b2f0bcd81d338298950f246'), 0, 16); } public function decrypt($string){ $string = base64_decode($string); return openssl_decrypt($string, self::$encryptMethod, $this-&gt;key, 0, $this-&gt;iv); } public function encrypt($string){ $output = openssl_encrypt($string, self::$encryptMethod, $this-&gt;key, 0, $this-&gt;iv); $output = base64_encode($output); return $output; } } $a = new CryptService; echo $a-&gt;encrypt('secret'); echo "\n"; echo $a-&gt;decrypt('S1NaeUFaUHdqc20rQWM1L2ZVMDJudz09'); echo "\n"; </code></pre> <p>ouutput</p> <pre><code>&gt;&gt;&gt; S1NaeUFaUHdqc20rQWM1L2ZVMDJudz09 &gt;&gt;&gt; secret </code></pre> <p>Now I have to write Python 3 code for encrypting data. I've tried use PyCrypto but without success. My code:</p> <pre><code>import base64 import hashlib from Crypto.Cipher import AES class AESCipher: def __init__(self, key, iv): self.key = hashlib.sha256(key.encode('utf-8')).digest() self.iv = hashlib.sha256(iv.encode('utf-8')).digest()[:16] __pad = lambda self,s: s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size) __unpad = lambda self,s: s[0:-ord(s[-1])] def encrypt( self, raw ): raw = self.__pad(raw) cipher = AES.new(self.key, AES.MODE_CBC, self.iv) return base64.b64encode(cipher.encrypt(raw)) def decrypt( self, enc ): enc = base64.b64decode(enc) cipher = AES.new(self.key, AES.MODE_CBC, self.iv ) return self.__unpad(cipher.decrypt(enc).decode("utf-8")) cipher = AESCipher('c7b35827805788e77e41c50df44441491098be42', 'c09f6a9e157d253d0b2f0bcd81d338298950f246') enc_str = cipher.encrypt("secret") print(enc_str) </code></pre> <p>output</p> <pre><code>&gt;&gt;&gt; b'tnF87LsVAkzkvs+gwpCRMg==' </code></pre> <p>But I need output <code>S1NaeUFaUHdqc20rQWM1L2ZVMDJudz09</code> which will PHP decrypt to <code>secret</code>. How to modify Python code to get expected output?</p>
0
2016-09-25T18:35:01Z
39,690,864
<p><a href="http://php.net/manual/en/function.hash.php" rel="nofollow">PHP's <code>hash</code></a> outputs a Hex-encoded string by default, but Python's <code>.digest()</code> returns <code>bytes</code>. You probably wanted to use <code>.hexdigest()</code>:</p> <pre><code>def __init__(self, key, iv): self.key = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32].encode("utf-8") self.iv = hashlib.sha256(iv.encode('utf-8')).hexdigest()[:16].encode("utf-8") </code></pre> <p>The idea of the initialization vector (IV) is to provide randomization for the encryption with the same key. If you use the same IV, an attacker may be able to deduce that you send the same message twice. This can be considered as a broken protocol.</p> <p>The IV is not supposed to be secret, so you can simply send it along with the ciphertext. It is common to prepend it to the ciphertext during encryption and slice it off before decryption.</p>
1
2016-09-25T19:20:49Z
[ "php", "python", "encryption", "aes", "pycrypto" ]
How to use inline_keyboard instead of keyboard in Telegram bot (Python)?
39,690,631
<p>I have this part of code (Python) that I'm using in my Telegram bot:</p> <pre><code>def reply(msg=None, img=None): if msg: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(chat_id), 'text': msg.encode('utf-8'), 'disable_web_page_preview': 'true', # 'reply_to_message_id': str(message_id), 'reply_markup': json.dumps({'keyboard': [bline1, bline2], 'resize_keyboard': True}), })).read() </code></pre> <p>For this part everything works fine. The question is: how to use inline_keyboard intead of regular keyboard?</p> <p>I understand that it is a noob question, but it would be great if someone could help me.</p> <p>Thanks!</p>
0
2016-09-25T18:58:23Z
39,742,993
<p>since the <a href="https://core.telegram.org/bots/api#inlinekeyboardmarkup" rel="nofollow">Inline Keyboard</a> is just a different json object, I'd say you only have to build it with <code>json.dumps</code> instead of your current build. Following your example, something like this should make the trick:</p> <pre><code>def reply(msg=None, img=None): if msg: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(chat_id), 'text': msg.encode('utf-8'), 'disable_web_page_preview': 'true', # 'reply_to_message_id': str(message_id), 'reply_markup': json.dumps({'inline_keyboard': [[{'text': bline1, 'callback_data': bline1}, {'text': bline2, 'callback_data': bline2}]]}), })).read() </code></pre>
0
2016-09-28T09:15:44Z
[ "python", "keyboard", "telegram", "telegram-bot" ]
overwriting output of function in terminal on same line
39,690,708
<p>I have a function, for example</p> <pre><code>def f(x): for i in range(x): print i </code></pre> <p>Without making any addition in f(x) function, is it possible to overwrite the terminal line during run? For example, in my case it shows like this:</p> <pre><code>print f(5) </code></pre> <p>output is:</p> <pre><code>1 2 3 4 </code></pre> <p>but I want it to overwrite and instead print like this:</p> <pre><code>print f(5) 4 </code></pre> <p>Please keep in mind that I cannot modify inside f(x) function.</p>
0
2016-09-25T19:05:33Z
39,690,758
<p>In general, no; but depending on what the "terminal" is assumed to be, maybe. Many terminal windows emulate the ancient cursor positioning commands from one or more "glass tty" terminals. In which case, if you assume you know what terminal is being emulated, you can send cursor positioning commands to move back to the previous before calling f.</p>
0
2016-09-25T19:11:00Z
[ "python", "python-2.7" ]
overwriting output of function in terminal on same line
39,690,708
<p>I have a function, for example</p> <pre><code>def f(x): for i in range(x): print i </code></pre> <p>Without making any addition in f(x) function, is it possible to overwrite the terminal line during run? For example, in my case it shows like this:</p> <pre><code>print f(5) </code></pre> <p>output is:</p> <pre><code>1 2 3 4 </code></pre> <p>but I want it to overwrite and instead print like this:</p> <pre><code>print f(5) 4 </code></pre> <p>Please keep in mind that I cannot modify inside f(x) function.</p>
0
2016-09-25T19:05:33Z
39,690,821
<p>Since <code>print</code> issues a newline, and you cannot go back after that, you have to prevent at all costs that a newline char to be issued in the terminal.</p> <p>You can do it by redirecting <code>sys.stdout</code>. <code>print</code> will output to your new stream. In your stream, remove the linefeed and add a carriage return. Done</p> <pre><code>import sys def f(x): for i in range(x): print i class fake(): def __init__(self): self.__out = sys.stdout def write(self,x): r = self.__out.write(x.replace("\n","")+"\r") self.__out.flush() # flush like if we wrote a newline return r sys.stdout=fake() f(5) </code></pre> <p>Result:</p> <ul> <li>on a terminal (windows or Linux): only 4 is shown</li> <li>redirecting to a file: we see all numbers separated by <code>\r</code> chars</li> </ul> <p>Ok it's a hack but we cannot modify <code>f</code> and we did not... Mission accomplished.</p> <p>It may be useful to restore <code>sys.stdout</code> to its original value once we're done.</p>
0
2016-09-25T19:16:47Z
[ "python", "python-2.7" ]
overwriting output of function in terminal on same line
39,690,708
<p>I have a function, for example</p> <pre><code>def f(x): for i in range(x): print i </code></pre> <p>Without making any addition in f(x) function, is it possible to overwrite the terminal line during run? For example, in my case it shows like this:</p> <pre><code>print f(5) </code></pre> <p>output is:</p> <pre><code>1 2 3 4 </code></pre> <p>but I want it to overwrite and instead print like this:</p> <pre><code>print f(5) 4 </code></pre> <p>Please keep in mind that I cannot modify inside f(x) function.</p>
0
2016-09-25T19:05:33Z
39,693,070
<p>If you are trying to print only the last line, you can pipe the output and use tail command to retrieve only the last word.</p> <p>Useful link: <a href="https://kb.iu.edu/d/acrj" rel="nofollow">https://kb.iu.edu/d/acrj</a></p>
0
2016-09-26T00:12:04Z
[ "python", "python-2.7" ]
Convert float to int and leave nulls
39,690,742
<p>I have the following dataframe, I want to convert values in column 'b' to integer</p> <pre><code> a b c 0 1 NaN 3 1 5 7200.0 20 2 5 580.0 20 </code></pre> <p>The following code is throwing exception "ValueError: Cannot convert NA to integer"</p> <pre><code>df['b'] = df['b'].astype(int) </code></pre> <p>How do i convert only floats to int and leave the nulls as is?</p>
3
2016-09-25T19:09:25Z
39,694,672
<p><code>np.NaN</code> is a floating point only kind of thing, so it has to be removed in order to create an integer pd.Series. Jeon's suggestion work's great If 0 isn't a valid value in <code>df['b']</code>. For example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'a': [1, 5, 5], 'b': [np.NaN, 7200.0, 580.0], 'c': [3, 20, 20]}) print(df, '\n\n') df['b'] = np.nan_to_num(df['b']).astype(int) print(df) </code></pre> <p>if there are valid 0's, then you could first replace them all with some unique value (e.g., -999999999), the the conversion above, and then replace these unique values with 0's.</p> <p>Either way, you have to remember that you have 0's where there were once NaNs. You will need to be careful to filter these out when doing various numerical analyses (e.g., mean, etc.)</p>
1
2016-09-26T04:19:31Z
[ "python", "pandas", "numpy" ]
Unwanted timestamp when using print in python
39,690,816
<p>I am using autobahn[twisted] to achieve some WAMP communication. While subscribing to a topic a getting feed from it i print it. When i do it i get something like this:</p> <pre><code>2016-09-25T21:13:29+0200 (u'USDT_ETH', u'12.94669009', u'12.99998074', u'12.90000334', u'0.00035594', u'18396.86929477', u'1422.19525455', 0, u'13.14200000', u'12.80000000') </code></pre> <p>I have sacrificed too many hours to take it out. And yes, i tested other things to print, it print without this timestamp. This is my code:</p> <pre><code>from twisted.internet.defer import inlineCallbacks from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner class PushReactor(ApplicationSession): @inlineCallbacks def onJoin(self, details): print "subscribed" yield self.subscribe(self.onTick, u'ticker') def onTick(self, *args): print args if __name__ == '__main__': runner = ApplicationRunner(u'wss://api.poloniex.com', u'realm1') runner.run(PushReactor) </code></pre> <p>How can i remove this timestamp?</p>
0
2016-09-25T19:16:33Z
39,691,914
<p>Well, <code>sys.stderr</code> and <code>sys.stdout</code> are redirected to a twisted logger.</p> <p>You need to change the logging format before running you app.</p> <p>See: <a href="https://twistedmatrix.com/documents/15.2.1/core/howto/logger.html" rel="nofollow">https://twistedmatrix.com/documents/15.2.1/core/howto/logger.html</a></p> <h2>How to reproduce</h2> <p>You can reproduce your problem with this simple application:</p> <pre><code>from autobahn.twisted.wamp import ApplicationRunner if __name__ == '__main__': print("hello1") runner = ApplicationRunner(u'wss://api.poloniex.com', u'realm1') print("hello2") runner.run(None) print("hello3") </code></pre> <p>When the process is killed, you'll see:</p> <pre><code>hello1 hello2 2016-09-26T14:08:13+0200 Received SIGINT, shutting down. 2016-09-26T14:08:13+0200 Main loop terminated. 2016-09-26T14:08:13+0200 hello3 </code></pre> <p>During application launching, <code>stdout</code> (and <code>stderr</code>) are redirected to a file-like object (of class <code>twisted.logger._io.LoggingFile</code>).</p> <p>Every call to <code>print</code> or <code>write</code> are changed in twister log messages (one for each line).</p> <p>The redirection is done in the class <code>twisted.logger._global.LogBeginner</code>, look at the <code>beginLoggingTo</code> method.</p>
0
2016-09-25T21:14:11Z
[ "python", "printing", "timestamp", "autobahn" ]
GitPython "blame" does not give me all changed lines
39,690,910
<p>I am using GitPython. Below I print the total number of lines changed in a specific commit: <code>f092795fe94ba727f7368b63d8eb1ecd39749fc4</code>:</p> <pre><code>from git import Repo repo = Repo("C:/Users/shiro/Desktop/lucene-solr/") sum_lines = 0 for blame_commit, lines_list in repo.blame('HEAD', 'lucene/core/src/java/org/apache/lucene/analysis/Analyzer.java'): if blame_commit.hexsha == 'f092795fe94ba727f7368b63d8eb1ecd39749fc4': sum_lines += len(lines_list) print sum_lines </code></pre> <p>The output is 38. However, if you simply go to <a href="https://github.com/apache/lucene-solr/commit/f092795fe94ba727f7368b63d8eb1ecd39749fc4" rel="nofollow">https://github.com/apache/lucene-solr/commit/f092795fe94ba727f7368b63d8eb1ecd39749fc4</a> and look at the commit yourself for file <code>/lucene/analysis/Analyzer.java</code>, the actual number of lines changed is not 38 but it is 47. Some lines are completely missing.</p> <p>Why am I getting a wrong value ?</p>
0
2016-09-25T19:26:12Z
39,691,814
<p><code>git blame</code> tells you which commit last changed each line in a given file.</p> <p>You're not counting the number of lines changed in that commit, but rather the number of lines in the file at your current HEAD that were last modified by that specific commit.</p> <p>Changing <code>HEAD</code> to <code>f092795fe94ba727f7368b63d8eb1ecd39749fc4</code> should give you the result you expect.</p> <pre><code>$ git blame f092795fe94ba727f7368b63d8eb1ecd39749fc4 ./lucene/core/src/java/org/apache/lucene/analysis/Analyzer.java | grep f092795 | wc -l 47 $ git blame master ./lucene/core/src/java/org/apache/lucene/analysis/Analyzer.java | grep f092795 | wc -l 38 </code></pre>
2
2016-09-25T21:03:21Z
[ "python", "git", "gitpython" ]
pass multiple arguments in the url
39,690,962
<p>I'm trying to make a simple django app that interacts with the database. But I'm having trouble passing more than one parameter in the url.</p> <p>To pass the arguments i do it this way:</p> <pre><code>127.0.0.1:8000/REST/insert/?n=test/?x=2/?y=2/?z=True </code></pre> <p>And then in my <strong>views.py</strong> I get the parameters with:</p> <pre><code>name = request.GET.get('n', '') x = request.GET.get('x', '') y = request.GET.get('y', '') z = request.GET.get('z', '') </code></pre> <p>Clearly I'm doing it wrong. How can I fix it ?</p>
0
2016-09-25T19:30:25Z
39,690,983
<p>The separators between query parameters should be <code>&amp;</code> characters instead of slashes and question marks (except the first).</p> <pre><code>/?n=test/?x=2/?y=2/?z=True </code></pre> <p>should be</p> <pre><code>/?n=test&amp;x=2&amp;y=2&amp;z=True </code></pre> <p>Note: I'm not actually sure you should be using query parameters here since your url has "insert" in it. If you're really trying to insert things into a database then this should at least be done through a post request as post data.</p>
2
2016-09-25T19:32:58Z
[ "python", "django", "django-urls" ]
pass multiple arguments in the url
39,690,962
<p>I'm trying to make a simple django app that interacts with the database. But I'm having trouble passing more than one parameter in the url.</p> <p>To pass the arguments i do it this way:</p> <pre><code>127.0.0.1:8000/REST/insert/?n=test/?x=2/?y=2/?z=True </code></pre> <p>And then in my <strong>views.py</strong> I get the parameters with:</p> <pre><code>name = request.GET.get('n', '') x = request.GET.get('x', '') y = request.GET.get('y', '') z = request.GET.get('z', '') </code></pre> <p>Clearly I'm doing it wrong. How can I fix it ?</p>
0
2016-09-25T19:30:25Z
39,691,517
<p>What you want to do is not safe. Since you do an insert operation, request type should be POST and you should send the information as json.</p> <p>Just write the data as json and put it to the body of the request.</p> <p>In your view;</p> <pre><code>import json def your_view(request): body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) # This is a dictionary. </code></pre>
1
2016-09-25T20:28:31Z
[ "python", "django", "django-urls" ]
sqlite3.OperationalError: near "WHERE": syntax error
39,691,052
<p>I want to update a series of columns Country1, Country2... Country 9 based on a comma delimited string of country names in column Country. I've programmed a single statement to accomplish this task. </p> <pre><code>cur.execute("\ UPDATE t \ SET Country1 = returnCountryName(Country,0),\ Country2 = returnCountryName(Country,1),\ Country3 = returnCountryName(Country,2),\ Country4 = returnCountryName(Country,3),\ Country5 = returnCountryName(Country,4),\ Country6 = returnCountryName(Country,5),\ Country7 = returnCountryName(Country,6),\ Country8 = returnCountryName(Country,7),\ Country9 = returnCountryName(Country,8),\ Country10 = returnCountryName(Country,9),\ WHERE Country IS NOT NULL\ ;") </code></pre> <p>Howerver, I am getting the error</p> <pre><code>sqlite3.OperationalError: near "WHERE": syntax error Press any key to continue . . . </code></pre>
-1
2016-09-25T19:40:14Z
39,691,086
<p>You have to remove the comma from the last assignment:</p> <pre><code>Country10 = returnCountryName(Country,9),\ </code></pre> <p>See also <a href="http://stackoverflow.com/a/39690916/6776093">my answer</a> to your original question</p>
0
2016-09-25T19:42:55Z
[ "python", "sqlite" ]
Erosion and dilation in Python OpenCV returns white
39,691,069
<p>I am trying to use dialation and ertion</p> <p>For example, like so:</p> <pre><code>dialated = cv2.dilate(edgesCopy, cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)), iterations = 1) </code></pre> <p>The input is a uint8 image that has only values of 0 and 255, as came out of</p> <pre><code>threshold, thresholdedEdges = cv2.threshold(edges, 220, 255, cv2.THRESH_BINARY_INV); </code></pre> <p>The output, however is just a white image. I fail to understand the reason.</p> <p>The entire code is</p> <pre><code> imageSize = img.shape if len(imageSize) != 2:#color print "got a color image - quitting" return cv2.imshow("im1", img) cv2.moveWindow("im1", 60, 50) gaussianBlur = cv2.GaussianBlur(img, (5, 5), 0) # cv2.imshow("gaussianBlur", gaussianBlur) # cv2.moveWindow("gaussianBlur", 260, 50) medianBlur = cv2.medianBlur(gaussianBlur, 5) # cv2.imshow("medianBlur", medianBlur) # cv2.moveWindow("medianBlur", 460, 50) minGradientValueThreshold = 225 maxGradientValueThreshold = 150 edges = cv2.Canny(medianBlur, minGradientValueThreshold, maxGradientValueThreshold) cv2.imshow("edges", edges) cv2.moveWindow("edges", 660, 50) # Threshold. # Set values equal to or above 220 to 0. # Set values below 220 to 255. threshold, thresholdedEdges = cv2.threshold(edges, 220, 1, cv2.THRESH_BINARY_INV); edgesCopy = thresholdedEdges.copy() #close the edges before floodfilling, to avoid filing the background # closing = cv2.morphologyEx(floodFilledImage, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))) DOESN'T WORK dialated = cv2.dilate(edgesCopy, cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)), iterations = 1) cv2.imshow("dialated", dialated) cv2.moveWindow("dialated", 60, 250) eroded = cv2.erode(dialated, cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)), iterations = 1) closing = eroded cv2.imshow("closing", closing) cv2.moveWindow("closing", 60, 250) </code></pre>
0
2016-09-25T19:41:32Z
39,692,474
<p>The result of the canny edge detection is image with binary edges of thickness 1. You are thresholding this edges (which is not needed by the way) with a threshold setting cv2.THRESH_BINARY_INV, which means that the threshold result gets value 1 where pixels are bellow threshold and 0 when above. The result of such thresholding is naturaly almost white image with black lines -> you are actually just inverting the result of canny edge detector. Dilating such an image finally results in totally white image (whatever the input image actually is).</p> <p>I suggest you to just skip the thresholding step!</p> <p>If you want to do the thresholding nevertheless, use THRESH_BINARY and set maxval to 255. I also think that there should be cv2.waitKey() function call after each cv2.imshow() (at least in my case it doesnt show anything otherwise).</p>
2
2016-09-25T22:37:53Z
[ "python", "opencv", "image-processing" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whitespace <code>\s</code>. The output should be: </p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', 'MAKES', ',', 'some', 'sense'] </code></pre> <p>My solution so far is is using the <code>re</code> module: </p> <pre><code>pattern = '([\.,\s]+)' re.split(pattern, s) </code></pre> <p>However, this captures whitespace as well. I have tried using other patterns like <code>[(\.)(,)\s]+</code> but they don't work.</p> <p><em>Edit</em>: @PadraicCunningham made an astute observation. For delimiters like <code>Some text ,. , some more text</code>, I'd only want to remove leading and trailing whitespace from <code>,. ,</code> and not whitespace within.</p>
4
2016-09-25T19:43:22Z
39,691,298
<p>The following approach would be the most simple one, I suppose ...</p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' pattern = '([\.,\s]+)' splitted = [i.strip() for i in re.split(pattern, s) if i.strip()] </code></pre> <p>The output:</p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', 'MAKES', ',', 'some', 'sense'] </code></pre>
4
2016-09-25T20:06:05Z
[ "python", "regex" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whitespace <code>\s</code>. The output should be: </p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', 'MAKES', ',', 'some', 'sense'] </code></pre> <p>My solution so far is is using the <code>re</code> module: </p> <pre><code>pattern = '([\.,\s]+)' re.split(pattern, s) </code></pre> <p>However, this captures whitespace as well. I have tried using other patterns like <code>[(\.)(,)\s]+</code> but they don't work.</p> <p><em>Edit</em>: @PadraicCunningham made an astute observation. For delimiters like <code>Some text ,. , some more text</code>, I'd only want to remove leading and trailing whitespace from <code>,. ,</code> and not whitespace within.</p>
4
2016-09-25T19:43:22Z
39,691,408
<p><em>Update based on OP's last edit</em></p> <p>Python 3.*:</p> <pre><code>list(filter(None, re.split('([.,]+(?:\s+[.,]+)*)|\s', s))) </code></pre> <p>Output:</p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', 'MAKES', ',', 'some', 'sense'] </code></pre>
0
2016-09-25T20:17:19Z
[ "python", "regex" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whitespace <code>\s</code>. The output should be: </p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', 'MAKES', ',', 'some', 'sense'] </code></pre> <p>My solution so far is is using the <code>re</code> module: </p> <pre><code>pattern = '([\.,\s]+)' re.split(pattern, s) </code></pre> <p>However, this captures whitespace as well. I have tried using other patterns like <code>[(\.)(,)\s]+</code> but they don't work.</p> <p><em>Edit</em>: @PadraicCunningham made an astute observation. For delimiters like <code>Some text ,. , some more text</code>, I'd only want to remove leading and trailing whitespace from <code>,. ,</code> and not whitespace within.</p>
4
2016-09-25T19:43:22Z
39,691,418
<p>I believe this is the most efficient option regarding memory, and really efficient regarding computation time:</p> <pre><code>import re from itertools import chain from operator import methodcaller input_str = 'This, I think,., ???? MAKES , some sense ' iterator = filter(None, # Filter out all 'None's chain.from_iterable( # Flatten the tuples into one long iterable map(methodcaller("groups"), # Take the groups from each match. re.finditer("(.*?)(?:([\.,]+)|\s+|$)", input_str)))) # If you want a list: list(iterator) </code></pre>
0
2016-09-25T20:17:58Z
[ "python", "regex" ]
How to split up a string on multiple delimiters but only capture some?
39,691,091
<p>I want to split a string on any combination of delimiters I provide. For example, if the string is: </p> <pre><code>s = 'This, I think,., کباب MAKES , some sense ' </code></pre> <p>And the delimiters are <code>\.</code>, <code>,</code>, and <code>\s</code>. However I want to capture all delimiters except whitespace <code>\s</code>. The output should be: </p> <pre><code>['This', ',', 'I', 'think', ',.,', 'کباب', 'MAKES', ',', 'some', 'sense'] </code></pre> <p>My solution so far is is using the <code>re</code> module: </p> <pre><code>pattern = '([\.,\s]+)' re.split(pattern, s) </code></pre> <p>However, this captures whitespace as well. I have tried using other patterns like <code>[(\.)(,)\s]+</code> but they don't work.</p> <p><em>Edit</em>: @PadraicCunningham made an astute observation. For delimiters like <code>Some text ,. , some more text</code>, I'd only want to remove leading and trailing whitespace from <code>,. ,</code> and not whitespace within.</p>
4
2016-09-25T19:43:22Z
39,691,580
<p><strong>NOTE:</strong> According to the new edit on the question, I've improved my old regex. The new one is quite long but trust me, it's work!</p> <p>I suggest a pattern below as a delimiter of the function <code>re.split()</code>:</p> <pre><code>(?&lt;![,\.\ ])(?=[,\.]+)|(?&lt;=[,\.])(?![,\.\ ])|(?&lt;=[,\.])\ +(?![,\.\ ])|(?&lt;![,\.\ ])\ +(?=[,\.][,\.\ ]+)|(?&lt;![,\.\ ])\ +(?![,\.\ ]) </code></pre> <p>My workaround here doesn't require any pre/post space modification. The thing that make regex work is about how you order the regex expressions with <code>or</code>. My cursory strategy is any patterns that dealing with a space-leading will be evaluated last. </p> <p>See <a href="https://regex101.com/r/eW8rZ6/3" rel="nofollow">DEMO</a> </p> <p><strong>Additional</strong></p> <p>According to @revo's comment he provided an another shorten version of mine which is</p> <pre><code>\s+(?=[^.,\s])|\b(?:\s+|(?=[,.]))|(?&lt;=[,.])\b </code></pre> <p>See <a href="https://regex101.com/r/eW8rZ6/5" rel="nofollow">DEMO</a></p>
2
2016-09-25T20:36:02Z
[ "python", "regex" ]
How to to enable sharing for the secondary axis (twiny) in python
39,691,102
<p>I'm trying to enable sharing for both primary and secondary axis. The example plot is illustrated by the code below. The plot contains two horizontal axes, the primary axis grid is shown in green, while the other axis has red grid.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt FIRST = 0.0 LAST = 2.0 STEP = 0.01 t = np.arange(FIRST, LAST, STEP) s1 = np.sin(2*np.pi*t) s2 = np.exp(-t) s3 = s1*s2 ############################################################################### plt.rc('axes', grid=True) plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) fig3 = plt.figure() ax1primary = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2) ax2primary = plt.subplot2grid((4,3), (2,0), colspan=3, sharex=ax1primary) ax3primary = plt.subplot2grid((4,3), (3,0), colspan=3, sharex=ax1primary) ax1primary.plot(t,s1) ax1primary.set_yticks(np.arange(-0.9, 1.0, 0.3)) ax1primary.xaxis.grid(color='green') ax2primary.plot(t[:150],s2[:150]) ax2primary.set_yticks(np.arange(0.3, 1, 0.2)) ax2primary.xaxis.grid(color='green') ax3primary.plot(t[30:],s3[30:]) ax3primary.plot([0,2],[0.2,0.2],'m') ax3primary.set_yticks(np.arange(-0.4, 0.7, 0.2)) ax3primary.xaxis.grid(color='green') INDEX = t[np.where(abs(s3-0.2) &lt; 0.005)[0]] INDEX = np.append(INDEX, LAST) INDEX = np.insert(INDEX, 0, FIRST) ax1secondary = ax1primary.twiny() ax1secondary.set_xticks(INDEX) ax1secondary.xaxis.grid(color='red') ax2secondary = ax2primary.twiny() ax2secondary.set_xticks(INDEX) ax2secondary.xaxis.grid(color='red') ax3secondary = ax3primary.twiny() ax3secondary.set_xticks(INDEX) ax3secondary.xaxis.grid(color='red') plt.tight_layout() plt.subplots_adjust(hspace=0) for ax in [ax1primary, ax2primary, ax2secondary, ax3secondary]: plt.setp(ax.get_xticklabels(), visible=False) ############################################################################### plt.show() </code></pre> <p>On a static figure there is no issue. The problem becomes obvious when you start panning (or zooming) one of the subplots. The primary (green) axis stays perfectly in sync and moves within all subplots, but the secondary (red) axis gets misaligned and moves only within the active subplot.</p> <p>Is there a way to fix this?</p> <hr> <p>The behavior that I want to achieve is following:</p> <p>I need one common "primary" x-axis (for all three subplots) with the ticks on the bottom of the figure and another common "secondary" x-axis (for all three subplots) with the ticks on the top of the figure. The primary axis is a standard regularly spaced axis, while the secondary axis shows the customized ticks (for example zero crossings) <strong>This is all satisfied in the example above. Now I need it to be satisfied also while panning and zooming subplots.</strong></p>
1
2016-09-25T19:44:10Z
39,706,112
<p>Thanks for clarifying your question. The intended use of <code>twiny</code> is to create a second fully independent x-axis with its own scale and offset, which you would then plot into. However in your case you are only using the secondary x-axis created by <code>twiny</code> as a way to display a second set of custom x ticks, and you want this axis to always have exactly the same scale and offset as the parent x-axis.</p> <p>One approach would be to create a <a href="http://matplotlib.org/users/event_handling.html" rel="nofollow">callback</a> that updates the limits of the secondary axis whenever the primary axis gets panned:</p> <pre><code>from matplotlib.backend_bases import NavigationToolbar2 parents = [ax1primary, ax2primary, ax3primary] children = [ax1secondary, ax2secondary, ax3secondary] def callback(event=None): # return immediately if the figure toolbar is not in "navigation mode" if not isinstance(parents[0].figure.canvas.manager.toolbar, NavigationToolbar2): return for parent, child in zip(parents, children): child.set_xlim(*parent.get_xlim()) child.set_ylim(*parent.get_ylim()) # connect the callback to the figure canvas fig3.canvas.mpl_connect('motion_notify_event', callback) </code></pre>
1
2016-09-26T14:58:14Z
[ "python", "matplotlib" ]
How to to enable sharing for the secondary axis (twiny) in python
39,691,102
<p>I'm trying to enable sharing for both primary and secondary axis. The example plot is illustrated by the code below. The plot contains two horizontal axes, the primary axis grid is shown in green, while the other axis has red grid.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt FIRST = 0.0 LAST = 2.0 STEP = 0.01 t = np.arange(FIRST, LAST, STEP) s1 = np.sin(2*np.pi*t) s2 = np.exp(-t) s3 = s1*s2 ############################################################################### plt.rc('axes', grid=True) plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) fig3 = plt.figure() ax1primary = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2) ax2primary = plt.subplot2grid((4,3), (2,0), colspan=3, sharex=ax1primary) ax3primary = plt.subplot2grid((4,3), (3,0), colspan=3, sharex=ax1primary) ax1primary.plot(t,s1) ax1primary.set_yticks(np.arange(-0.9, 1.0, 0.3)) ax1primary.xaxis.grid(color='green') ax2primary.plot(t[:150],s2[:150]) ax2primary.set_yticks(np.arange(0.3, 1, 0.2)) ax2primary.xaxis.grid(color='green') ax3primary.plot(t[30:],s3[30:]) ax3primary.plot([0,2],[0.2,0.2],'m') ax3primary.set_yticks(np.arange(-0.4, 0.7, 0.2)) ax3primary.xaxis.grid(color='green') INDEX = t[np.where(abs(s3-0.2) &lt; 0.005)[0]] INDEX = np.append(INDEX, LAST) INDEX = np.insert(INDEX, 0, FIRST) ax1secondary = ax1primary.twiny() ax1secondary.set_xticks(INDEX) ax1secondary.xaxis.grid(color='red') ax2secondary = ax2primary.twiny() ax2secondary.set_xticks(INDEX) ax2secondary.xaxis.grid(color='red') ax3secondary = ax3primary.twiny() ax3secondary.set_xticks(INDEX) ax3secondary.xaxis.grid(color='red') plt.tight_layout() plt.subplots_adjust(hspace=0) for ax in [ax1primary, ax2primary, ax2secondary, ax3secondary]: plt.setp(ax.get_xticklabels(), visible=False) ############################################################################### plt.show() </code></pre> <p>On a static figure there is no issue. The problem becomes obvious when you start panning (or zooming) one of the subplots. The primary (green) axis stays perfectly in sync and moves within all subplots, but the secondary (red) axis gets misaligned and moves only within the active subplot.</p> <p>Is there a way to fix this?</p> <hr> <p>The behavior that I want to achieve is following:</p> <p>I need one common "primary" x-axis (for all three subplots) with the ticks on the bottom of the figure and another common "secondary" x-axis (for all three subplots) with the ticks on the top of the figure. The primary axis is a standard regularly spaced axis, while the secondary axis shows the customized ticks (for example zero crossings) <strong>This is all satisfied in the example above. Now I need it to be satisfied also while panning and zooming subplots.</strong></p>
1
2016-09-25T19:44:10Z
39,721,415
<p>Unfortunately the proposed callback solution is not robust enough. Most of the time panning works fine, but zooming is a disaster. Still, too often the grids get misaligned. </p> <p>Until I find out how to improve the callback solution, I decided to code a custom grid and annotate the values within the plot.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt FIRST = 0.0 LAST = 2.0 STEP = 0.01 t = np.arange(FIRST, LAST, STEP) s1 = np.sin(2*np.pi*t) s2 = np.exp(-t) s3 = s1*s2 ############################################################################### plt.rc('axes', grid=True) plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) fig3 = plt.figure() ax1primary = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2) ax2primary = plt.subplot2grid((4,3), (2,0), colspan=3, sharex=ax1primary) ax3primary = plt.subplot2grid((4,3), (3,0), colspan=3, sharex=ax1primary) ax1primary.plot(t,s1) ax1primary.set_yticks(np.arange(-0.9, 1.0, 0.3)) ax1primary.xaxis.grid(color='green') ax1primary.set_ylim(-1, 1) ax2primary.plot(t[:150],s2[:150]) ax2primary.set_yticks(np.arange(0.3, 1, 0.2)) ax2primary.xaxis.grid(color='green') ax2primary.set_ylim(0.2, 1) ax3primary.plot(t[30:],s3[30:]) ax3primary.plot([0,2],[0.2,0.2],'m') ax3primary.set_yticks(np.arange(-0.4, 0.7, 0.2)) ax3primary.xaxis.grid(color='green') ax3primary.set_ylim(-0.6, 0.8) INDEX = np.where(abs(s3-0.2) &lt; 0.005)[0] for i in range(0, len(INDEX)): ax1primary.annotate(t[INDEX[i]], xy=(t[INDEX[i]], 0)) ax1primary.plot([t[INDEX], t[INDEX]], [-1e9 * np.ones(len(INDEX)), 1e9 * np.ones(len(INDEX))], 'r') ax2primary.plot([t[INDEX], t[INDEX]], [-1e9 * np.ones(len(INDEX)), 1e9 * np.ones(len(INDEX))], 'r') ax3primary.plot([t[INDEX], t[INDEX]], [-1e9 * np.ones(len(INDEX)), 1e9 * np.ones(len(INDEX))], 'r') plt.tight_layout() plt.subplots_adjust(hspace=0) for ax in [ax1primary, ax2primary]: plt.setp(ax.get_xticklabels(), visible=False) ############################################################################### plt.show() </code></pre>
0
2016-09-27T09:46:51Z
[ "python", "matplotlib" ]
scipy ndimage to fill array for matplotlib interpolated data
39,691,152
<p>I have an array of data representing what might look like a topographic map when plotted using a contour map. I am looking to expand the array to 'interpolate' data between points at a user-selected interval and then fill the missing elements with mean values between the existing data points. For example:</p> <pre><code>Original Array: [[1 2 3] [4 5 6] [7 8 9]] with 1X expansion becomes: [[1 . 2 . 3] [. . . . .] [4 . 5 . 6] [. . . . .] [7 . 8 . 9]] </code></pre> <p>and the filled in '.' values would be the mean of those values in the data point region. I understand that there are a number of ways to do something like this with scipy.ndimage filters, but it seems they all alter the original data values, i.e. gaussian_filter and ndimage.zoom.</p> <p>I wonder if there is a filter that I'm missing that would expand this data array and retain the original values in their expanded positions and fill in the missing points with the 'interpolated' mean values? If someone could point me in the right direction, I'll check it out, but all my searching and testing haven't yielded the results I'm looking for yet.</p> <p>Here's a sample of the applicable code this is coming from. The original x, y, and z values come from arrays created from a sql result on a mysql database, I've tried 'order' variations from 0 to 5, all the listed modes I could find, and prefilter on and off. I've also tried a number of options using the gaussian_filter as well. The interpolation value is a number between 1 and 10 passed from user input:</p> <pre><code>x=np.array(self.lon) y=np.array(self.lat) z=np.array(self.plotdata) if (int(interpolation)&gt;0): x=scipy.ndimage.zoom(x, int(interpolation), order=0, mode='nearest', prefilter=True) y=scipy.ndimage.zoom(y, int(interpolation), order=0, mode='nearest', prefilter=True) z=scipy.ndimage.zoom(z, int(interpolation), order=0, mode='nearest', prefilter=True) </code></pre> <p>TIA</p>
0
2016-09-25T19:49:44Z
39,692,541
<p>I was doing something similar and had issues with ndimage.zoom. It was skewing the images and I was never happy with the results. I found skimage.transform.resize. This worked much better and might be useful for you. </p> <p><a href="http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.resize" rel="nofollow">http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.resize</a></p>
0
2016-09-25T22:47:07Z
[ "python", "numpy", "matplotlib", "scipy" ]
How can I add an outline to an image?
39,691,158
<p>I'm fairly new to Python, and I have a python function that adds an outline to an image. However, the function currently adds the outline one pixel inside the image, instead of on the outside like it should. How can I modify this to make the outline further out by 1 pixel?</p> <pre><code>def addOutline(imageArray): from statistics import mean newAr = imageArray newAr.flags.writeable = True balance = 250 for i0 in range(1,len(newAr)): for i in range(1,len(newAr[i0])): if mean(newAr[i0][i][:3]) &gt; balance and mean(newAr[i0][i-1][:3]) &lt; balance: newAr[i0][i-1][:3] = 40 if mean(newAr[i0][i][:3]) &lt; balance and mean(newAr[i0][i-1][:3]) &gt; balance: newAr[i0][i][:3] = 40 if mean(newAr[i0][i][:3]) &lt; balance and mean(newAr[i0-1][i][:3]) &gt; balance: newAr[i0][i][:3] = 40 if mean(newAr[i0][i][:3]) &lt; balance and mean(newAr[i0+1][i][:3]) &gt; balance: newAr[i0][i][:3] = 40 return newAr </code></pre>
0
2016-09-25T19:50:11Z
39,691,227
<p>I guess if you really want the outline to be outside the figure. You need to create a new image array with size <code>(len(newAr)+1)*(len(newAr[0]+1))</code>, where the extra pixel is to put your line. All the other pixels inside should be copied from your original image. </p>
3
2016-09-25T19:58:22Z
[ "python", "image", "python-3.x", "pillow" ]
Pandas GroupBy Doesn't Persist After Applying Quantiles?
39,691,164
<p>I'm trying to get quantiles for two distinct groups in a Pandas df. I'm able to apply to quantiles function and get a table with grouped results, however, I can't seem to call the groupby attributes on the dataframe after doing so. Example:</p> <pre><code>rand = np.random.RandomState(1) df = pd.DataFrame({'A': ['foo', 'bar'] * 3, 'B': rand.randn(6), 'C': rand.randint(0, 20, 6)}) gb = df.groupby(['A']) gb.groups </code></pre> <p>This returns something like:</p> <pre><code>{'bar': [1, 3, 5], 'foo': [0, 2, 4]} </code></pre> <p>Then I apply the quantile function:</p> <pre><code>q=gb.quantile(np.arange(0,1.1,.1)) </code></pre> <p>When I print this df, it shows the two groups, but when I try to call them, it throws an error:</p> <pre><code>q.group AttributeError: 'DataFrame' object has no attribute 'group' </code></pre> <p>How can I call the groups in the quantile dataframe?</p>
2
2016-09-25T19:51:11Z
39,691,213
<p>(First, note that your code is missing</p> <pre><code>import numpy as np import numpy.random as rand </code></pre> <p>or something like that. The second one is a bit annoying to guess.)</p> <p>Your two lines </p> <pre><code>gb = df.groupby(['A']) q=gb.quantile(np.arange(0,1.1,.1)) </code></pre> <p>Are equivalent to </p> <pre><code>q=df.groupby(['A']).quantile(np.arange(0,1.1,.1)) </code></pre> <p>In other words, <code>q</code> is already the <em>result</em> of applying the quantile on each group. The result you're looking for is <code>q</code> itself:</p> <pre><code>&gt;&gt;&gt; q B C A bar 0.0 -1.311556 13.0 0.1 -1.188745 13.2 0.2 -1.065935 13.4 0.3 -0.943124 13.6 0.4 -0.820313 13.8 0.5 -0.697503 14.0 0.6 -0.662497 14.4 0.7 -0.627492 14.8 0.8 -0.592486 15.2 0.9 -0.557481 15.6 1.0 -0.522475 16.0 foo 0.0 0.032946 1.0 0.1 0.051352 4.0 0.2 0.069759 7.0 0.3 0.088166 10.0 0.4 0.106572 13.0 0.5 0.124979 16.0 0.6 0.388895 16.2 0.7 0.652811 16.4 0.8 0.916728 16.6 0.9 1.180644 16.8 1.0 1.444560 17.0 </code></pre>
2
2016-09-25T19:56:51Z
[ "python", "pandas" ]
Pandas GroupBy Doesn't Persist After Applying Quantiles?
39,691,164
<p>I'm trying to get quantiles for two distinct groups in a Pandas df. I'm able to apply to quantiles function and get a table with grouped results, however, I can't seem to call the groupby attributes on the dataframe after doing so. Example:</p> <pre><code>rand = np.random.RandomState(1) df = pd.DataFrame({'A': ['foo', 'bar'] * 3, 'B': rand.randn(6), 'C': rand.randint(0, 20, 6)}) gb = df.groupby(['A']) gb.groups </code></pre> <p>This returns something like:</p> <pre><code>{'bar': [1, 3, 5], 'foo': [0, 2, 4]} </code></pre> <p>Then I apply the quantile function:</p> <pre><code>q=gb.quantile(np.arange(0,1.1,.1)) </code></pre> <p>When I print this df, it shows the two groups, but when I try to call them, it throws an error:</p> <pre><code>q.group AttributeError: 'DataFrame' object has no attribute 'group' </code></pre> <p>How can I call the groups in the quantile dataframe?</p>
2
2016-09-25T19:51:11Z
39,694,401
<p>You can call specific groups using the index:</p> <pre><code>q.loc['foo'] </code></pre>
0
2016-09-26T03:45:09Z
[ "python", "pandas" ]
Display a matrix with putting a common factor in sympy
39,691,325
<p>I want to display a matrix with putting an extracted common factor on outside of the matrix after matrix calculation in sympy.</p> <p>I wrote below code.</p> <pre><code>from sympy import * a = symbols("a") b = symbols("b") A = Matrix([exp(I*a),exp(I*a)*exp(I*b)]) print simplify(A) </code></pre> <p>I got below output.</p> <pre><code>Matrix([ [ exp(I*a)], [exp(I*(a + b))]]) </code></pre> <p>However, I want to get below output.</p> <pre><code>exp(I*a)*Matrix([ [ 1], [exp(I*b)]]) </code></pre> <p>I tried collect(A,exp(I*a)) and got follow error.</p> <pre><code>Traceback (most recent call last): File "&lt;ipython-input-65-834f4c326df4&gt;", line 1, in &lt;module&gt; runfile('C:/Anaconda2/Programs/test/untitled44.py', wdir='C:/Anaconda2/Programs/test') File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Anaconda2/Programs/test/untitled44.py", line 14, in &lt;module&gt; collect(A,exp(I*a)) File "C:\Anaconda2\lib\site-packages\sympy\simplify\simplify.py", line 451, in collect if expr.is_Mul: File "C:\Anaconda2\lib\site-packages\sympy\matrices\matrices.py", line 3084, in __getattr__ "%s has no attribute %s." % (self.__class__.__name__, attr)) AttributeError: MutableDenseMatrix has no attribute is_Mul. </code></pre> <p>I know a way to extract a common factor for a element of a matrix like follow link. <a href="https://github.com/sympy/sympy/issues/8442" rel="nofollow">https://github.com/sympy/sympy/issues/8442</a></p> <p>But it's not my desire.</p> <p>How should I do?</p>
1
2016-09-25T20:08:23Z
39,692,039
<p>I do not think <code>Sympy</code> provides a function for the task you want. However, you can do this manually, as per the method proposed in the accepted answer of a similar question asked in the Mathematica SE (<a href="http://mathematica.stackexchange.com/questions/44500/factor-a-vector">link</a>). </p> <p>The idea is to extract the common factor of the polynomial elements via <code>gcd</code> and then use <code>MatMul</code> with the <code>evaluate=False</code> option in order to restrict <code>Sympy</code> from performing the scalar-matrix multiplication.</p> <pre><code>import sympy as sp a, b = sp.symbols('a, b') A = sp.Matrix([sp.exp(sp.I * a), sp.exp(sp.I * a) * sp.exp(sp.I * b)]) g = sp.gcd(tuple(A)) A_v2 = sp.MatMul(g,(A/g),evaluate = False) print(A_v2) </code></pre> <blockquote> <pre><code>exp(I*a)*Matrix([ [ 1], [exp(I*b)]]) </code></pre> </blockquote>
1
2016-09-25T21:30:53Z
[ "python", "matrix", "sympy", "symbolic-math" ]
How to convert a nltk tree (Stanford) into newick format in python?
39,691,327
<p>I have this Stanford tree and I want to convert this into newick format.</p> <pre><code> (ROOT (S (NP (DT A) (NN friend)) (VP (VBZ comes) (NP (NP (JJ early)) (, ,) (NP (NP (NNS others)) (SBAR (WHADVP (WRB when)) (S (NP (PRP they)) (VP (VBP have) (NP (NN time)))))))))) </code></pre>
1
2016-09-25T20:08:37Z
39,691,651
<p>There might be ways to do this just using string processing, but I would parse them and print them in the newick format recursively. A somewhat minimal implementation:</p> <pre><code>import re class Tree(object): def __init__(self, label): self.label = label self.children = [] @staticmethod def _tokenize(string): return list(reversed(re.findall(r'\(|\)|[^ \n\t()]+', string))) @classmethod def from_string(cls, string): tokens = cls._tokenize(string) return cls._tree(tokens) @classmethod def _tree(cls, tokens): t = tokens.pop() if t == '(': tree = cls(tokens.pop()) for subtree in cls._trees(tokens): tree.children.append(subtree) return tree else: return cls(t) @classmethod def _trees(cls, tokens): while True: if not tokens: raise StopIteration if tokens[-1] == ')': tokens.pop() raise StopIteration yield cls._tree(tokens) def to_newick(self): if self.children and len(self.children) == 1: return ','.join(child.to_newick() for child in self.children) elif self.chilren: return '(' + ','.join(child.to_newick() for child in self.children) + ')' else: return self.label </code></pre> <p>Note that, of course, information gets lost during the conversion, since only terminal nodes are kept. Usage:</p> <pre><code>&gt;&gt;&gt; s = """(ROOT (...""" &gt;&gt;&gt; Tree.from_string(s).to_newick() ... </code></pre>
0
2016-09-25T20:43:28Z
[ "python", "tree", "nltk" ]
Finding correct path to files in subfolders with os.walk with python?
39,691,504
<p>I am trying to create a program that copies files with certain file extension to the given folder. When files are located in subfolders instead of the root folder the program fails to get correct path. In its current state the program works perfectly for the files in the root folder, but it crashes when it finds matching items in subfolders. The program tries to use rootfolder as directory instead of the correct subfolder.</p> <p>My code is as follows</p> <pre><code># Selective_copy.py walks through file tree and copies files with # certain extension to give folder import shutil import os import re # Deciding the folders and extensions to be targeted # TODO: user input instead of static values extension = "zip" source_folder = "/Users/viliheikkila/documents/kooditreeni/" destination_folder = "/Users/viliheikkila/documents/test" def Selective_copy(source_folder): # create regex to identify file extensions mo = re.compile(r"(\w+).(\w+)") # Group(2) represents the file extension for dirpath, dirnames, filenames in os.walk(source_folder): for i in filenames: if mo.search(i).group(2) == extension: file_path = os.path.abspath(i) print("Copying from " + file_path + " to " + destination_folder) shutil.copy(file_path, destination_folder) Selective_copy(source_folder) </code></pre>
0
2016-09-25T20:26:41Z
39,691,532
<p><code>dirpath</code> is one of the things provided by <code>walk</code> for a reason: it gives the path to the directory that the items in <code>files</code> is located in. You can use that to determine the subfolder you should be using.</p>
1
2016-09-25T20:30:52Z
[ "python", "os.walk" ]
Finding correct path to files in subfolders with os.walk with python?
39,691,504
<p>I am trying to create a program that copies files with certain file extension to the given folder. When files are located in subfolders instead of the root folder the program fails to get correct path. In its current state the program works perfectly for the files in the root folder, but it crashes when it finds matching items in subfolders. The program tries to use rootfolder as directory instead of the correct subfolder.</p> <p>My code is as follows</p> <pre><code># Selective_copy.py walks through file tree and copies files with # certain extension to give folder import shutil import os import re # Deciding the folders and extensions to be targeted # TODO: user input instead of static values extension = "zip" source_folder = "/Users/viliheikkila/documents/kooditreeni/" destination_folder = "/Users/viliheikkila/documents/test" def Selective_copy(source_folder): # create regex to identify file extensions mo = re.compile(r"(\w+).(\w+)") # Group(2) represents the file extension for dirpath, dirnames, filenames in os.walk(source_folder): for i in filenames: if mo.search(i).group(2) == extension: file_path = os.path.abspath(i) print("Copying from " + file_path + " to " + destination_folder) shutil.copy(file_path, destination_folder) Selective_copy(source_folder) </code></pre>
0
2016-09-25T20:26:41Z
39,691,701
<pre><code>file_path = os.path.abspath(i) </code></pre> <p>This line is blatantly wrong. Keep in mind that <code>filenames</code> keeps list of base file names. At this point it's just a list of strings and (technically) they are not associated at all with files in filesystem.</p> <p><a href="https://docs.python.org/3.5/library/os.path.html#os.path.abspath" rel="nofollow"><code>os.path.abspath</code> does string-only operations and attempts to merge file name with current working dir</a>. As a result, merged filename points to file that <strong>does not exist</strong>.</p> <p>What should be done is merge between <code>root</code> and base file name (both values yield from <code>os.walk</code>):</p> <pre><code>file_path = os.path.abspath(dirpath, i) </code></pre>
0
2016-09-25T20:48:20Z
[ "python", "os.walk" ]
Sublime Text 3 subl command not working in windows 10
39,691,547
<p>when I run the subl command, it just pauses for a moment and doesn't give me any feedback as to what happened and doesn't open. I am currently on windows 10 running the latest sublime text 3 build. I already copied my subl.exe from my sublime text 3 directory to my system32 directory. What am I missing? I've tried subl.exe ., subl.exe detect.py, subl, subl.exe</p> <p>Please help me with this setup</p>
-1
2016-09-25T20:31:50Z
39,713,501
<p>I'm assuming that when you invoke <code>subl.exe</code> via an absolute path then it works.</p> <pre><code>&gt; "C:\Program Files\Sublime Text 3\subl.exe" </code></pre> <p>Assuming the above works, then the location of <code>subl.exe</code> can be added to the system path so that there is no need to specify the absolute path.</p> <p>Go to <code>Control Panel &gt; System and Security &gt; System &gt; Advanced system settings</code> and add <code>C:\Program Files\Sublime Text 3</code> to the <code>PATH</code> environment variable.</p> <p>Check that the <code>PATH</code> variable does not already contain the path to <code>subl.exe</code> so to avoid adding it twice.</p> <p>You essentially are going to append <code>;C:\Program Files\Sublime Text 3</code> to the <code>PATH</code> variable. <em>Note the <code>;</code> which is a path separator.</em> </p> <p><strong>You may need to restart Windows for the change to take effect.</strong></p> <p>See <a href="http://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them">What are PATH and other environment variables, and how can I set or use them?</a> for in depth information on <code>PATH</code> and other environment variables in general.</p>
0
2016-09-26T22:41:34Z
[ "python", "command-line", "sublimetext3", "sublimetext" ]
Python 3.4 tkinter, not clearing frame after selecting a option from a menu
39,691,619
<p>This is a little program I made to find the area of different quadrilaterals, when I select a option from the drop down menu it works. But when I switch from let's say square to trapezium, I get this:</p> <p><img src="http://i.stack.imgur.com/qROin.png" alt="2"></p> <p>I want to clear the window leaving only the selected option.</p> <p><strong>Here is the code:</strong></p> <pre><code>from tkinter import * def square(): ment = IntVar() def mhello(): mtext = ment.get() mtext *= 2 mlabel2 = Label(mGui, text=mtext).pack() mlabel = Label(mGui, text="Square").pack() mbutton = Button(mGui, text= "Submit", command = mhello). pack() nEntry = Entry(mGui, textvariable=ment).pack() def rectangle(): oneMent = IntVar() twoMent = IntVar() def mhello(): oneMtext = oneMent.get() twoMtext = twoMent.get() mtext = 0 mtext = oneMtext * twoMtext mlabel2 = Label(mGui, text=mtext).pack() mlabel = Label(mGui, text="Rectangle/Parallelogram").pack() mbutton = Button(mGui, text= "Submit", command = mhello). pack() oneEntry = Entry(mGui, textvariable=oneMent).pack() twoEntry = Entry(mGui, textvariable=twoMent).pack() def trapezium(): oneMent = IntVar() twoMent = IntVar() threeMent = IntVar() def mhello(): oneMtext = oneMent.get() twoMtext = twoMent.get() threeMtext = threeMent.get() mtext = 0 mtext = oneMtext + twoMtext mtext /= 2 mtext *= threeMtext mlabel2 = Label(mGui, text=mtext).pack() mlabel = Label(mGui, text="Trapezium").pack() mbutton = Button(mGui, text= "Submit", command = mhello). pack() oneEntry = Entry(mGui, textvariable=oneMent).pack() twoEntry = Entry(mGui, textvariable=twoMent).pack() threeEntry = Entry(mGui, textvariable=threeMent).pack() def rhombus(): oneMent = IntVar() twoMent = IntVar() def mhello(): oneMtext = oneMent.get() twoMtext = twoMent.get() mtext = 0 mtext = oneMtext * twoMtext mtext /= 2 mlabel2 = Label(mGui, text=mtext).pack() mlabel = Label(mGui, text="Rhombus").pack() mbutton = Button(mGui, text= "Submit", command = mhello). pack() oneEntry = Entry(mGui, textvariable=oneMent).pack() twoEntry = Entry(mGui, textvariable=twoMent).pack() def restart(): mGui.destroy() mGui = Tk() mGui.geometry("450x450+500+300") mGui.title("Square Area Finder") mHomeLabel = Label(mGui, text="Use the drop down menu to select the quadrilateral you want to find the area of.").pack() menu = Menu(mGui) mGui.config(menu=menu) file =Menu(menu) file.add_command(label="Square", command=square) file.add_command(label="Rectangle/Parallelogram", command=rectangle) file.add_command(label="Trapezium", command=trapezium) file.add_command(label="Rhombus", command=rhombus) file.add_separator() file.add_command(label="Quit", command=restart) menu.add_cascade(label="Options", menu=file) mGui.mainloop() </code></pre> <p>Thank you to anyone that can help. </p>
0
2016-09-25T20:39:56Z
39,691,829
<p>When a different option from the drop down menu is selected you need to delete what you had before, then create the new widgets</p> <p>In each of your functions where you make a shape, you need to first destroy the widgets, then create the new ones</p> <p><strong>I have fixed the code:</strong></p> <pre><code>from tkinter import * global widgets # this list will contain widgets to be deleted widgets = [] def square(): global widgets for widget in widgets[:]: widget.destroy() widgets.remove(widget) ment = IntVar() def mhello(): mtext = ment.get() mtext *= 2 mlabel2 = Label(mGui, text=mtext) mlabel = Label(mGui, text="Square") mbutton = Button(mGui, text= "Submit", command = mhello) nEntry = Entry(mGui, textvariable=ment) widgets = widgets[:] + [mlabel, mbutton, nEntry] # destroy these later for widget in widgets: widget.pack() # pack them afterwards def rectangle(): global widgets for widget in widgets[:]: widget.destroy() widgets.remove(widget) oneMent = IntVar() twoMent = IntVar() def mhello(): oneMtext = oneMent.get() twoMtext = twoMent.get() mtext = 0 mtext = oneMtext * twoMtext mlabel2 = Label(mGui, text=mtext).pack() mlabel = Label(mGui, text="Rectangle/Parallelogram") mbutton = Button(mGui, text= "Submit", command = mhello) oneEntry = Entry(mGui, textvariable=oneMent) twoEntry = Entry(mGui, textvariable=twoMent) widgets = widgets + [mlabel, mbutton, oneEntry, twoEntry] # destroy these later for widget in widgets: widget.pack() # pack them afterwards def trapezium(): global widgets for widget in widgets[:]: widget.destroy() widgets.remove(widget) oneMent = IntVar() twoMent = IntVar() threeMent = IntVar() def mhello(): oneMtext = oneMent.get() twoMtext = twoMent.get() threeMtext = threeMent.get() mtext = 0 mtext = oneMtext + twoMtext mtext /= 2 mtext *= threeMtext mlabel2 = Label(mGui, text=mtext).pack() mlabel = Label(mGui, text="Trapezium") mbutton = Button(mGui, text= "Submit", command = mhello) oneEntry = Entry(mGui, textvariable=oneMent) twoEntry = Entry(mGui, textvariable=twoMent) threeEntry = Entry(mGui, textvariable=threeMent) widgets = widgets + [mlabel, mbutton, oneEntry, twoEntry, threeEntry] # destroy these later for widget in widgets: widget.pack() # pack them afterwards def rhombus(): global widgets for widget in widgets[:]: widget.destroy() widgets.remove(widget) oneMent = IntVar() twoMent = IntVar() def mhello(): oneMtext = oneMent.get() twoMtext = twoMent.get() mtext = 0 mtext = oneMtext * twoMtext mtext /= 2 mlabel2 = Label(mGui, text=mtext).pack() mlabel = Label(mGui, text="Rhombus") mbutton = Button(mGui, text= "Submit", command = mhello) oneEntry = Entry(mGui, textvariable=oneMent) twoEntry = Entry(mGui, textvariable=twoMent) widgets = widgets + [mlabel, mbutton, oneEntry, twoEntry] # destroy these later for widget in widgets: widget.pack() # pack them afterwards def restart(): mGui.destroy() mGui = Tk() mGui.geometry("450x450+500+300") mGui.title("Square Area Finder") mHomeLabel = Label(mGui, text="Use the drop down menu to select the quadrilateral you want to find the area of.").pack() menu = Menu(mGui) mGui.config(menu=menu) file =Menu(menu) file.add_command(label="Square", command=square) file.add_command(label="Rectangle/Parallelogram", command=rectangle) file.add_command(label="Trapezium", command=trapezium) file.add_command(label="Rhombus", command=rhombus) file.add_separator() file.add_command(label="Quit", command=restart) menu.add_cascade(label="Options", menu=file) mGui.mainloop() </code></pre> <p>This code works but it could be a lot shorter and more efficient</p> <p>Its good practice to put similar code into one separate function instead of copying it 4 times</p>
1
2016-09-25T21:05:00Z
[ "python", "tkinter" ]
Unicode encoding in email
39,691,628
<p>I have manually created and sent myself an html email in gmail. I want to be able to reuse this html output to programatically send it (using smtplib in python).</p> <p>In gmail, I view the source, which appears like:</p> <blockquote> <p>Mime-Version: 1.0 Content-Type: multipart/alternative; boundary="--==_mimepart_57daadsdas2e101427152ee"; charset=UTF-8 ----==_mimepart_57daadsdas2e101427152ee Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable</p> <p><strong>Hi all !</strong> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D</p> <p>Venez d=C3=A9couvrir</p> </blockquote> <p>My problem is that when I then try to send this content as html programatically, it's not displayed correctly. I suspect it's because of unicode conversion. I can't convert back for example the characters "d=C3=A9couvrir" to what it should be: "découvrir".</p> <p>Could anyone help?</p>
0
2016-09-25T20:40:52Z
39,692,888
<p>There's are some <a href="https://docs.python.org/2/library/email-examples.html#email-examples" rel="nofollow">MIME examples</a> that are probably more suitable, but the simple answer from the headers is that it is UTF8 and <code>quoted-printable</code> encoding, so you can use the <code>quopri</code> module:</p> <pre><code>&gt;&gt;&gt; quopri.decodestring('Venez d=C3=A9couvrir').decode('utf8') 'Venez découvrir' </code></pre>
1
2016-09-25T23:42:27Z
[ "python", "unicode", "unicode-string" ]
python recursion class variable
39,691,636
<p>Let me rewrite my question so that it is clearer. I encountered a issue on LeetCode problem: validate binary search tree. </p> <p>My first solution looks something like this:</p> <pre><code>class Solution(object): def recursion(self, input, var_x, ans): #update var_x #update ans self.recursion(input, var_x, ans) def mySolution(self, input): ans = [] var_x = 0 self.recursion(input, var_x, ans) return ans </code></pre> <p>This solution fails to pass the test. But after I made a simple change, it passes:</p> <pre><code>class Solution(object): def recursion(self, input, ans): #update self.var_x #update ans self.recursion(input, ans) def mySolution(self, input): ans = [] self.var_x = 0 self.recursion(input, ans) return ans </code></pre> <p>What is the difference that declare var_x versus self.var_x? I think these two has the same effect in this problem, but one passes the test the other doesn't?</p>
-2
2016-09-25T20:41:30Z
39,708,182
<p>The semantic difference is simple: <strong>var_x</strong> is merely a local variable, one per call instance. <strong>self.var_x</strong> is an attribute of the object, one per class instance.</p> <p>If you need the value only within the one call instance, use <strong>var_x</strong> and don't bother the objects with storing the transient value. If you need it as a long-term object property (attribute), then use <strong>self.var_x</strong>.</p>
0
2016-09-26T16:47:30Z
[ "python", "recursion", "binary-search-tree", "inorder" ]
Possible starting letters of uuid4() in Python
39,691,654
<p>I'm using uuid4() to generate random names for my files. However, I need to know the possible starting letters for these files. Can the uuid4()'s only start with [a-z,A-Z,0-9] or can they also include punctuation characters like [_-,]? I cannot find a reference for this.</p>
-2
2016-09-25T20:43:47Z
39,691,687
<p>I'm guessing you are using hex and so it would be 0-f. </p> <p>Otherwise from the spec it is: UUID.hex The UUID as a 32-character hexadecimal string.</p> <p>UUID.int The UUID as a 128-bit integer.</p> <p>UUID.urn The UUID as a URN as specified in RFC 4122.</p> <p>Ref -> <a href="https://www.ietf.org/rfc/rfc4122.txt" rel="nofollow">https://www.ietf.org/rfc/rfc4122.txt</a></p>
1
2016-09-25T20:47:13Z
[ "python" ]
Resampling timeseries with a given timedelta
39,691,671
<p>I am using Pandas to structure and process Data. This is my DataFrame:</p> <p><a href="http://i.stack.imgur.com/wDHTC.png" rel="nofollow"><img src="http://i.stack.imgur.com/wDHTC.png" alt="enter image description here"></a></p> <p>I want to do a resampling of time-series data, and have, for every ID (named here "3"), all bitrate scores, from beginning to end (beginning_time / end_time). For exemple, for the first row, I want to have all seconds, from 2016-07-08 02:17:42 to 2016-07-08 02:17:55, with the same bitrate score, and the same ID of course. Something like this :</p> <p>For example, given :</p> <pre><code>df = pd.DataFrame( {'Id' : ['CODI126640013.ts', 'CODI126622312.ts'], 'beginning_time':['2016-07-08 02:17:42', '2016-07-08 02:05:35'], 'end_time' :['2016-07-08 02:17:55', '2016-07-08 02:26:11'], 'bitrate': ['3750000', '3750000']}) </code></pre> <p>which gives :</p> <p><a href="http://i.stack.imgur.com/N0h0A.png" rel="nofollow"><img src="http://i.stack.imgur.com/N0h0A.png" alt="enter image description here"></a></p> <p>And I want to have for the first row :</p> <p><a href="http://i.stack.imgur.com/ZQemx.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZQemx.png" alt="enter image description here"></a></p> <p>Same thing for the secend row.. So the objectif is to resample the deltaTime between the beginning and the end times, the bitrate score must be the same of course.</p> <p>I'm trying this code:</p> <pre><code>df['new_beginning_time'] = pd.to_datetime(df['beginning_time']) df.set_index('new_beginning_time').groupby('Id', group_keys=False).apply(lambda df: df.resample('S').ffill()).reset_index() </code></pre> <p>But in this context, it didn't work ! Any ideas ? Thank you very much !</p>
0
2016-09-25T20:45:58Z
39,692,605
<p>This should do the trick</p> <pre><code>all = [] for row in df.itertuples(): time_range = pd.date_range(row.beginning_time, row.end_time, freq='1S') all += (zip(time_range, [row.Id]*len(time_range), [row.bitrate]*len(time_range))) pd.DataFrame(all) In[209]: pd.DataFrame(all) Out[209]: 0 1 2 0 2016-07-08 02:17:42 CODI126640013.ts 3750000 1 2016-07-08 02:17:43 CODI126640013.ts 3750000 2 2016-07-08 02:17:44 CODI126640013.ts 3750000 3 2016-07-08 02:17:45 CODI126640013.ts 3750000 4 2016-07-08 02:17:46 CODI126640013.ts 3750000 5 2016-07-08 02:17:47 CODI126640013.ts 3750000 6 2016-07-08 02:17:48 CODI126640013.ts 3750000 7 2016-07-08 02:17:49 CODI126640013.ts 3750000 </code></pre> <p>edit: I am using python 2.7, python 3 as a different zip() </p>
1
2016-09-25T22:58:31Z
[ "python", "datetime", "pandas", "group-by", "resampling" ]
Resampling timeseries with a given timedelta
39,691,671
<p>I am using Pandas to structure and process Data. This is my DataFrame:</p> <p><a href="http://i.stack.imgur.com/wDHTC.png" rel="nofollow"><img src="http://i.stack.imgur.com/wDHTC.png" alt="enter image description here"></a></p> <p>I want to do a resampling of time-series data, and have, for every ID (named here "3"), all bitrate scores, from beginning to end (beginning_time / end_time). For exemple, for the first row, I want to have all seconds, from 2016-07-08 02:17:42 to 2016-07-08 02:17:55, with the same bitrate score, and the same ID of course. Something like this :</p> <p>For example, given :</p> <pre><code>df = pd.DataFrame( {'Id' : ['CODI126640013.ts', 'CODI126622312.ts'], 'beginning_time':['2016-07-08 02:17:42', '2016-07-08 02:05:35'], 'end_time' :['2016-07-08 02:17:55', '2016-07-08 02:26:11'], 'bitrate': ['3750000', '3750000']}) </code></pre> <p>which gives :</p> <p><a href="http://i.stack.imgur.com/N0h0A.png" rel="nofollow"><img src="http://i.stack.imgur.com/N0h0A.png" alt="enter image description here"></a></p> <p>And I want to have for the first row :</p> <p><a href="http://i.stack.imgur.com/ZQemx.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZQemx.png" alt="enter image description here"></a></p> <p>Same thing for the secend row.. So the objectif is to resample the deltaTime between the beginning and the end times, the bitrate score must be the same of course.</p> <p>I'm trying this code:</p> <pre><code>df['new_beginning_time'] = pd.to_datetime(df['beginning_time']) df.set_index('new_beginning_time').groupby('Id', group_keys=False).apply(lambda df: df.resample('S').ffill()).reset_index() </code></pre> <p>But in this context, it didn't work ! Any ideas ? Thank you very much !</p>
0
2016-09-25T20:45:58Z
39,697,742
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#groupby-syntax-with-window-and-resample-operations" rel="nofollow"><code>resample</code> - 0.18.1 version of pandas</a>:</p> <pre><code>df.beginning_time = pd.to_datetime(df.beginning_time) df.end_time = pd.to_datetime(df.end_time) df = pd.melt(df, id_vars=['Id','bitrate'], value_name='dates').drop('variable', axis=1) df.set_index('dates', inplace=True) print(df) Id bitrate dates 2016-07-08 02:17:42 CODI126640013.ts 3750000 2016-07-08 02:05:35 CODI126622312.ts 3750000 2016-07-08 02:17:55 CODI126640013.ts 3750000 2016-07-08 02:26:11 CODI126622312.ts 3750000 print (df.groupby('Id').resample('1S').ffill()) Id bitrate Id dates CODI126622312.ts 2016-07-08 02:05:35 CODI126622312.ts 3750000 2016-07-08 02:05:36 CODI126622312.ts 3750000 2016-07-08 02:05:37 CODI126622312.ts 3750000 2016-07-08 02:05:38 CODI126622312.ts 3750000 2016-07-08 02:05:39 CODI126622312.ts 3750000 2016-07-08 02:05:40 CODI126622312.ts 3750000 2016-07-08 02:05:41 CODI126622312.ts 3750000 2016-07-08 02:05:42 CODI126622312.ts 3750000 2016-07-08 02:05:43 CODI126622312.ts 3750000 2016-07-08 02:05:44 CODI126622312.ts 3750000 2016-07-08 02:05:45 CODI126622312.ts 3750000 2016-07-08 02:05:46 CODI126622312.ts 3750000 2016-07-08 02:05:47 CODI126622312.ts 3750000 ... ... </code></pre>
1
2016-09-26T08:12:40Z
[ "python", "datetime", "pandas", "group-by", "resampling" ]
Proper model defination in django for a widget manager
39,691,679
<p>I have a model called <code>widgetManager</code> and 2 widget models called <code>emailWidget</code> and <code>TextWidget</code>. Now a single instance of widgetManager can have multiple instances of emailWidget and TextWidget. How can this be achieved with the following in mind</p> <ol> <li>Till now i only have two but there can be more in future</li> <li>The order of widget is very important</li> </ol> <p>I have tried with adding two many-many relations in widgetManager but that seems impractical and not the best way to go around because if first condition.</p> <p>What i have in mind is maybe i can somehow make a base widget class and extend all the widgets from that class but i am not sure about that. Would be super helpful if someone can point me in the right direction. Thanks in advance. </p>
0
2016-09-25T20:46:20Z
39,692,799
<p>If I understood your description correctly, you want a relationship where there can be many emailWidget or TextWidget for one instance of widgetManager. </p> <p>What you can do in this case is add a ForeignKey field for widgetManager to emailWidget and TextWidget. This way, you can have many instances of the widgets while they refer to the same manager.</p> <p>I think you may have confused inheritance with model relationships when you said you want to extend widgets from a base class. Perhaps I'm wrong? </p> <p>Not sure what you mean't about order of the widget being important either..</p>
0
2016-09-25T23:28:14Z
[ "python", "django", "django-models" ]
How to write nth value of list into csv file
39,691,707
<p>i have the following list :</p> <pre><code>sec_min=['37', '01', '37', '02', '37', '03', '37', '04', '37', '05',....] </code></pre> <p>i want to store this list into CVS file in following format:</p> <pre><code>37,01 37,02 37,03 37,04 ... and so on </code></pre> <p>this is what i coded:</p> <pre><code>with open('datas.csv','w')as f: data=csv.writer(f) for value in sec_min: data.writerow(sec_min[:2]) </code></pre> <p>(i.e. every two elements of list in new row)</p>
-1
2016-09-25T20:48:56Z
39,691,782
<p>compose a "matrix" of row length = 2, and write all the rows at once in a generator comprehension</p> <pre><code>with open('datas.csv','wb') as f: # python 2 with open('datas.csv','w',newline='') as f: # python 3 data=csv.writer(f) data.writerows(sec_min[l:l+2] for l in range(0,len(sec_min),2)) </code></pre> <p>note the different way of opening a file for csv module whether you're running python 2 or python 3.</p> <p>Your original method results in blank lines every other line because of extra <code>\r</code> chars.</p>
1
2016-09-25T20:58:21Z
[ "python" ]
AlterField on auto generated _ptr field in migration causes FieldError
39,691,785
<p>I have two models:</p> <pre><code># app1 class ParentModel(models.Model): # some fields </code></pre> <p>Now, in another app, I have child model:</p> <pre><code># app2 from app1.models import ParentModel class ChildModel(ParentModel): # some fields here too </code></pre> <p>In initial migration for <code>app2</code> django creates <code>OneToOneField</code> with <code>parent_link=True</code> named <code>parentmodel_ptr</code>.</p> <p>Now I want to change this auto generated field to let's say <code>IntegerField</code>, so I create new migration with this operations:</p> <pre><code>class Migration(migrations.Migration): dependencies = [ ('app2', '0001_initial'), ] operations = [ migrations.AlterField( 'childmodel', 'parentmodel_ptr', models.IntegerField(null=True, blank=True) ) ] </code></pre> <p>Trying to migrate, I got an exception </p> <pre><code>django.core.exceptions.FieldError: Auto-generated field 'parentmodel_ptr' in class 'ChildModel' for parent_link to base class 'ParentModel' clashes with declared field of the same name. </code></pre> <p>So is that even possible to make it somehow?</p>
0
2016-09-25T20:59:08Z
39,692,180
<p>If your code supports it, you could just change the parent class to an abstract class and have all the fields in the child model. However, if you still do need the parent object separately, then I don't think you can change the Django OneToOne link without some serious hacking (not recommended). </p> <p>If you only need the relation and don't need the methods, etc. then you could remove the inheritance and go with a self-created either OneToOneField or an IntegerField that holds the ForeignKey to that other object. You could elaborate the question with your end goal, so it would be simpler to offer real solutions rather than theories.</p>
1
2016-09-25T21:50:06Z
[ "python", "django", "database-migration" ]
Counting phrases in Python using NLTK
39,691,816
<p>I am trying to get a phrase count from a text file but so far I am only able to obtain a word count (see below). I need to extend this logic to count the number of times a two-word phrase appears in the text file. </p> <p>Phrases can be defined/grouped by using logic from NLTK from my understanding. I believe the collections function is what I need to obtain the desired result, but I'm not sure how to go about implementing it from reading the NLTK documentation. Any tips/help would be greatly appreciated. </p> <pre><code>import re import string frequency = {} document_text = open('Words.txt', 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) for word in match_pattern: count = frequency.get(word,0) frequency[word] = count + 1 frequency_list = frequency.keys() for words in frequency_list: print (words, frequency[words]) </code></pre>
0
2016-09-25T21:03:28Z
39,692,750
<p>You can get all the two word phrases using the <code>collocations</code> module. This tool identifies words that often appear consecutively within corpora.</p> <p>To find the two word phrases you need to first calculate the frequencies of words and their appearance in the context of other words. NLTK has a <code>BigramCollocationFinder</code> class that can do this. Here's how we can find the Bigram Collocations:</p> <pre><code>import re import string import nltk from nltk.tokenize import word_tokenize, sent_tokenize from nltk.collocations import BigramCollocationFinder, BigramAssocMeasures frequency = {} document_text = open('Words.txt', 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) finder = BigramCollocationFinder.from_words(match_pattern) bigram_measures = nltk.collocations.BigramAssocMeasures() print(finder.nbest(bigram_measures.pmi, 2)) </code></pre> <p>NLTK Collocations Docs: <a href="http://www.nltk.org/api/nltk.html?highlight=collocation#module-nltk.collocations" rel="nofollow">http://www.nltk.org/api/nltk.html?highlight=collocation#module-nltk.collocations</a></p>
0
2016-09-25T23:21:51Z
[ "python", "nltk", "word-count", "phrase" ]
Counting phrases in Python using NLTK
39,691,816
<p>I am trying to get a phrase count from a text file but so far I am only able to obtain a word count (see below). I need to extend this logic to count the number of times a two-word phrase appears in the text file. </p> <p>Phrases can be defined/grouped by using logic from NLTK from my understanding. I believe the collections function is what I need to obtain the desired result, but I'm not sure how to go about implementing it from reading the NLTK documentation. Any tips/help would be greatly appreciated. </p> <pre><code>import re import string frequency = {} document_text = open('Words.txt', 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) for word in match_pattern: count = frequency.get(word,0) frequency[word] = count + 1 frequency_list = frequency.keys() for words in frequency_list: print (words, frequency[words]) </code></pre>
0
2016-09-25T21:03:28Z
39,695,415
<p><code>nltk.brigrams</code> returns a pair of words and their frequency in an specific text. Try this:</p> <pre><code>import nltk from nltk import bigrams document_text = open('Words.txt', 'r') text_string = document_text.read().lower() tokens = word_tokenize(text_string) result = bigrams(tokens) </code></pre> <p>Output:</p> <pre><code>[(('w1', 'w2'), 6), (('w3', 'w4'), 3), (('w5', 'w6'), 3), (('w7', 'w8'), 3)...] </code></pre>
0
2016-09-26T05:43:39Z
[ "python", "nltk", "word-count", "phrase" ]
Itertools Chain on Nested List
39,691,830
<p>I have two lists combined sequentially to create a nested list with python's map and zip funcionality; however, I wish to recreate this with itertools. </p> <p>Furthermore, I am trying to understand why itertools.chain is returning a flattened list when I insert two lists, but when I add a nested list it simply returns the nested list. </p> <p>Any help on these two issues would be greatly appreciated. </p> <pre><code>from itertools import chain a = [0,1,2,3] b = [4,5,6,7] #how can I produce this with itertools? c = list(map(list, zip(a,b))) print(c) #[[0, 4], [1, 5], [2, 6], [3, 7]] d = list(chain(c)) print(d) #[[0, 4], [1, 5], [2, 6], [3, 7]] d = list(chain(a,b)) print(d) #[0, 1, 2, 3, 4, 5, 6, 7] </code></pre>
0
2016-09-25T21:05:04Z
39,692,054
<p>I'll try to answer your questions as best I can.</p> <p>First off, <code>itertools.chain</code> doesn't work the way you think it does. <code>chain</code> takes <code>x</code> number of iterables and iterates over them in sequence. When you call <code>chain</code>, it essentially (internally) packs the objects into a list:</p> <pre><code>chain("ABC", "DEF") # Internally creates ["ABC", "DEF"] </code></pre> <p>Inside the method, it accesses each of these items one at a time, and iterates through them:</p> <pre><code>for iter_item in arguments: for item in iter_item: yield item </code></pre> <p>So when you call <code>chain([[a,b],[c,d,e],[f,g]])</code>, it creates a list with <em>one iterable object:</em> the list you passed as an argument. So now it looks like this:</p> <pre><code>[ #outer [ #inner [a,b], [c,d,e], [f,g] ] ] </code></pre> <p><code>chain</code> as such iterates over the <strong>inner</strong> list, and returns three elements: <code>[a,b]</code>, <code>[c,d,e]</code>, and <code>[f,g]</code> in order. Then they get repacked by <code>list</code>, giving you what you had in the first place.</p> <p>Incidentally, there is a way to do what you want to: <code>chain.from_iterable</code>. This is an alternate constructor for <code>chain</code> which accepts a single iterable, such as your list, and pulls the elements out to iterate over. So instead of this:</p> <pre><code># chain(l) [ #outer [ #inner [a,b], [c,d,e], [f,g] ] ] </code></pre> <p>You get this:</p> <pre><code># chain.from_iterable(l) [ [a,b], [c,d,e], [f,g] ] </code></pre> <p>This will iterate through the three sub-lists, and return them in one sequence, so <code>list(chain.from_iterable(l))</code> will return <code>[a,b,c,d,e,f,g]</code>.</p> <p>As for your second question: While I don't know why <code>itertools</code> is a necessity to this process, you can do this in Python 2.x:</p> <p><code>list(itertools.izip(x,y))</code></p> <p>However, in 3.x, the <code>izip</code> function has been removed. There is still <code>zip_longest</code>, which will match up as many pairs as it can, and accept a filler value for extra pairs: <code>list(zip_longest([a,b,c],[d,e,f,g,h],fillvalue="N"))</code> returns <code>[(a,d),(b,e),(c,f),(N,g),(N,h)]</code> since the second list is longer than the first. Normal <code>zip</code> will take the shortest iterable and cut off the rest.</p> <p>In other words, unless you want <code>zip_longest</code> instead of <code>zip</code>, <code>itertools</code> does not have a built-in method for zipping.</p>
0
2016-09-25T21:32:14Z
[ "python", "python-3.x" ]
From Raw binary image data to PNG in Python
39,691,936
<p>After searching for a few hours, I ended up on <a href="http://stackoverflow.com/questions/32946436/read-img-medical-image-without-header-in-python">this</a> link. A little background information follows.</p> <p>I'm capturing live frames of a running embedded device via a hardware debugger. The captured frames are stored as <a href="http://pasted.co/a60277d7" rel="nofollow">raw binary file</a>s, without headers or format. After looking at the above link and understanding, albeit perfunctorily, the NumPY and Matplotlib, I was able to convert the raw binary data to an image successfully. This is important because I'm not sure if the link to the raw binary file will help any one.</p> <p>I use this code:</p> <pre><code>import matplotlib.pyplot as plt # study documentation import numpy as np # " " iFile = "FramebufferL0_0.bin" # Layer-A shape = (430, 430) # length and width of the image dtype = np.dtype('&lt;u2') # unsigned 16 bit little-endian. oFile = "FramebufferL0_0.png" fid = open(iFile, 'rb') data = np.fromfile(fid, dtype) image = data.reshape(shape) plt.imshow(image, cmap = "gray") plt.savefig(oFile) plt.show() </code></pre> <p>Now, the image I'm showing is black and white because the color map is gray-scale (right?). The actual captured frame is NOT black and white. That is, the image I see on my embedded device is "colorful".</p> <p>My question is, how can I calculate actual color of each pixel from the raw binary file? Is there a way I can get the actual color map of the image from the raw binary? I looked into <a href="http://matplotlib.org/examples/pylab_examples/custom_cmap.html" rel="nofollow">this</a> example and I'm sure that, if I'm able to calculate the R, G and B channels (and Alpha too), I'll be able to recreate the exact image. An example code would be of much help.</p>
2
2016-09-25T21:17:38Z
39,692,784
<p>An RGBA image has 4 channels, one for each color and one for the alpha value. The binary file seems to have a single channel, as you don't report an error when performing the <code>data.reshape(shape)</code> operation (the shape for the corresponding RGBA image would be (430, 430, 4)). I see two potential reasons:</p> <ol> <li><p>The image actual does have colour information but when you are grabbing the data you are only grabbing one of the four channels.</p></li> <li><p>The image is actually a gray-scale image, but the embedded device shows a pseudocolor image, creating the illusion of colour information. Without knowing what the colourmap is being used, it is hard to help you, other than point you towards <code>matplotlib.pyplot.colormaps()</code>, which lists all already available colour maps in matplotlib.</p></li> </ol> <p>Could you </p> <p>a) explain the exact source / type of imaging modality, and </p> <p>b) show a photo of the output of the embedded device?</p> <p>PS: Also, at least in my hands, the pasted binary file seems to have a size of 122629, which is incongruent with an image shape of (430,430).</p>
2
2016-09-25T23:26:21Z
[ "python", "numpy", "matplotlib" ]
python POST request issue
39,691,962
<p>I am trying to get the title and the link of every article from <a href="https://latercera.com/resultadoBusqueda.html?q=enersis" rel="nofollow">this site</a>.</p> <p>The data of interest is loaded with javascript after some time in json response.</p> <pre><code> var ltcom = 'TEFURVJDRVJB'; var ltpapaer = 'TFRQQVBFUg=='; var bender = new Canela.tool.Bender('searchBox',ltcom, { replaceImg: 'http://resource.latercera.com/2015/css/img/bx_loader.gif', objectId: 'contentId', hl: 'abstract', taxonomyId: '24', ajaxTpl: true, targets: { rowsContainer: 'result', pageContainer: 'pages', resumeContainer: 'resume' }, parameters: { type: 'CONTENT', fq: 'taxonomyId:24 AND status:2 AND launchDate:[2008-05-31T23:59:59.999Z TO NOW]', sort: 'launchDate desc', rows: 15 }, templates: { rowTpl: '/index/tpl/rowTpl.html', rowContainerTpl: '/index/tpl/rowContainerTpl.html', pageTpl: '/index/tpl/pageTpl.html', pageContainerTpl: '/index/tpl/pageContainerTpl.html', resumeTpl: '/index/tpl/resumeTpl.html' } </code></pre> <p>I tried using selenium approach, but with no success.</p> <p>Current code:</p> <pre><code>import requests url="http://www.latercera.com/app/application" data= { 'action':'searchSolr', 'type':'CONTENT', 'siteCode':'TEFURVJDRVJB', 'fq':'taxonomyId:24 AND status:2 AND launchDate:[2008-05-31T23:59:59.999Z TO NOW]', 'indent':'on', 'wt':'json', 'qt':'default', 'sort':'launchDate desc', 'start':'0', 'rows':'15', 'q':'enersis' } print (requests.get(url, data=data).text) </code></pre> <p>requests.get(url, data=data) spits out 200.</p> <p>Is there a need to use some header info? How should I move forward with this? Thanks in advance!</p>
1
2016-09-25T21:21:09Z
39,692,546
<p>You need a <em>Referer</em> header:</p> <pre><code>headers = {"Referer": "http://www.latercera.com/resultadoBusqueda.html?q=enersis"} data = {"type": 'CONTENT', "fq": 'taxonomyId:24 AND status:2 AND launchDate:[2008-05-31T23:59:59.999Z TO NOW]', "sort": 'launchDate desc', "rows": 15, "siteCode": 'TEFURVJDRVJB', "q": "enersis", "action": "searchSolr"} r = (requests.post("http://www.latercera.com/app/application", data=data,headers=headers)) print(r) print(r.content) </code></pre> <p>Which gives you all the data in xml format which we can parse with bs4:</p> <pre><code>soup = BeautifulSoup(r.content, "xml") print [(s.text, s.parent.select_one("arr[name=url]").text) for s in soup.select("arr[name=n_title]")] </code></pre> <p>That returns:</p> <pre><code>[(u'Las advertencias de la SEC al proceso de fusi\xf3n que Enel impulsa en Enersis', u'/noticia/negocios/2016/09/655-697979-9-las-advertencias-de-la-sec-al-proceso-de-fusion-que-enel-impulsa-en-enersis.shtml'), (u'Enersis Am\xe9ricas aclar\xf3 mejor\xeda en precio de OPA', u'/noticia/negocios/2016/09/655-695035-9-enersis-americas-aclaro-mejoria-en-precio-de-opa.shtml'), (u'Enersis Am\xe9ricas mejora precio de OPA y fija fecha en proceso de fusi\xf3n de activos', u'/noticia/negocios/2016/09/655-694868-9-enersis-americas-mejora-precio-de-opa-y-fija-fecha-en-proceso-de-fusion-de.shtml/noticia/portada/2016/09/653-694868-9-enersis-americas-mejora-precio-de-opa-y-fija-fecha-en-proceso-de-fusion-de.shtml'), (u'Nicola Cotugno, gerente general Enersis Chile: "queremos mantener el liderazgo, #7;pero no s\xf3lo con nueva capacidad"', u'/noticia/negocios/2016/08/655-694297-9-nicola-cotugno-gerente-general-enersis-chile-queremos-mantener-el-liderazgo-pero.shtml'), (u'El buen momento de las firmas chilenas en la bolsa de EE.UU.', u'/noticia/negocios/2016/08/655-692187-9-el-buen-momento-de-las-firmas-chilenas-en-la-bolsa-de--eeuu.shtml/noticia/portada/2016/08/653-692187-9-el-buen-momento-de-las-firmas-chilenas-en-la-bolsa-de--eeuu.shtml'), (u'Estiman en US$ 145 millones el costo en que incurrir\xe1 Enersis Am\xe9ricas por fusi\xf3n', u'/noticia/negocios/2016/08/655-691649-9-estiman-en-us-145-millones-el-costo-en-que-incurrira-enersis-americas-por-fusion.shtml/noticia/portada/2016/08/653-691649-9-estiman-en-us-145-millones-el-costo-en-que-incurrira-enersis-americas-por-fusion.shtml'), (u'Los pasos que seguir\xe1 el cambio de imagen de Enersis', u'/noticia/negocios/2016/08/655-691378-9-los-pasos-que-seguira-el-cambio-de-imagen-de-enersis.shtml/noticia/portada/2016/08/653-691378-9-los-pasos-que-seguira-el-cambio-de-imagen-de-enersis.shtml'), (u'Enersis, Endesa y Chilectra cambiar\xedan de nombre para unificarse bajo marca Enel', u'/noticia/negocios/2016/08/655-691270-9-enersis-endesa-y-chilectra-cambiarian-de-nombre-para-unificarse-bajo-marca-enel.shtml'), (u'El nuevo dilema de Enel: sepultar #7;las marcas Enersis, Endesa y Chilectra', u'/noticia/negocios/2016/07/655-690896-9-el-nuevo-dilema-de-enel-sepultar-las-marcas-enersis-endesa-y-chilectra.shtml'), (u'SVS niega m\xe1s plazo a Enersis Am\xe9ricas para fusi\xf3n y complica a el\xe9ctrica en EE.UU.', u'/noticia/negocios/2016/07/655-687234-9-svs-niega-mas-plazo-a-enersis-americas-para-fusion-y-complica-a-electrica-en.shtml/noticia/portada/2016/07/653-687234-9-svs-niega-mas-plazo-a-enersis-americas-para-fusion-y-complica-a-electrica-en.shtml'), (u'Rafael Fern\xe1ndez: CMPC #7;tiene un buen compliance y colusi\xf3n fue un "accidente"', u'/noticia/negocios/2016/06/655-685371-9-rafael-fernandez-cmpc-tiene-un-buen-compliance-y-colusion-fue-un-accidente.shtml/noticia/portada/2016/06/653-685371-9-rafael-fernandez-cmpc-tiene-un-buen-compliance-y-colusion-fue-un-accidente.shtml'), (u'The Panama Papers: las sociedades que Mossack Fonseca cre\xf3 para los protagonistas del "Caso Chispas"', u'/noticia/nacional/2016/05/680-679986-9-the-panama-papers-las-sociedades-que-mossack-fonseca-creo-para-los-protagonistas.shtml/noticia/portada/2016/05/653-679986-9-the-panama-papers-las-sociedades-que-mossack-fonseca-creo-para-los-protagonistas.shtml/noticia/despliegue/canal/epigrafe-destacado-rojo/2016/05/3032-679986-9-the-panama-papers-las-sociedades-que-mossack-fonseca-creo-para-los-protagonistas.shtml/noticia/despliegue/home/epigrafe-destacado-rojo/2016/05/3038-679986-9-the-panama-papers-las-sociedades-que-mossack-fonseca-creo-para-los-protagonistas.shtml'), (u'Enersis Am\xe9ricas inicia proceso de fusi\xf3n con Endesa Am\xe9ricas y Chilectra Am\xe9ricas', u'/noticia/negocios/2016/05/655-679596-9-enersis-americas-inicia-proceso-de-fusion-con-endesa-americas-y-chilectra.shtml'), (u'Herman Chadwick Pi\xf1era es elegido como nuevo presidente de Enersis Chile', u'/noticia/negocios/2016/04/655-678650-9-herman-chadwick-pinera-es-elegido-como-nuevo-presidente-de-enersis-chile.shtml/noticia/portada/2016/04/653-678650-9-herman-chadwick-pinera-es-elegido-como-nuevo-presidente-de-enersis-chile.shtml'), (u'Daniel Fern\xe1ndez deja Enersis tras fin de primera etapa en proceso de reestructuraci\xf3n', u'/noticia/negocios/2016/04/655-678440-9-daniel-fernandez-deja-el-cargo-de-country-manager-de-enersis.shtml/noticia/tamano-contenedor/home/col9/2016/04/3057-678440-9-daniel-fernandez-deja-el-cargo-de-country-manager-de-enersis.shtml/noticia/portada/2016/04/653-678440-9-daniel-fernandez-deja-el-cargo-de-country-manager-de-enersis.shtml')] </code></pre>
0
2016-09-25T22:47:55Z
[ "python", "python-requests" ]
pandas assign value based on mean
39,692,099
<p>Let's say I have a dataframe column. I want to create a new column where the value for a given observation is 1 if the corresponding value in the old column is above average. But the value should be 0 if the value in the other column is average or below. </p> <p>What's the fastest way of doing this?</p>
0
2016-09-25T21:38:42Z
39,692,150
<p>Say you have the following DataFrame:</p> <pre><code>df = pd.DataFrame({'A': [1, 4, 6, 2, 8, 3, 7, 1, 5]}) df['A'].mean() Out: 4.111111111111111 </code></pre> <p>Comparison against the mean will get you a boolean vector. You can cast that to integer:</p> <pre><code>df['B'] = (df['A'] &gt; df['A'].mean()).astype(int) </code></pre> <p>or use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">np.where</a>:</p> <pre><code>df['B'] = np.where(df['A'] &gt; df['A'].mean(), 1, 0) df Out: A B 0 1 0 1 4 0 2 6 1 3 2 0 4 8 1 5 3 0 6 7 1 7 1 0 8 5 1 </code></pre>
3
2016-09-25T21:46:52Z
[ "python", "pandas" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' return letter </code></pre> <p><strong><em>this btw didnt work at all and i really dont get the "def" command since its not mentioned again? No errors</em></strong></p> <p>Anyway, here is my new modified code from what i have been learning from books and online...</p> <pre><code>score = float(input("What is your score")) if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' print (letter) input ("Press Enter to Exit") </code></pre> <p><strong><em>This code doesnt work either, but at least it is asking for user input now. No errors</em></strong></p> <p>What am i missing here?</p>
-1
2016-09-25T21:55:28Z
39,692,252
<p>Since you are a noobie, let me give you a few tips. </p> <p>1: SO is hostile to easily google-able things</p> <p>If you google "python def" you'll see that it's the keyword for defining a function. What's a function? <em>google</em>. Oh, a function is a block of code that can be called multiple times.</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' return letter print(letterGrade(95)) # A print(letterGrade(70)) # C print(letterGrade(20)) # F </code></pre> <p>2: "else" and "if" can be combined in python:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' elif score &gt;= 80: # grade must be B, C, D or F letter = 'B' elif score &gt;= 70: # grade must be C, D or F letter = 'C' elif score &gt;= 60: # grade must D or F letter = 'D' else: letter = 'F' return letter </code></pre>
-1
2016-09-25T22:00:34Z
[ "python" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' return letter </code></pre> <p><strong><em>this btw didnt work at all and i really dont get the "def" command since its not mentioned again? No errors</em></strong></p> <p>Anyway, here is my new modified code from what i have been learning from books and online...</p> <pre><code>score = float(input("What is your score")) if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' print (letter) input ("Press Enter to Exit") </code></pre> <p><strong><em>This code doesnt work either, but at least it is asking for user input now. No errors</em></strong></p> <p>What am i missing here?</p>
-1
2016-09-25T21:55:28Z
39,692,444
<p>The <code>def</code> keyword introduces a function. In order for your script to work interactively, can you call the <code>letterGrade</code> function like this:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' return letter if __name__ == '__main__': score = float(input("What is your score? ")) print letterGrade(score) input ("Press Enter to Exit") </code></pre> <p>Here, the <code>__name__ == '__main__':</code> block will be executed when you invoke your script from the command line (<code>python your_script_name.py</code>)</p>
1
2016-09-25T22:32:29Z
[ "python" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' return letter </code></pre> <p><strong><em>this btw didnt work at all and i really dont get the "def" command since its not mentioned again? No errors</em></strong></p> <p>Anyway, here is my new modified code from what i have been learning from books and online...</p> <pre><code>score = float(input("What is your score")) if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' print (letter) input ("Press Enter to Exit") </code></pre> <p><strong><em>This code doesnt work either, but at least it is asking for user input now. No errors</em></strong></p> <p>What am i missing here?</p>
-1
2016-09-25T21:55:28Z
39,692,504
<p>Ok let's first start with some pseudo code, I always try to pseudo code my problems and draw them out as much as possible, it helps me and it might help you. So the grading scale you seem to have implemented is something like this. If you have a grade lower than 100 but greater than or equal to 90 it is an A, lower than 90 but greater than or equal to an 80 it is a b, so on and so on. Let's use conditional statements for this. You can nest it like you had, but setting up the order of conditions may be what you need. So if the grade is not greater than or equal to 90, then the grade can only be lower than 90, thus a B, C, D or F.</p> <pre><code>if (grade &gt;= 90): letter = 'A' elif (grade &gt;= 80): letter = 'B' elif (grade &gt;= 70) letter = 'C' elif (grade &gt;= 60) letter = 'D' else: letter = 'F' </code></pre> <p>So with these conditional statements we go through the process of finding the grade, as explained a bit above the code, if the user does not have a grade greater than 90, it hops to the next elif which checks if it is greater than or equal to 80, so on and so on, if grade at one point not greater than or equal to 60, then all other values lower than 60 will be an F.</p> <p>Now to cover 'def'. You use def to define a function. Here is a generic layout:</p> <pre><code>def functioname(parameters, parameters): stuffgoeshere </code></pre> <p>Now, the parameters are optional, it all depends if you need to pass any data to the function, in your case, you are passing the grade of the user:</p> <pre><code>def gradeLetter(grade): if (grade &gt;= 90): return 'A' elif (grade &gt;= 80): return 'B' elif (grade &gt;= 70) return 'C' elif (grade &gt;= 60) return 'D' else: return 'F' </code></pre> <p>At this point you can call the function, passing in the value the user typed in. We return the character in the function, so that you can assign it to a variable to print it, or you can just print it within the function, whichever is your preference.</p> <pre><code>g = input("Please enter your grade: ") l = gradeLetter(g) print("Your letter grade is " + l) </code></pre> <p>Hope this helps you out. If you have any questions feel free to comment below. </p>
1
2016-09-25T22:42:37Z
[ "python" ]
Problems with my first python script
39,692,217
<p>I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.</p> <p>Here is the original code:</p> <pre><code>def letterGrade(score): if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' return letter </code></pre> <p><strong><em>this btw didnt work at all and i really dont get the "def" command since its not mentioned again? No errors</em></strong></p> <p>Anyway, here is my new modified code from what i have been learning from books and online...</p> <pre><code>score = float(input("What is your score")) if score &gt;= 90: letter = 'A' else: # grade must be B, C, D or F if score &gt;= 80: letter = 'B' else: # grade must be C, D or F if score &gt;= 70: letter = 'C' else: # grade must D or F if score &gt;= 60: letter = 'D' else: letter = 'F' print (letter) input ("Press Enter to Exit") </code></pre> <p><strong><em>This code doesnt work either, but at least it is asking for user input now. No errors</em></strong></p> <p>What am i missing here?</p>
-1
2016-09-25T21:55:28Z
39,694,567
<p>Omg hoooooooooooly crap! I need to apologize for wasting everyone's time. RPGillespie was correct, my code was working this entire time. Im new to using PyCharm and for some reason its set up in a way that you can be doing code at the top for one project, but actually "running" the code for a different project at the bottom. Iv been running the wrong code this entire time...day wasted!!! =(</p> <p>I will say that i wont be making that mistake anymore. Geez, what a fiasco!!!</p> <p>Thanks again for EVERYONE'S help and warm welcome. I will admit that as i am new to this forum, i am not new to forums in general. And its nice to not get eaten alive for asking a "noob" question or not knowing the un spoken rules of said forum. Its nice to find a place that actually tries to help its members.</p> <p>My sincerest apologies again, i promise my next problem/question wont be wasting this forums time =).</p> <p>iv undoubtedly earned the badge of "DOH" and "Facepalm".</p>
0
2016-09-26T04:07:02Z
[ "python" ]
Drawing multiple shapes at a time from a list of options (Python Turtle Graphics)?
39,692,334
<p>So, first of all, here's the requirements:</p> <ol> <li>user picks 3 shapes from a list of 6;</li> <li>user chooses size, fill color, and line color;</li> <li>user cannot pick the same shape twice</li> <li>shapes should be drawn evenly spaced, taking up 1/3 of the screen each</li> </ol> <p>Here's my code so far:</p> <pre><code>import turtle turtle = turtle.Screen() def circle(): def triangle(): def square(): def pentagon(): def hexagon(): def heptagon(): for list in ["1.Circle","2.Triangle","3.Square","4.Pentagon","5.Hexagon","6.Heptagon"]: print(list) shape1 = input("Choose one number from the following:") if shape1 == "1": for list in ["2.Triangle","3.Square","4.Pentagon","5.Hexagon","6.Heptagon"]: print(list) shape2 = input("Choose one number from the following:") if shape2 == "2": elif shape2 == "3": elif shape2 == "4": elif shape2 == "5": elif shape2 == "6": else: print("Incorrect input. Please try again.") if shape1 == "2": if shape1 == "3": if shape1 == "4": if shape1 == "5": if shape1 == "6": else: print("Incorrect input. Please try again.") </code></pre> <p>Basically, I'm terribly confused. The only way I can find to draw three shapes in a row of the user's choosing is to do every possible outcome - 123, 124, 125, 126, 132, 134...etc etc, which would take forever, look horrible, and then I would have to write the turtle commands each time. As you can see, I tried playing around with def, but in my smaller test code it didn't work at all, so I'm not sure I understand it correctly either.</p> <p>In addition to all of that, how would I ensure that all of the shapes or where they should be? The only way I can see it is to write separate code for each outcome with different "goto"s.</p> <p>Is there a way to have the user put all three options at once ("123", "231", etc) and then for the program to go through each number and draw it in turn? Is there a way to assign each number to a set of code drawing the shape? I'm pretty new at all of this. I appreciate any help you can give me. Thank you!</p>
0
2016-09-25T22:12:47Z
39,692,994
<p>Below is an example framework that prompts the user from (a diminishing) list of shapes, divides the canvas and draws them. It only implements circles, you need to fill in the other shapes, and it's far from finished code, you need to add error checking and other finishing touches:</p> <pre><code>import turtle CANVAS_WIDTH = 900 CANVAS_HEIGHT = 600 CHROME_WIDTH = 30 # allow for window borders, title bar, etc. SHAPE_CHOICES = 3 def circle(bounds): turtle.penup() center_x = bounds['x'] + bounds['width'] // 2 bottom_y = bounds['y'] turtle.setposition(center_x, bottom_y) turtle.pendown() turtle.circle(min(bounds['width'], bounds['height']) // 2) def triangle(bounds): circle(bounds) def square(bounds): circle(bounds) def pentagon(bounds): circle(bounds) def hexagon(bounds): circle(bounds) def heptagon(bounds): circle(bounds) DESCRIPTION, FUNCTION = 0, 1 shapes = [("Circle", circle), ("Triangle", triangle), ("Square", square), ("Hexagon", hexagon), ("Heptagon", heptagon)] choices = [] turtle.setup(CANVAS_WIDTH + CHROME_WIDTH, CANVAS_HEIGHT + CHROME_WIDTH) for _ in range(SHAPE_CHOICES): for i, (description, function) in enumerate(shapes): print("{}. {}".format(i + 1, description)) choice = int(input("Choose one number from the above: ")) - 1 choices.append(shapes[choice][FUNCTION]) del shapes[choice] x, y = -CANVAS_WIDTH // 2, -CANVAS_HEIGHT // 2 width, height = CANVAS_WIDTH // SHAPE_CHOICES, CANVAS_HEIGHT // SHAPE_CHOICES # I'm dividing the screen into thirds both horizontally and vertically bounds = dict(x=x, y=y, width=width, height=height) for choice in choices: choice(bounds) bounds['x'] += width bounds['y'] += height turtle.done() </code></pre>
0
2016-09-25T23:58:44Z
[ "python", "turtle-graphics" ]
Slicing Cross-section of 2D NumPy array
39,692,351
<p>I'm looking to print a cross-section of a numpy array. I am looking to pull the first 15 rows and only data from the 5th index column.</p> <pre><code>import csv as csv import numpy as np csv_file_object = open('train.csv', 'rU') header = next(csv_file_object) data = [] for row in csv_file_object: data.append(row) data = np.array(data) print(data[0:15,5]) </code></pre> <p>When I run the above code, I receive the following error: IndexError: too many indices for array.</p> <p>Running the code without adding the column filter works as expected. The csv file is a 12x892 (x,y) dataset.</p>
0
2016-09-25T22:14:58Z
39,692,430
<p>The <code>csv_file_object</code> is a file object contains all lines of your csv file without splitting. You have to use <code>csv</code> module to read them properly:</p> <pre><code>with open('train.csv', 'rU') as csv_file_object: reader = csv.DictReader(csv_file_object) data = np.array([row.values() for row in reader]) </code></pre> <p>But since you want to convert them to a numpy array you better to use <code>genfromtxt</code> function:</p> <pre><code>data = np.genfromtxt('train.csv') </code></pre> <p>You can pass arguments like <code>dtype</code>, <code>delimiter</code> and <code>names</code> (a boolean for keeping the headers).</p>
0
2016-09-25T22:29:54Z
[ "python", "arrays", "numpy", "indices" ]
Slicing Cross-section of 2D NumPy array
39,692,351
<p>I'm looking to print a cross-section of a numpy array. I am looking to pull the first 15 rows and only data from the 5th index column.</p> <pre><code>import csv as csv import numpy as np csv_file_object = open('train.csv', 'rU') header = next(csv_file_object) data = [] for row in csv_file_object: data.append(row) data = np.array(data) print(data[0:15,5]) </code></pre> <p>When I run the above code, I receive the following error: IndexError: too many indices for array.</p> <p>Running the code without adding the column filter works as expected. The csv file is a 12x892 (x,y) dataset.</p>
0
2016-09-25T22:14:58Z
39,692,734
<p>UPDATE: I did not call csv.reader() prior to opening the file</p> <pre><code>import csv as csv import numpy as np csv_file_object = csv.reader(open('train.csv', 'rU')) header = next(csv_file_object) data = [] for row in csv_file_object: data.append(row) data = np.array(data) print(data.shape) print(data[0:15,5]) </code></pre>
0
2016-09-25T23:19:24Z
[ "python", "arrays", "numpy", "indices" ]
Altering dictionaries/keys in Python
39,692,480
<p>I have ran the code below in Python to generate a list of words and their count from a text file. How would I go about filtering out words from my "frequency_list" variable that only have a count of 1? </p> <p>In addition, how would I export the print statement loop at the bottom to a CSV</p> <p>Thanks in advance for any help provided.</p> <pre><code>import re import string frequency = {} document_text = open('Words.txt', 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) for word in match_pattern: count = frequency.get(word,0) frequency[word] = count + 1 frequency_list = frequency.keys() for words in frequency_list: print (words, frequency[words]) </code></pre>
1
2016-09-25T22:39:06Z
39,692,759
<p>For the first part - you can use dict comprehension:</p> <p><code>frequency = {k:v for k,v in frequency.items() if v&gt;1}</code></p>
1
2016-09-25T23:22:34Z
[ "python", "dictionary", "export-to-csv" ]
Altering dictionaries/keys in Python
39,692,480
<p>I have ran the code below in Python to generate a list of words and their count from a text file. How would I go about filtering out words from my "frequency_list" variable that only have a count of 1? </p> <p>In addition, how would I export the print statement loop at the bottom to a CSV</p> <p>Thanks in advance for any help provided.</p> <pre><code>import re import string frequency = {} document_text = open('Words.txt', 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) for word in match_pattern: count = frequency.get(word,0) frequency[word] = count + 1 frequency_list = frequency.keys() for words in frequency_list: print (words, frequency[words]) </code></pre>
1
2016-09-25T22:39:06Z
39,693,023
<p>To filter out words, an alternative way would be:</p> <pre><code>frequency = dict(filter(lambda (k,v): v&gt;1, frequency.items())) </code></pre> <p>To export the print statement loop at the bottom to a CSV, you could do that:</p> <pre><code>import csv frequency_list = ['word1','word2','word3'] # example with open('output.csv','w') as csvfile: writer = csv.writer(csvfile, delimiter=",") writer.writerow(frequency_list) </code></pre> <p>This will generate an 'output.csv' file with the words from your frequency_list in <em>one row</em>. </p> <p>To get <em>a row for each word</em> try, the following:</p> <pre><code>with open('output.csv','w') as csvfile: writer = csv.writer(csvfile, delimiter=",") writer.writerows([i.strip() for i in l.split(',')] for l in frequency_list) </code></pre> <blockquote> <p>Update</p> </blockquote> <p>To get a csv with the counters, keep your initial dictionary and do the following:</p> <pre><code>frequency = {"one":1,"two":2,"three":3} #example with open('output.csv', 'w') as csvfile: writer = csv.writer(csvfile) for key, value in frequency.items(): writer.writerow([key, value]) </code></pre>
1
2016-09-26T00:03:54Z
[ "python", "dictionary", "export-to-csv" ]
Am I using the isalpha() method in my while loop correctly (Python)?
39,692,515
<p>I want to allow the user to construct an argument using premises (sentences that support your argument) and a conclusion. I want the program to raise a question (yes/no) if the user wants to add an additional premises after the first one. If yes --> premises: ____, If no --> Conclusion: ____. The problem is that i can write no for the additional premises question (or anything) and it'd take that input and make another premises. </p> <p>Thank you in advance for any help!</p> <pre><code>print("Welcome to the argument-validity test!") def premises_conclusion(): premises_1 = raw_input("Premises: ") premises_qstn = raw_input("Would you like an additional premises(yes/no)? ") additional_premises = raw_input("Premises: ") while premises_qstn.isalpha(): additional_premises = raw_input("Premises: ") if premises_qstn == 'yes': additional_premises = raw_input("Premises: ") elif premises_qstn == "no": break else: print("Please enter yes or no.") conclusion = input("Conclusion: ") premises_conclusion() # When i use additional_premises in line 7, the while statement asks the additional # premises even if i say 'no'. # When i delete additional_premises in line 7, the while statement only skips # to the conclusion (acts like i said no for yes). No matter what I say it # skips to the conclusion. </code></pre>
-1
2016-09-25T22:43:33Z
39,692,611
<p>These lines seem problematic:</p> <pre><code>premises_qstn = raw_input("Would you like an additional premises(yes/no)? ") additional_premises = raw_input("Premises: ") </code></pre> <p>It asks if you want additional premises, but doesn't check the input (<code>premises_qstn</code>) before immediately asking for more no matter what.</p> <p>Then, the first line inside the while loop asks for premises <em>again</em>, but the loop breaking condition of <code>elif premises_qstn == "no":</code> still hasn't been checked.</p>
1
2016-09-25T22:59:11Z
[ "python", "while-loop" ]
RecursionError while trying to change background on multiple windows in python tkinter
39,692,529
<p>Last night I started a mini project where I wanted to make a game using <code>tkinter</code> (as opposed to <code>pygame</code> mainly because I don't know how to make multiple windows in <code>pygame</code>). </p> <p>I want the user to guess the RGB values and compute their accuracy. Yet, whenever I run my code I get a <code>RecursionError</code> during the <code>startgame</code> function and none of the colors change. I'm confused as to why.</p> <pre><code>from tkinter import * import random class multiWindow(Tk): def __init__(self): # ******* CREATE WINDOWS ******* window1 = Tk() window2 = Tk() window3 = Tk() # ******* WINDOW DIMENSIONS ******* windowH = 100 windowW = 250 # ******* SCREEN RES ******* screenW = 1366-windowW screenH = 768-windowH # ******* COORDINATES OF WINDOWS ******* window1.geometry('%dx%d+%d+%d' % (windowW,windowH,screenW/6,screenH/3)) window2.geometry('%dx%d+%d+%d' % (windowW,windowH,screenW/2,screenH/3)) window3.geometry('%dx%d+%d+%d' % (windowW,windowH,screenW/(6/5),screenH/3)) # ******* WINDOW TITLES ******* window1.title("Color1") window2.title("Color2") window3.title("Color3") # ******** BUTTON START ******* buttonStart = Button(window1,text="Start Game", command=lambda: self.startGame()) buttonStart.pack() # ******* OPEN WINDOWS ******* window1.mainloop() window2.mainloop() window3.mainloop() # ******** PRODUCE RANDOM COLOR ******** def randomRGB(self): return random.randint(0,255) def guessRed(self,window): while True: try: print("I want you to guess the RGB values of the colors in the windows above.") print("Guess the red value of the window displaying ",window) guess = int(input()) if guess &lt; 0 or guess &gt; 255: raise else: return guess break except: print("Error") def startGame(self): # ******** DETERMINE COLOR VALUES ******* colorVal = [0,0,0,0,0,0,0,0,0] for x in range(0,len(colorVal)): colorVal[x] = self.randomRGB() # ******* GIVE WINDOWS COLOR ******* self.window1.configure(background='#%02x%02x%02x'%(colorVal[0],colorVal[1],colorVal[2],)) self.window2.configure(background='#%02x%02x%02x'%(colorVal[3],colorVal[4],colorVal[5],)) self.window3.configure(background='#%02x%02x%02x'%(colorVal[6],colorVal[7],colorVal[8],)) multiWindow = multiWindow() print("This comes after multiwindow class") </code></pre> <p>I'm not very well adversed in <code>tkinter</code>. Just started reading about it 2 days ago, but I feel this problem has less to do with my grasp of <code>tkinter</code> than my grasp of python. </p> <p>Any help is greatly appreciated</p>
0
2016-09-25T22:45:16Z
39,693,939
<p>Your program must have exactly one instance of <code>Tk</code>, and you must call <code>mainloop</code> exactly once. If you need additional windows, create instances of <code>Toplevel</code>. Nothing will work the way you expect if you have more than one instance of <code>Tk</code>. </p> <p>You also need to remove your infinite loop in <code>guessRed</code> as well as the call to <code>input</code>. A GUI shouldn't be getting input from the console. </p> <hr> <p>Unrelated to any other problems, you don't need to use <code>lambda</code> in the following:</p> <pre><code>Button(window1,text="Start Game", command=lambda: self.startGame()) </code></pre> <p>In this case the <code>lambda</code> serves no purpose other than to make the code slightly more complex. Instead, just pass a reference to the function:</p> <pre><code>Button(window1,text="Start Game", command=self.startGame) </code></pre>
0
2016-09-26T02:36:49Z
[ "python", "tkinter", "python-3.5" ]
How to change the shape of the marker depending on a column variable?
39,692,554
<p>I am trying to create a scatter plot for a csv file in python which contains 4 columns <code>x</code>, <code>y</code>, <code>TL</code>, <code>L</code>. I am supposed to plot <code>x</code> versus <code>y</code> and change the color of the marker based on the <code>class ID</code> in the <code>TL</code> column which I have achieved in the below code.</p> <pre><code>import pandas as pd from matplotlib import pyplot as plt import numpy as np df=pd.read_csv('knnDataSet.csv') df.columns=['SN','x','y','TL','L'] color=['red','green','blue'] groups = df.groupby('TL') fig, ax = plt.subplots() for name, group in groups: ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name) ax.legend() plt.show() </code></pre> <p>Also, I need to change the shape depending on whether the marker has a label in the <code>L</code> column or not, but I dont know how to update my code to fit this requirement. </p> <p>Here is the link for the <code>knnDataSet.csv</code> file: <a href="https://www.dropbox.com/s/d9fzjs1pkmhyzqw/knnDataSet.csv?dl=0" rel="nofollow"><em>knnDataSet.csv</em></a> </p>
1
2016-09-25T22:49:54Z
39,694,347
<p>You probably want something like this:</p> <pre><code>import pandas as pd from matplotlib import pyplot as plt import numpy as np df=pd.read_csv('knnDataSet.csv') df.columns=['SN','x','y','TL','L'] color=['red','green','blue'] groups = df.groupby('TL') fig, ax = plt.subplots(figsize=(11,8)) for name, group in groups: for x in group.values: if np.isnan(x[4]): ax.plot(x[1], x[2], marker='x', linestyle='', ms=12) else: ax.plot(x[1], x[2], marker='o', linestyle='', ms=12) #ax.legend() plt.show() </code></pre> <p>If a label in the L column is <strong>NOT</strong> defined then the marker will be <code>X</code><br> If a label in the L column <strong>IS</strong> defined then the marker will be <code>O</code></p> <p><strong>Output:</strong> <a href="http://i.stack.imgur.com/mJRS7.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/mJRS7.jpg" alt="enter image description here"></a></p>
1
2016-09-26T03:38:40Z
[ "python", "matplotlib", "scatter-plot", "markers" ]
Ways to reach variables from one class to another class?
39,692,687
<p>I'm trying to create a basic game, but I'm fairly new to the python programming scene. I've come across a problem where with two classes (a player and enemy class), I want to access class variables like health from the player and enemy, and vice versa. What are some ways of doing this? </p> <p>Here's the code to better emphasize what I'm asking:</p> <pre><code> class Player(object): def __init__(self, image): self.x = 100 self.y = 240 self.health = 30 self.defense = 25 self.image = image self.black = (0, 0, 0) self.draw() def draw(self): screen.blit(self.image, (self.x, self.y)) line = pygame.draw.rect(screen, self.black, (80, 300, 100, 5)) def attack(self): pass class Enemy(object): def __init__(self, image): self.x = 480 self.y = 240 self.health = 20 self.defense = 15 self.image = image self.black = (0, 0, 0) self.draw() def draw(self): screen.blit(self.image, (self.x, self.y)) line = pygame.draw.rect(screen, self.black, (460, 300, 100, 5)) def attack(self): pass </code></pre> <p>Basically, I don't understand how I can take something like the "self.health" from one class, and easily access it from the other class. I've tried some methods of using return methods etc., but I'm curious if there are any simple ways to do this. Help is appreciated!</p>
0
2016-09-25T23:11:07Z
39,692,741
<p>This code creates a class, and in the special <code>__init__</code> method, it assigns values to various <em>member variables</em>.</p> <pre><code>class Player(object): def __init__(self, image): self.x = 100 self.y = 240 self.health = 30 self.defense = 25 self.image = image self.black = (0, 0, 0) self.draw() </code></pre> <p>These member variables are also called <em>properties</em> in Python. If you have a reference to a Player instance (an instance of the Player class):</p> <pre><code>p = Player() </code></pre> <p>You can access the properties all you like:</p> <pre><code>print(p.health) </code></pre> <p>Perhaps you need some kind of "main loop" or controller class that has access to players and enemies and can set their properties accordingly:</p> <pre><code>class MainLoop(object): def __init__(self): self.player_1 = Player() self.enemy_1 = Enemy() def run(self): if fight(): # fight() is some function of your game self.player_1.health -= 10 self.enemy_1.health -= 20 </code></pre>
0
2016-09-25T23:20:55Z
[ "python", "pygame" ]
Tensorflow: Filter must not be larger than the input
39,692,711
<p>I want to perform convolution along the training sample that is of shape [n*1] and apply zero-padding too. So far, no results.</p> <p>I am building a character-level CNN (idea taken from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification_character_cnn.py" rel="nofollow">here</a>)</p> <p>My data is essentially tweets, initially each of length 140. I filter all non-alphabetical characters (replace them with empty string ''), all alphabetical characters I convert to lowercase and encode as one-hot encoder. </p> <p>So I have data is n*m, where n is the number of training examples, m=140*26=3640, since each alphabetical character is encoded as one-hot vector.</p> <p>Now, I am trying to perform convolution, and here is where I have a problem. Essentially: 1) I try to pad a single tweet with zeros around it. 2) Then what I want to do is perform convolution with a filter 3*3 along the tweet, which, I expect to be of 3642*3 size, where width = 3642 and height=3 after padding.</p> <pre><code>F = 3 # filter size S = 1 # stride P = 1 # zero-pading MAX_DOCUMENT_LENGTH = 3640 IMAGE_WIDTH = MAX_DOCUMENT_LENGTH IMAGE_HEIGHT = 1 N_FILTERS = 20 FILTER_SHAPE1 = F BATCH_SIZE = 257 def conv_model(X, y): X = tf.cast(X, tf.float32) y = tf.cast(y, tf.float32) # reshape X to 4d tensor with 2nd and 3rd dimensions being image width and height # final dimension being the number of color channels X = tf.reshape(X, [-1, IMAGE_WIDTH, IMAGE_HEIGHT, 1]) # first conv layer will compute N_FILTERS features for each FxF patch with tf.variable_scope('conv_layer1'): h_conv1 = tf.contrib.layers.conv2d(inputs=X,num_outputs=N_FILTERS, kernel_size=[3,3], padding='VALID') </code></pre> <p>I get the error: <code>ValueError: Filter must not be larger than the input: Filter: (3, 3) Input: (3640, 1)</code></p> <p><strong>Why is zero-padding not applied?</strong> At least, the result of its application does not work...</p> <p>So I change the filter size to <code>[3,1]</code> and I call:</p> <pre><code>h_conv1 = tf.contrib.layers.conv2d(inputs=X, num_outputs=N_FILTERS, kernel_size=[3,1], padding='VALID') </code></pre> <p>And I don't get the error. </p> <p><strong>Could someone please explain what is happening?</strong> </p> <p>Also, why do we need to reshape the input as X = tf.reshape(X, [-1, IMAGE_WIDTH, IMAGE_HEIGHT, 1])? </p>
0
2016-09-25T23:14:28Z
39,701,004
<blockquote> <p>Why is zero-padding not applied?</p> </blockquote> <p>Use <code>padding = 'SAME'</code> in conv2d for zero-padding.</p> <blockquote> <p>Could someone please explain what is happening?</p> </blockquote> <p>You can't use the 3x3 filter in the case of 'flat' image. To use the 3x3 filter, input should have dimensions bigger than 3 on both width and height. </p> <blockquote> <p>Also, why do we need to reshape the input as X = tf.reshape(X, [-1, IMAGE_WIDTH, IMAGE_HEIGHT, 1])?</p> </blockquote> <p>A Single image has a shape of [width, height, number_of_channels]. Extra dimension stands for minibatch size. -1 just preserves total size.</p>
1
2016-09-26T10:56:25Z
[ "python", "machine-learning", "tensorflow", "deep-learning", "convolution" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a one-liner slicing trick that will pull it off? Points for simplicity here.</p>
3
2016-09-25T23:24:21Z
39,692,812
<pre><code>import numpy as np x = np.array(range(1, 16)) y = np.vstack([x[0::5], x[1::5]]).T.ravel() y // =&gt; array([ 1, 2, 6, 7, 11, 12]) </code></pre> <p>Taking the first <code>N</code> rows of every block of <code>M</code> rows in the array <code>[1, 2, ..., K</code>]:</p> <pre><code>import numpy as np K = 30 M = 5 N = 2 x = np.array(range(1, K+1)) y = np.vstack([x[i::M] for i in range(N)]).T.ravel() y // =&gt; array([ 1, 2, 6, 7, 11, 12, 16, 17, 21, 22, 26, 27]) </code></pre> <p>Notice that <code>.T</code> and <code>.ravel()</code> are fast operations: they don't copy any data, but just manipulate the dimensions and strides of the array.</p> <p>If you insist on getting your slice using fancy indexing:</p> <pre><code>import numpy as np K = 30 M = 5 N = 2 x = np.array(range(1, K+1)) fancy_indexing = [i*M+n for i in range(len(x)//M) for n in range(N)] x[fancy_indexing] // =&gt; array([ 1, 2, 6, 7, 11, 12, 16, 17, 21, 22, 26, 27]) </code></pre>
0
2016-09-25T23:31:13Z
[ "python", "numpy", "vectorization" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a one-liner slicing trick that will pull it off? Points for simplicity here.</p>
3
2016-09-25T23:24:21Z
39,692,899
<p>I first thought you need this to work for 2d arrays due to your phrasing of "first N rows of every block of M rows", so I'll leave my solution as this.</p> <p>You could work some magic by reshaping your array into 3d:</p> <pre><code>M = 5 # size of blocks N = 2 # number of columns to cut x = np.arange(3*4*M).reshape(4,-1) # (4,3*N)-shaped dummy input x = x.reshape(x.shape[0],-1,M)[:,:,:N+1].reshape(x.shape[0],-1) # (4,3*N)-shaped output </code></pre> <p>This will extract every column according to your preference. In order to use it for your 1d case you'd need to make your 1d array into a 2d one using <code>x = x[None,:]</code>.</p>
0
2016-09-25T23:43:51Z
[ "python", "numpy", "vectorization" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a one-liner slicing trick that will pull it off? Points for simplicity here.</p>
3
2016-09-25T23:24:21Z
39,692,907
<p>Reshape the array to multiple rows of five columns then take (slice) the first two columns of each row.</p> <pre><code>&gt;&gt;&gt; x array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) &gt;&gt;&gt; x.reshape(x.shape[0] / 5, 5)[:,:2] array([[ 1, 2], [ 6, 7], [11, 12]]) </code></pre> <p>Or</p> <pre><code>&gt;&gt;&gt; x.reshape(x.shape[0] / 5, 5)[:,:2].flatten() array([ 1, 2, 6, 7, 11, 12]) &gt;&gt;&gt; </code></pre> <p>It only works with 1-d arrays that have a length that is a multiple of five.</p>
1
2016-09-25T23:45:05Z
[ "python", "numpy", "vectorization" ]
Efficient numpy indexing: Take first N rows of every block of M rows
39,692,769
<pre><code>x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) </code></pre> <p>I want to grab first 2 rows of array x from every block of 5, result should be:</p> <pre><code>x[fancy_indexing] = [1,2, 6,7, 11,12] </code></pre> <p>It's easy enough to build up an index like that using a for loop.</p> <p>Is there a one-liner slicing trick that will pull it off? Points for simplicity here.</p>
3
2016-09-25T23:24:21Z
39,695,491
<p><strong>Approach #1</strong> Here's a vectorized one-liner using <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow"><code>boolean-indexing</code></a> -</p> <pre><code>x[np.mod(np.arange(x.size),M)&lt;N] </code></pre> <p><strong>Approach #2</strong> If you are going for performance, here's another vectorized approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html" rel="nofollow"><code>NumPy strides</code></a> -</p> <pre><code>n = x.strides[0] shp = (x.size//M,N) out = np.lib.stride_tricks.as_strided(x, shape=shp, strides=(M*n,n)).ravel() </code></pre> <p>Sample run -</p> <pre><code>In [61]: # Inputs ...: x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) ...: N = 2 ...: M = 5 ...: In [62]: # Approach 1 ...: x[np.mod(np.arange(x.size),M)&lt;N] Out[62]: array([ 1, 2, 6, 7, 11, 12]) In [63]: # Approach 2 ...: n = x.strides[0] ...: shp = (x.size//M,N) ...: out=np.lib.stride_tricks.as_strided(x,shape=shp,strides=(M*n,n)).ravel() ...: In [64]: out Out[64]: array([ 1, 2, 6, 7, 11, 12]) </code></pre>
3
2016-09-26T05:49:52Z
[ "python", "numpy", "vectorization" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asterisks.</p>
-2
2016-09-25T23:42:44Z
39,692,913
<p>You need to increment the num_printed variable.</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt; num_stars: print('*') num_printed += 1 </code></pre> <p>Also note that I changed the <code>&lt;=</code> to <code>&lt;</code>: you want to be checking for when <code>num_printed</code> is no longer less than the total number of stars, which will happen after the last start is counted, and your counter increments.</p>
0
2016-09-25T23:45:50Z
[ "python" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asterisks.</p>
-2
2016-09-25T23:42:44Z
39,692,918
<p>Why not simply use</p> <pre><code>print num_stars * '*' </code></pre>
0
2016-09-25T23:46:40Z
[ "python" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asterisks.</p>
-2
2016-09-25T23:42:44Z
39,692,922
<p>The issue is that num_printed is not getting incremented.</p> <p>In the while loop, add <code>num_printed += 1</code>, and change the condition to <code>num_printed &lt; num_stars</code>, otherwise you will be printing 4 stars:</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt; num_stars: print('*') num_printed += 1 </code></pre>
2
2016-09-25T23:47:03Z
[ "python" ]
Python Loop To Print Asterisks Based on User Input
39,692,890
<p>I'm trying to create a python program to print a certain number of asterisks based on user input. My code is below</p> <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print('*') </code></pre> <p>The output is an infinite loop. I want to print the number of stars variable as asterisks.</p>
-2
2016-09-25T23:42:44Z
39,693,006
<p>If you don't want to use a loop here. Maybe do something like this:</p> <pre><code>stars = int(raw_input('number of stars: ')) star_list= ['*' for i in range(stars)] print ' '.join(['%s' % i for i in star_list]) </code></pre>
0
2016-09-26T00:00:36Z
[ "python" ]
Python - unorderable types: Car() > int
39,692,949
<p>I keep getting this error: </p> <pre><code>in move_the_car if self.car_fuel &gt; x_count + y_count: TypeError: unorderable types: Car() &gt; int() </code></pre> <p>From this code:</p> <pre><code>if self.fuel &gt; x_count + y_count: </code></pre> <p>I've heard global can resolve this, but I'm not sure how. If anyone has any other solutions or answer, I will be very grateful. Also I am a beginner in coding and python, so my code may not be written the best, but I am always looking to improve.</p> <p>Entire code</p> <pre><code>class Car: def __init__(self, id_, fuel, x_pos, y_pos): """ @type self: Car @type id_: str @type fuel: int @rtype: None """ self.id = id_ self.fuel = fuel self.x_pos = x_pos self.y_pos = y_pos @property def id_(self): return self.id @id_.setter def id_(self, value): if value != str: raise ValueError() else: self.id = value @property def car_fuel(self): return self.fuel @car_fuel.setter def car_fuel(self, value): if value &lt; 0: raise ValueError() else: self.fuel = value def move_the_car(self, id_, new_x_pos, new_y_pos): """ @type self: Car @type id_: str @type new_x_pos: int @type new_y_pos: int @rtype: None """ x_count = 0 y_count = 0 while x_count != abs(new_x_pos): x_count += 1 while y_count != abs(new_y_pos): y_count += 1 # if fuel level is greater than the movement counter, then return # the new x and y positions if self.fuel &gt; x_count + y_count: new_fuel_level = self._fuel - (x_count + y_count) self._fuel = new_fuel_level self.x_pos = new_x_pos self.y_pos = new_y_pos new_pos = [self.x_pos, self.y_pos] return new_pos elif 0 &lt; self.fuel &lt; (x_count + y_count): new_pos = [self.x_pos, self.y_pos] return new_pos elif self.fuel &lt;= 0: old_pos = [self.x_pos, self.y_pos] return old_pos else: return None </code></pre> <p><strong>Example:</strong></p> <pre><code>test_car = Car('car1', 10, 0, 0) #id = 'car1', fuel = 10, x_pos = 0, y_pos = 0 print(test_car) # works fine print(test_car.car_fuel) #works fine, gives 10 print(test_car.fuel) # works fine, gives 10 print(test_car.move_the_car('car1', 2, 3)) # works fine, gives [2,3] </code></pre> <p><strong>I also call this class in another class, this may be the problem.</strong></p> <pre><code>class CarManager: def __init__(self): self._cars = {} def add_car(self, id_, fuel): """Add a new car to the system""" if id_ not in self._cars: self._cars[id_] = Car(id_, fuel, 0, 0) return self._cars[id_] else: return None def move_car(self, id_, new_x, new_y): """Move the car with the given id. """ if id_ not in self._cars: return None else: car_pos = Car(id_, self._cars[id_], new_x, new_y) return car_pos.move_the_car(id_, new_x, new_y) </code></pre> <p><strong>The last part may be the problem:</strong></p> <pre><code>def move_car(self, id_, new_x, new_y): """Move the car with the given id. """ if id_ not in self._cars: return None else: car_pos = Car(id_, self._cars[id_], new_x, new_y) return car_pos.move_the_car(id_, new_x, new_y) </code></pre>
-4
2016-09-25T23:50:59Z
39,693,084
<blockquote> <p>if self.car_fuel > x_count + y_count:</p> <p>TypeError: unorderable types: Car() > int()</p> </blockquote> <p>This is telling you that at some point you've assigned a <em>Car</em> instance to <code>self.car_fuel</code> when you likely intended to assign an <em>int</em> or a <em>float</em>.</p>
1
2016-09-26T00:14:40Z
[ "python" ]
If statement executes when it's false
39,692,999
<p>I am getting "Knob already attached to a node" when i try to add a knob</p> <p>i get this when i try to run my code from menu.py button.. if i run the script from the script editor i don't get the error.. why is that?</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: nuke.message("first tmp knob created") i.addKnob(t) elif sum0 != 0: nuke.message("second tmp knob created") else: nuke.message("no nob created") </code></pre> <p>Even though <strong>i check if there is a knob named tempMb</strong> .. it still executes it as if there was not, when there is.. edit: "t" is earlier defined as Int_Knob...</p> <p>Thanks!</p>
2
2016-09-25T23:59:07Z
39,693,035
<p>First I'm going to change the <code>elif</code> to just <code>else</code> because your if condition is already testing the elif condition and I don't see how that would be changing while in this code.</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: nuke.message("first tmp knob created") i.addKnob(t) else: nuke.message("second tmp knob created") else: nuke.message("no nob created") </code></pre> <p>Second I'm assuming that <code>i.knob(string)</code> doesn't check for the existence of a knob by that name, or your code would behave more as you expected. So when I read <a href="https://docs.thefoundry.co.uk/nuke/80/pythonreference/nuke-module.html#allNodes" rel="nofollow">the docs</a> it seems like a couple of things may happen:</p> <ol> <li>The nodes might or might not be knobs in the list returned. If you know you only want knobs you could filter by class type. I think that might look like <code>nuke.allNodes(nuke.Knob)</code>.</li> <li>I don't think a nuke.Knob.knob(str) is a test for its name or label. I read the docs as implying that your test should be: <code>if i.name != "tempMb":</code> or possibly <code>if i.label != "tempMb"</code> it depends on how you created <code>t</code>.</li> </ol> <p>Moving on though, I think there may be a logical error here. If you have 2 nodes (and if you make the above changes, let's assume they're both knobs), and as you loop over all nodes the first one is the <code>tempMb</code>, then when you check the second one it won't be that and you'll try to add <code>t</code>, which I assume is named <code>tempMb</code> too. So that's why it looks to you as though the negative condition is always occurring.</p> <p>You need to restructure in one of two ways:</p> <ol> <li>Before the loop, set a false boolean, in the loop set it to true when the knob is <code>tempMb</code> is found; you may as well exit the loop as soon as this occurs. After the loop check the boolean to see if it's safe to add <code>t</code>.</li> <li>I see a possible function <a href="https://docs.thefoundry.co.uk/nuke/80/pythonreference/nuke-module.html#exists" rel="nofollow"><code>nuke.exists(s)</code></a> which tells you if you have any "item" named <code>s</code>.</li> </ol> <p>Maybe remove the loop and write the following:</p> <pre><code> if not nuke.exists("tempMb"): # Add your knob. I'm actually not seeing `addKnob` in the docs. </code></pre>
1
2016-09-26T00:05:29Z
[ "python", "nuke" ]
If statement executes when it's false
39,692,999
<p>I am getting "Knob already attached to a node" when i try to add a knob</p> <p>i get this when i try to run my code from menu.py button.. if i run the script from the script editor i don't get the error.. why is that?</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: nuke.message("first tmp knob created") i.addKnob(t) elif sum0 != 0: nuke.message("second tmp knob created") else: nuke.message("no nob created") </code></pre> <p>Even though <strong>i check if there is a knob named tempMb</strong> .. it still executes it as if there was not, when there is.. edit: "t" is earlier defined as Int_Knob...</p> <p>Thanks!</p>
2
2016-09-25T23:59:07Z
39,693,100
<p><code>nuke.exists("Name of Knob")</code> will check if your knob exists. Try using that in your if statement.</p> <p>More details on <a href="http://community.thefoundry.co.uk/discussion/topic.aspx?f=190&amp;t=101399" rel="nofollow">Nuke forum</a>.</p> <p>See also <a href="https://www.thefoundry.co.uk/products/nuke/developers/100/pythonreference/nuke-module.html#exists" rel="nofollow">Documentation on nuke.exists</a></p>
0
2016-09-26T00:18:09Z
[ "python", "nuke" ]
If statement executes when it's false
39,692,999
<p>I am getting "Knob already attached to a node" when i try to add a knob</p> <p>i get this when i try to run my code from menu.py button.. if i run the script from the script editor i don't get the error.. why is that?</p> <pre><code>for i in nuke.allNodes(): if not i.knob("tempMb"): if sum0 == 0: nuke.message("first tmp knob created") i.addKnob(t) elif sum0 != 0: nuke.message("second tmp knob created") else: nuke.message("no nob created") </code></pre> <p>Even though <strong>i check if there is a knob named tempMb</strong> .. it still executes it as if there was not, when there is.. edit: "t" is earlier defined as Int_Knob...</p> <p>Thanks!</p>
2
2016-09-25T23:59:07Z
40,057,021
<p>Try this solution:</p> <pre><code>t = nuke.Int_Knob( 'tempMb', 'tempMb' ) for i in nuke.allNodes(): if not i.knob("tempMb"): if nuke.exists("sum0"): nuke.message("First tmp knob created") i.addKnob(t) else: nuke.message("Second tmp knob created") else: nuke.message("No knob created") </code></pre> <p><a href="https://i.stack.imgur.com/fqgbx.png" rel="nofollow"><img src="https://i.stack.imgur.com/fqgbx.png" alt="enter image description here"></a></p>
0
2016-10-15T08:53:09Z
[ "python", "nuke" ]
pymc determine sum of random variables
39,693,005
<p>I have two independent Normal distributed random variables <code>a, b</code>. In pymc, it's something like:</p> <pre><code>from pymc import Normal def model(): a = Normal('a', tau=0.01) b = Normal('b', tau=0.1) </code></pre> <p>I'd like to know what's <code>a+b</code> if we can see it as a normal distribution, that is:</p> <pre><code>from pymc import Normal def model(): a = Normal('a', tau=0.01) b = Normal('b', tau=0.1) tau_c = Uniform("tau_c", lower=0.0, upper=1.0) c = Normal("a+b", tau=tau_c, observed=True, value=a+b) </code></pre> <p>Then I'd like to estimate <code>tau_c</code>, but it doesn't work with pymc because <code>a</code> and <code>b</code> are stochastic (if they are arrays it's posible, but I don't have observations of <code>a</code> or <code>b</code>, I just know their distributions).</p> <p>A way I think I can do it, is generating random values by using the distributions of each <code>a</code> and <code>b</code> and then doing this:</p> <pre><code>def model(a, b): tau_c = Uniform("tau_c", lower=0.0, upper=1.0) c = Normal("a+b", tau=tau_c, observed=True, value=a+b) </code></pre> <p>But I think there's a better way of doing this with pymc.</p> <p>Thanks!</p>
-2
2016-09-26T00:00:24Z
39,729,738
<p>If I understood correctly your question and code you should be doing something simpler. If you want to estimate the parameters of the distribution given by the sum of a and b, then use only the first block in the following example. If you also want to estimate the parameters for the variable a independently of the parameter of variable b, then use the other two blocks</p> <pre><code>with pm.Model() as model: mu = pm.Normal('mu', mu=0, sd=10) sd = pm.HalfNormal('sd', 10) alpha = pm.Normal('alpha', mu=0, sd=10) ab = pm.SkewNormal('ab', mu=mu, sd=sd, alpha=alpha, observed=a+b) mu_a = pm.Normal('mu_a', mu=0, sd=10) sd_a = pm.HalfNormal('sd_a', 10) alpha_a = pm.Normal('alpha_a', mu=0, sd=10) a = pm.SkewNormal('a', mu=mu_a, sd=sd_a, alpha=alpha_a, observed=a) mu_b = pm.Normal('mu_b', mu=0, sd=10) sd_b = pm.HalfNormal('sd_b', 10) alpha_b = pm.Normal('alpha_b', mu=0, sd=10) b = pm.SkewNormal('b', mu=mu_b, sd=sd_b, alpha=alpha_b, observed=b) trace = pm.sample(1000) </code></pre> <p>Be sure to use the last version of PyMC3, since previous versions did not include the SkewNormal distribution.</p> <p><strong>Update:</strong></p> <p>Given that you change your question:</p> <p>If a and b are independent random variables and both are normally distributed then their sum is going to be normally distributed. </p> <p>a ~ N(mu_a, sd_a²)</p> <p>b ~ N(mu_b, sd_b²)</p> <p>a+b ~ N(mu_a+mu_b, sd_a²+sd_b²)</p> <p>that is you sum their means and you sum their variances (not their standard deviations). You don't need to use PyMC3.</p> <p>If you still want to use PyMC3 (may be your distribution are not Gaussian and you do not know how to compute their sum analytically). You can generate synthetic data from your <code>a</code> and <code>b</code> distributions and then use PyMC3 to estimate the parameters, something in line of:</p> <pre><code>with pm.Model() as model: mu = pm.Normal('mu', mu=0, sd=10) sd = pm.HalfNormal('sd', 10) ab = pm.Normal('ab', mu=mu, sd=sd, observed=a+b) trace = pm.sample(1000) </code></pre>
0
2016-09-27T16:22:03Z
[ "python", "statistics", "probability", "pymc", "pymc3" ]
How to use Boolean OR inside a regex
39,693,056
<p>I want to use a regex to find a substring, followed by a variable number of characters, followed by any of several substrings.</p> <p>an re.findall of</p> <pre><code>"ATGTCAGGTAAGCTTAGGGCTTTAGGATT" </code></pre> <p>should give me:</p> <pre><code>['ATGTCAGGTAA', 'ATGTCAGGTAAGCTTAG', 'ATGTCAGGTAAGCTTAGGGCTTTAG'] </code></pre> <p>I have tried all of the following without success:</p> <pre><code>import re string2 = "ATGTCAGGTAAGCTTAGGGCTTTAGGATT" re.findall('(ATG.*TAA)|(ATG.*TAG)', string2) re.findall('ATG.*(TAA|TAG)', string2) re.findall('ATG.*((TAA)|(TAG))', string2) re.findall('ATG.*(TAA)|(TAG)', string2) re.findall('ATG.*(TAA)|ATG.*(TAG)', string2) re.findall('(ATG.*)(TAA)|(ATG.*)(TAG)', string2) re.findall('(ATG.*)TAA|(ATG.*)TAG', string2) </code></pre> <p>What am I missing here?</p>
2
2016-09-26T00:09:20Z
39,693,127
<p>This is not super-easy, because a) you want overlapping matches, and b) you want greedy and non-greedy and everything inbetween.</p> <p>As long as the strings are fairly short, you can check every substring:</p> <pre><code>import re s = "ATGTCAGGTAAGCTTAGGGCTTTAGGATT" p = re.compile(r'ATG.*TA[GA]$') for start in range(len(s)-6): # string is at least 6 letters long for end in range(start+6, len(s)): if p.match(s, pos=start, endpos=end): print(s[start:end]) </code></pre> <p>This prints:</p> <pre><code>ATGTCAGGTAA ATGTCAGGTAAGCTTAG ATGTCAGGTAAGCTTAGGGCTTTAG </code></pre> <p>Since you appear to work with DNA sequences or something like that, make sure to check out <a href="http://biopython.org" rel="nofollow">Biopython</a>, too.</p>
3
2016-09-26T00:23:22Z
[ "python", "regex", "parsing", "boolean-logic" ]
How to use Boolean OR inside a regex
39,693,056
<p>I want to use a regex to find a substring, followed by a variable number of characters, followed by any of several substrings.</p> <p>an re.findall of</p> <pre><code>"ATGTCAGGTAAGCTTAGGGCTTTAGGATT" </code></pre> <p>should give me:</p> <pre><code>['ATGTCAGGTAA', 'ATGTCAGGTAAGCTTAG', 'ATGTCAGGTAAGCTTAGGGCTTTAG'] </code></pre> <p>I have tried all of the following without success:</p> <pre><code>import re string2 = "ATGTCAGGTAAGCTTAGGGCTTTAGGATT" re.findall('(ATG.*TAA)|(ATG.*TAG)', string2) re.findall('ATG.*(TAA|TAG)', string2) re.findall('ATG.*((TAA)|(TAG))', string2) re.findall('ATG.*(TAA)|(TAG)', string2) re.findall('ATG.*(TAA)|ATG.*(TAG)', string2) re.findall('(ATG.*)(TAA)|(ATG.*)(TAG)', string2) re.findall('(ATG.*)TAA|(ATG.*)TAG', string2) </code></pre> <p>What am I missing here?</p>
2
2016-09-26T00:09:20Z
39,693,824
<p>I like the accepted answer just fine :-) That is, I'm adding this for info, not looking for points.</p> <p>If you have heavy need for this, trying a match on <code>O(N^2)</code> pairs of indices may soon become unbearably slow. One improvement is to use the <code>.search()</code> method to "leap" directly to the only starting indices that can possibly pay off. So the following does that.</p> <p>It also uses the <code>.fullmatch()</code> method so that you don't have to artificially change the "natural" regexp (e.g., in your example, no need to add a trailing <code>$</code> to the regexp - and, indeed, in the following code doing so would no longer work as intended). Note that <code>.fullmatch()</code> was added in Python 3.4, so this code also requires Python 3!</p> <p>Finally, this intends to generalize the <code>re</code> module's <code>finditer()</code> function/method. While you don't need match objects (you just want strings), they're far more generally applicable, and returning a generator is often friendlier than returning a list too.</p> <p>So, no, this doesn't do exactly what you want, but does things from which you can <em>get</em> what you want, in Python 3, faster:</p> <pre><code>def finditer_overlap(regexp, string): start = 0 n = len(string) while start &lt;= n: # don't know whether regexp will find shortest or # longest match, but _will_ find leftmost match m = regexp.search(string, start) if m is None: return start = m.start() for finish in range(start, n+1): m = regexp.fullmatch(string, start, finish) if m is not None: yield m start += 1 </code></pre> <p>Then, e.g.,</p> <pre><code>import re string2 = "ATGTCAGGTAAGCTTAGGGCTTTAGGATT" pat = re.compile("ATG.*(TAA|TAG)") for match in finditer_overlap(pat, string2): print(match.group()) </code></pre> <p>prints what you wanted in your example. The other ways you tried to write a regexp should also work. In this example it's faster because the second time around the outer loop <code>start</code> is 1, and <code>regexp.search(string, 1)</code> fails to find another match, so the generator exits at once (so skips checking <code>O(N^2)</code> other index pairs).</p>
0
2016-09-26T02:18:58Z
[ "python", "regex", "parsing", "boolean-logic" ]
How to select words of equal max length from a text document
39,693,099
<p>I am trying to write a program to read a text document and output the longest word in the document. If there are multiple longest words (i.e., all of equal length) then I need to output them all in the same order in which they occur. For example, if the longest words were dog and cat your code should produce:</p> <p>dog cat</p> <p>I am having trouble finding out how to select numerous words of equal max length and print them. This is as far as I've gotten, I am just struggling to think of how to select all words with equal max length:</p> <p>open the file for reading</p> <pre><code>fh = open('poem.txt', 'r') longestlist = [] longestword = '' for line in fh: words = (line.strip().split(' ')) for word in words: word = ''.join(c for c in word if c.isalpha()) if len(word) &gt; (longestword): longest.append(word) for i in longestlist: print i </code></pre>
0
2016-09-26T00:17:46Z
39,693,148
<p>What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only put that one word in it and also update the longest length. If you visited words with same length as the longest you should add them to the list.</p> <p>P.S. I did not put the code so you can do it yourself.</p>
0
2016-09-26T00:25:58Z
[ "python", "string", "maxlength" ]
How to select words of equal max length from a text document
39,693,099
<p>I am trying to write a program to read a text document and output the longest word in the document. If there are multiple longest words (i.e., all of equal length) then I need to output them all in the same order in which they occur. For example, if the longest words were dog and cat your code should produce:</p> <p>dog cat</p> <p>I am having trouble finding out how to select numerous words of equal max length and print them. This is as far as I've gotten, I am just struggling to think of how to select all words with equal max length:</p> <p>open the file for reading</p> <pre><code>fh = open('poem.txt', 'r') longestlist = [] longestword = '' for line in fh: words = (line.strip().split(' ')) for word in words: word = ''.join(c for c in word if c.isalpha()) if len(word) &gt; (longestword): longest.append(word) for i in longestlist: print i </code></pre>
0
2016-09-26T00:17:46Z
39,693,191
<p>Ok, first off, you should probably use a <code>with</code> <code>as</code> statement, it just simplifies things and makes sure you don't mess up. So</p> <p><code>fh = open('poem.txt', 'r')</code></p> <p>becomes</p> <p><code>with open('poem.txt','r') as file:</code></p> <p>and since you're just concerned with words, you might as well use a built-in from the start:</p> <pre><code> words = file.read().split() </code></pre> <p>Then you just set a counter of the max word length (initialized to 0), and an empty list. If the word has broken the max length, set a new maxlength and rewrite the list to include only that word. If it's equal to the maxlength, include it in the list. Then just print out the list members. If you want to include some checks like <code>.isalpha()</code> feel free to put it in the relevant portions of the code.</p> <pre><code>maxlength = 0 longestlist = [] for word in words: if len(word) &gt; maxlength: maxlength = len(word) longestlist = [word] elif len(word) == maxlength: longestlist.append(word) for item in longestlist: print item </code></pre> <p>-MLP</p>
1
2016-09-26T00:34:12Z
[ "python", "string", "maxlength" ]
Selecting text using multiple splits
39,693,115
<p>I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:</p> <pre><code>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 </code></pre> <p>I need to extract the hours from each line (in this case 09) and then find the most common hours the emails were sent.</p> <p>Basically, what I need to do is build a for loop that splits each text by colon</p> <pre><code>split(':') </code></pre> <p>and then splits by space:</p> <pre><code>split() </code></pre> <p>I've tried for hours, but can't seem to figure it out. What my code looks like so far:</p> <pre><code>name = raw_input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) counts = dict() lst = list() temp = list() for line in handle: if not "From " in line: continue words = line.split(':') for word in words: counts[word] = counts.get(word,0) + 1 for key, val in counts.items(): lst.append( (val, key) ) lst.sort(reverse = True) for val, key in lst: print key, val </code></pre> <p>The code above only does 1 split, but I've kept trying multiple methods to split the text again. I keep getting a list attribute error, saying "list object has no attribute split". Would appreciate any help on this. Thanks again</p>
1
2016-09-26T00:21:29Z
39,693,257
<p>First, </p> <pre><code>import re </code></pre> <p>Then replace</p> <pre><code>words = line.split(':') for word in words: counts[word] = counts.get(word,0) + 1 </code></pre> <p>by</p> <pre><code>line = re.search("[0-9]{2}:[0-9]{2}:[0-9]{2}", line).group(0) words = line.split(':') hour = words[0] counts[hour] = counts.get(hour, 0) + 1 </code></pre> <p>Input:</p> <pre><code>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 12:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 15:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 12:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 13:14:16 2008 From stephen.marquard@uct.ac.za Sat Jan 5 12:14:16 2008 </code></pre> <p>Output:</p> <pre><code>09 4 12 3 15 1 13 1 </code></pre>
1
2016-09-26T00:44:26Z
[ "python", "split" ]
Selecting text using multiple splits
39,693,115
<p>I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:</p> <pre><code>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 </code></pre> <p>I need to extract the hours from each line (in this case 09) and then find the most common hours the emails were sent.</p> <p>Basically, what I need to do is build a for loop that splits each text by colon</p> <pre><code>split(':') </code></pre> <p>and then splits by space:</p> <pre><code>split() </code></pre> <p>I've tried for hours, but can't seem to figure it out. What my code looks like so far:</p> <pre><code>name = raw_input("Enter file:") if len(name) &lt; 1 : name = "mbox-short.txt" handle = open(name) counts = dict() lst = list() temp = list() for line in handle: if not "From " in line: continue words = line.split(':') for word in words: counts[word] = counts.get(word,0) + 1 for key, val in counts.items(): lst.append( (val, key) ) lst.sort(reverse = True) for val, key in lst: print key, val </code></pre> <p>The code above only does 1 split, but I've kept trying multiple methods to split the text again. I keep getting a list attribute error, saying "list object has no attribute split". Would appreciate any help on this. Thanks again</p>
1
2016-09-26T00:21:29Z
39,693,330
<p>Using the same test file as Marcel Jacques Machado:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter(line.split(' ')[-2].split(':')[0] for line in open('input')).items() [('12', 3), ('09', 4), ('15', 1), ('13', 1)] </code></pre> <p>This shows that <code>09</code> occurs 4 times while <code>13</code> occurs only once.</p> <p>If we want prettier output, we can do some formatting. This shows the hours and their counts sorted from most common to least common:</p> <pre><code>&gt;&gt;&gt; print('\n'.join('{} {}'.format(hh, n) for hh,n in Counter(line.split(' ')[-2].split(':')[0] for line in open('input')).most_common())) 09 4 12 3 15 1 13 1 </code></pre>
1
2016-09-26T00:57:16Z
[ "python", "split" ]
Django: How do I use a foreign key field in aggregation?
39,693,126
<p>Let's say I have the following two models:</p> <pre><code>class Parent(models.Model): factor = models.DecimalField(...) ... other fields class Child(models.Model): field_a = models.DecimalField(...) field_b = models.DecimalField(...) parent = models.ForeignKey(Parent) ... other fields </code></pre> <p>Now I want to calculate the sum of <code>(field_a * field_b * factor)</code> of all objects in the <code>Child</code> model. I can calculate the sum of <code>(field_a * field_b)</code> with <code>aggregate(value=Sum(F('field_a')*F('field_b'), output_field=DecimalField()))</code>. My question is how I can pull out the <code>factor</code> field from the <code>Parent</code> model?</p> <p>I am new to Django and I really appreciate your help!</p>
5
2016-09-26T00:23:10Z
39,693,157
<p>Django let's you follow relationships with the double underscore (__) as deep as you like. So in your case <code>F('parent__factor')</code> should do the trick.</p> <p>The full queryset:</p> <pre><code>Child.objects.aggregate(value=Sum(F('field_a') * F('field_b') * F('parent__factor'), output_field=DecimalField())) </code></pre>
5
2016-09-26T00:27:15Z
[ "python", "django" ]
Stripe is creating customers when charge declined
39,693,185
<p>For some reason when some one charges to sign up to the subscription plan if their card is declined stripe is still creating the customer.</p> <p>I'm not particularly sure why this is happening since I am creating the customer with the charge, how do I make it so if some one signs up but their card does not go through stripe doesn't make them a customer?</p> <p>Here is my code</p> <pre><code>import stripe @app.route('/stripe/charge', methods=['POST']) def stripe_charge(): data = json.loads(request.data) user = data['user'] source = data['stripeToken'] # obtained from Stripe.js try: customer = stripe.Customer.create( source=source, plan="gold5", email=email, ) except stripe.CardError, e: return jsonify(error="%s" % e) return jsonify(customer) </code></pre>
0
2016-09-26T00:33:01Z
39,694,625
<p>Are you sure its a <code>CardError</code> that would be thrown? Try doing a general <code>Exception</code>, see what error gets thrown when the card is bad. Also their API docs don't actually say an error will be thrown if the card is declined:</p> <blockquote> <p>If an invoice payment is due and a source is not provided, the call will raise an error. If a non-existent plan or a non-existent or expired coupon is provided, the call will raise an error.</p> </blockquote> <p><a href="https://stripe.com/docs/api?lang=python#create_customer" rel="nofollow">https://stripe.com/docs/api?lang=python#create_customer</a></p>
0
2016-09-26T04:12:55Z
[ "python", "flask", "stripe-payments" ]
Stripe is creating customers when charge declined
39,693,185
<p>For some reason when some one charges to sign up to the subscription plan if their card is declined stripe is still creating the customer.</p> <p>I'm not particularly sure why this is happening since I am creating the customer with the charge, how do I make it so if some one signs up but their card does not go through stripe doesn't make them a customer?</p> <p>Here is my code</p> <pre><code>import stripe @app.route('/stripe/charge', methods=['POST']) def stripe_charge(): data = json.loads(request.data) user = data['user'] source = data['stripeToken'] # obtained from Stripe.js try: customer = stripe.Customer.create( source=source, plan="gold5", email=email, ) except stripe.CardError, e: return jsonify(error="%s" % e) return jsonify(customer) </code></pre>
0
2016-09-26T00:33:01Z
39,699,269
<p>Because you <a href="https://stripe.com/docs/api#create_customer" rel="nofollow">create the customer</a> with the <code>plan</code> parameter, Stripe will attempt to create both the customer and the subscription in one go. Unless the plan has a trial period, Stripe will immediately attempt to bill the customer for the plan's amount (since Stripe's subscriptions are paid upfront), and if the charge fails, then the call will return an error and the customer will <em>not</em> be created.</p> <p>If you're seeing a different behavior, I recommend you get in touch with <a href="https://support.stripe.com/email" rel="nofollow">Stripe's support</a> to describe the problem. Make sure you include the customer ID and/or request ID in your message.</p>
1
2016-09-26T09:32:39Z
[ "python", "flask", "stripe-payments" ]
Monthly credit card payment calculator shows Syntax Error
39,693,248
<p>This program is supposed to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company. When I try to run it, it shows a SyntaxError, and I'm not sure why. Here's my code:</p> <pre><code>def ccb(balance, annualInterestRate, monthlyPaymentRate): monthlyInterestRate = annualInterestRate / 12.0 month = 0 for calc in range(12): minMonthlyPaymentRate = balance * monthlyPaymentRate unpaidBalance = balance - minMonthlyPaymentRate interest = monthlyInterestRate * unpaidBalance print ("Month | Balance | Unpaid Balance | Interest") print (month + " | " + round(balance) + " | " + round(unpaidBalance) + " | " + Interest) balance = unpaidBalance + Interest month += 1 print ("Remaining balance: " + round(balance)) </code></pre>
-1
2016-09-26T00:43:21Z
39,693,338
<p>A few things (though none appear to throw SyntaxError - seconding Andrew in the comments, if it's a SyntaxError - share the full message):</p> <p>1) You can't implicitly make an integer a string, you need to cast it. Ex:</p> <pre><code>str(round(balance)) </code></pre> <p>instead of</p> <pre><code>round(balance) </code></pre> <p>2) 'Interest' is never defined, but 'interest' is.</p> <p>With those fixed, it runs fine.</p> <p>Also, <a href="http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions">this</a> might be relevant ;)</p>
-1
2016-09-26T00:58:23Z
[ "python", "syntax-error", "banking" ]
Python mysql.connector module, Passing data into string VALUES %s
39,693,265
<p>I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this error. </p> <p>mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1</p> <p>If I do it like this: </p> <pre><code>sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)"),(data) </code></pre> <p>I get a tuple error.. </p> <pre><code>import mysql.connector from mysql.connector import errorcode cnx = mysql.connector.connect (user='userDB1', password='UserPwd1', host='somedatabase.com', database='mydatabase1') cursor = cnx.cursor() sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)") data=('HelloSQLWORLD') cursor.execute(sql_insert,data) cnx.commit() cnx.close() </code></pre>
0
2016-09-26T00:45:29Z
39,693,279
<p>Pythonic string formatting is:</p> <pre><code>str1 = 'hello' str2 = 'world' '%s, %s' % (str1, str2) </code></pre> <p>Use <code>%</code> with <code>tuple</code>, not <code>,</code></p> <p>For your particular case, try:</p> <pre><code>cursor.execute(sql_insert % (data)) </code></pre>
0
2016-09-26T00:47:59Z
[ "python", "mysql" ]
Python mysql.connector module, Passing data into string VALUES %s
39,693,265
<p>I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this error. </p> <p>mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1</p> <p>If I do it like this: </p> <pre><code>sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)"),(data) </code></pre> <p>I get a tuple error.. </p> <pre><code>import mysql.connector from mysql.connector import errorcode cnx = mysql.connector.connect (user='userDB1', password='UserPwd1', host='somedatabase.com', database='mydatabase1') cursor = cnx.cursor() sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)") data=('HelloSQLWORLD') cursor.execute(sql_insert,data) cnx.commit() cnx.close() </code></pre>
0
2016-09-26T00:45:29Z
39,693,357
<p>No, don't do it the way @Jeon suggested - by using string formatting you are exposing your code to <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL injection attacks</a>. Instead, <em>properly parameterize the query</em>:</p> <pre><code>query = """ INSERT INTO Products (title) VALUES (%s)""" cursor.execute(query, ('HelloSQLWORLD', )) </code></pre> <p>Note how the query parameters are put into a <em>tuple</em>.</p>
1
2016-09-26T01:01:03Z
[ "python", "mysql" ]
Add image to pull request comment
39,693,292
<p>I'm using the github3.py library to create a comment in a pull request from the columns field in a csv file. I would like to add an image to the comment along with the output from the columns, but I can't find a way to do this. I've read up on using PIL to open images, but <code>.create_comment()</code> only takes a string value. Any hints or pointers?</p> <pre><code>failed_validation_lst=[] with open(reportOut, 'r') as f: reader = csv.reader(f, skipinitialspace=True) headers = next(reader) for row_number,row in enumerate(reader,2): for column, val in enumerate(row): if val == 'True': failed_validation_lst.append(headers[column]) failed_validation_string = '; '.join(failed_validation_lst) repo.issue(row[0]).create_comment(failed_validation_string) </code></pre>
1
2016-09-26T00:49:53Z
39,728,703
<p>The GitHub API does not support this. Commenting on a pull request is the same thing as <a href="https://developer.github.com/v3/issues/comments/#create-a-comment" rel="nofollow">commenting on a issue</a>. You'll need to host the image elsewhere and use image tag markdown to display it, e.g.,</p> <pre><code>![image description](http://image-hosting.com/path/to/img.jpg) </code></pre>
2
2016-09-27T15:31:14Z
[ "python", "github3.py" ]
Change specific elements of a list from string to integers in python
39,693,346
<p>If I have a list such as </p> <p><code>c=['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']</code></p> <p>How do I specifically Convert the numbers of the the list into integers leaving the rest of the string as it is and get rid of the \n ?</p> <p>expected output: </p> <pre><code>`c=['my', 'age', 'is', 5,'The', 'temperature', 'today' 'is' ,87]` </code></pre> <p>I tried using the 'map()' and 'isdigit()' function but it didnt work.</p> <p>Thank you. </p>
0
2016-09-26T00:59:59Z
39,693,370
<p>You can write a function that tries to convert to an <code>int</code> and if it fails return the original, e.g:</p> <pre><code>def conv(x): try: x = int(x) except ValueError: pass return x &gt;&gt;&gt; c = ['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n'] &gt;&gt;&gt; list(map(conv, c)) ['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87] &gt;&gt;&gt; [conv(x) for x in c] ['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87] </code></pre> <p>Note: 2 strings separated by whitespace are automatically concatenated by python, e.g. <code>'today' 'is'</code> is equivalent to <code>'todayis'</code></p>
0
2016-09-26T01:04:31Z
[ "python", "string", "list" ]
Change specific elements of a list from string to integers in python
39,693,346
<p>If I have a list such as </p> <p><code>c=['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']</code></p> <p>How do I specifically Convert the numbers of the the list into integers leaving the rest of the string as it is and get rid of the \n ?</p> <p>expected output: </p> <pre><code>`c=['my', 'age', 'is', 5,'The', 'temperature', 'today' 'is' ,87]` </code></pre> <p>I tried using the 'map()' and 'isdigit()' function but it didnt work.</p> <p>Thank you. </p>
0
2016-09-26T00:59:59Z
39,693,395
<p>If you don't know the format of integers in your text, or there are just too many variations, then one approach is simply to try <code>int()</code> on everything and see what succeeds or fails:</p> <pre><code>original = ['my', 'age', 'is', '5\n', 'The', 'temperature', 'today', 'is', '87\n'] revised = [] for token in original: try: revised.append(int(token)) except ValueError: revised.append(token) print(revised) </code></pre> <p>Generally using <code>try</code> and <code>except</code> as part of your algorithm, not just your error handling, is a bad practice, since they aren't efficient. However, in this case, it's too hard to predict all the possible inputs that <code>int()</code>, or <code>float()</code>, can successfully handle, so the <code>try</code> approach is reasonable.</p>
0
2016-09-26T01:09:55Z
[ "python", "string", "list" ]
How to filter out elements from list by comparison function, which works with pairs in this list?
39,693,354
<p>I have list of PIL <em>images</em> (more than 2) and function <em>diff (im1, im2)</em>, which return True if percentage difference in images is small - i.e. if it return True, then 2 compared images - duplicate. How do I get PIL list of images without duplicates (i.e. if I have 3 equal images of sun and 2 images of cat, I need only one image of sun and one image of cat)? I've wanted use filter, but it filter out elements of list with function one by one, but in my situation I have only comparison function.</p> <p><strong>upd1:</strong> I've tried code, suggested by AChampion:</p> <pre><code>import itertools as it dupes = {i for i in (i1, i2) for i1, i2 in it.combinations(images_list, 2) if diff(i1, i2)} set(images_list) - dupes </code></pre> <p>but python 3.5 says NameError: name 'i1' is not defined, I quite could not understand it also, </p> <p><strong>upd2:</strong> So I've corrected this code as I could and ended up in some sort of nested list, which I "flattened" (and not sure all this stuff works properly), but then I'm getting <strong>TypeError: unhashable type: 'JpegImageFile'</strong> for <strong>string images = set(images) - dupes</strong></p> <p>example code:</p> <pre><code>for url in images_urls: images.append(Image.open(requests.get(url, stream=True).raw)) dupes = [[i for i in (i1, i2)] for i1, i2 in it.combinations(images, 2) if diff(i1, i2)] dupes = [item for sublist in dupes for item in sublist] dupes = set(dupes) images = set(images) - dupes </code></pre> <p><strong>upd3:</strong> as @Padraic Cunningham suggested I've got:</p> <pre><code>for url in images_urls: print('downloading url:', url) images.append(Image.open(requests.get(url, stream=True).raw)) dupes = set(itertools.chain(*(t for t in itertools.combinations(images, 2) if diff(*t)))) images = set(images) - dupes </code></pre> <p>But still getting <strong>TypeError: unhashable type: 'JpegImageFile'</strong> maybe there is more easy way to do this without hash/eq approach? For now I will try to look closely at hash/eq realization approach...</p> <p>-- <strong>upd4:</strong> I need {'flower','cat'}, but I'm getting {'flower'}</p> <pre><code>import itertools def diff(a, b): return a == b images_list = [ 'flower', 'cat', 'flower' ] some_values = set(itertools.chain(*(t for t in itertools.combinations(images_list, 2) if diff(*t)))) print(some_values) </code></pre>
0
2016-09-26T01:00:44Z
39,693,451
<p>Construct a set of all the duplicates and subtract from original set. I've changed the diff to similarity test rather than an equality test to better reflect the problem description:</p> <pre><code>images_list = [ 'image red contents1', 'image green contents', 'image red contents2', ] import itertools as it def diff(a, b): return a.split()[1] == b.split()[1] dupes = {i2 for i1, i2 in it.combinations(images_list, 2) if diff(i1, i2)} set(images_list) - dupes # {'image green contents', 'image red contents1'} </code></pre>
0
2016-09-26T01:19:04Z
[ "python", "list", "filter", "set", "itertools" ]
How do I replace all values equal to x in nth level of a multi index
39,693,359
<p>Consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series(np.arange(6), pd.MultiIndex.from_product([[1, 2], [1, 2, 3]])) 1 1 0 2 1 3 2 2 1 3 2 4 3 5 dtype: int64 </code></pre> <p>I want to replace all values of <code>3</code> in the index with <code>4</code>.</p> <hr> <p>I just came up with this and I don't like it.</p> <pre><code>lvl0 = s.index.get_level_values(0) lvl1 = s.index.get_level_values(1) s.index = pd.MultiIndex.from_tuples(zip(lvl0, np.where(lvl1 == 3, 4, lvl1))) s 1 1 0 2 1 4 2 2 1 3 2 4 4 5 dtype: int64 </code></pre>
1
2016-09-26T01:02:17Z
39,693,548
<p>You could use <code>s.index.levels = [[1, 2], [1, 2, 4]]</code> but you may get a FutureWarning:</p> <blockquote> <p>FutureWarning: setting `levels` directly is deprecated. Use set_levels instead</p> </blockquote> <p>So you may try</p> <pre><code>&gt;&gt;&gt; s.index = s.index.set_levels([[1, 2], [1, 2, 4]]) &gt;&gt;&gt; s 1 1 0 2 1 4 2 2 1 3 2 4 4 5 </code></pre>
1
2016-09-26T01:32:35Z
[ "python", "pandas", "numpy", "multi-index" ]
How do I replace all values equal to x in nth level of a multi index
39,693,359
<p>Consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series(np.arange(6), pd.MultiIndex.from_product([[1, 2], [1, 2, 3]])) 1 1 0 2 1 3 2 2 1 3 2 4 3 5 dtype: int64 </code></pre> <p>I want to replace all values of <code>3</code> in the index with <code>4</code>.</p> <hr> <p>I just came up with this and I don't like it.</p> <pre><code>lvl0 = s.index.get_level_values(0) lvl1 = s.index.get_level_values(1) s.index = pd.MultiIndex.from_tuples(zip(lvl0, np.where(lvl1 == 3, 4, lvl1))) s 1 1 0 2 1 4 2 2 1 3 2 4 4 5 dtype: int64 </code></pre>
1
2016-09-26T01:02:17Z
39,693,569
<p>you could reset the index</p> <pre><code>s = s.reset_index() s[s==3] = 4 In[227]: s Out[227]: level_0 level_1 0 0 1 1 0 1 1 2 1 2 1 4 2 3 2 1 4 4 2 2 4 5 2 4 5 </code></pre>
1
2016-09-26T01:36:08Z
[ "python", "pandas", "numpy", "multi-index" ]
What is a robust method for parsing a string that can be used to issue commands
39,693,396
<p>Certain tools that we all use often allow strings to be parsed as optional commands. For example, with most IRC tools one can write something like <code>/msg &lt;nick&gt; hi there!</code>, resulting in the string being parsed and executing a command.</p> <p>I was thinking about this on the weekend, and realised that I have absolutely no idea how I could implement this functionality robustly. My birds-eye view understanding of it is that every input will need to be parsed, a potential match found for issuing a command, and that command will need to be executed with proper validation in place.</p> <p>I wrote a quick proof of concept for this in Python:</p> <pre><code>class InputParser: def __init__(self): self.command_character = '!!' self.message = None self.command = None self.method = None def process_message(self, message): # every input into the system is sent through here. If the # start of the string matches the command_character, try and # find the command, otherwise return back the initial # message. self.message = message if self.message.startswith(self.command_character): self.command = self.message.split(' ')[0] self.method = self.command.replace(self.command_character, '') try: return self.__class__.__dict__['_%s' % self.method]() except KeyError: # no matching command found, return the input message return self.message return self.message def _yell(self): # returns an uppercase string return self.message.upper().replace(self.command, '') def _me(self): # returns a string wrapped by * characters return ('*%s*' % self.message).replace(self.command, '') </code></pre> <p>Example usage:</p> <p><code>!!yell hello friend</code> > <code>HELLO FRIEND</code></p> <p><strong>Question</strong>: Can someone provide me a link to an existing project, an existing library or give me a conceptual overview on an effective way to robustly change the manner in which a string is interpreted by a program, leading to different behaviour by the application? </p>
0
2016-09-26T01:10:13Z
39,693,516
<p>Rather than hacking away at the class internals, you would be better off using a dictionary to map the command strings to a function that performs the command. Set up the dictionary at the class level, or in the <code>__init__()</code> if it might vary between instances.</p> <p>This way the dictionary serves two purposes: one to provide the valid command tokens and the other to map the command token to an action.</p>
0
2016-09-26T01:28:11Z
[ "python", "string", "command", "irc" ]
Pandas: when can I directly assign to values array
39,693,431
<p>I was messing with pandas in the interpreter and the following behavior took me by surprise:</p> <pre><code>&gt;&gt;&gt; data2 = [[1, np.nan], [2, -17]] &gt;&gt;&gt; f2 = pd.DataFrame(data2) &gt;&gt;&gt; f2 0 1 0 1 NaN 1 2 -17.0 &gt;&gt;&gt; f2.values[1, 1] = -99.0 &gt;&gt;&gt; f2 0 1 0 1 NaN 1 2 -17.0 &gt;&gt;&gt; type(f2.values[0, 0]), type(f2.values[1, 0]) (&lt;class 'numpy.float64'&gt;, &lt;class 'numpy.float64'&gt;) </code></pre> <p>I am unable to assign directly to the underlying array using the values attribute. However, if I explicitly start with floats, I can:</p> <pre><code>&gt;&gt;&gt; data = [[1.0, np.nan], [2.0, -17.0]] &gt;&gt;&gt; f = pd.DataFrame(data) &gt;&gt;&gt; f 0 1 0 1.0 NaN 1 2.0 -17.0 &gt;&gt;&gt; f.values[1, 1] = -99.0 &gt;&gt;&gt; f 0 1 0 1.0 NaN 1 2.0 -99.0 </code></pre> <p>Does anyone know a rule that would have allowed me to predict this? I feel like I must be missing something obvious.</p>
0
2016-09-26T01:15:10Z
39,693,521
<p>using .values returns a numpy array. so whatever you do after doing <code>df.values</code> will be exactly like using a numpy array.</p> <p>using<code>df.iloc[i,i]</code> allows you to set values or extract value using an integer position</p>
0
2016-09-26T01:29:12Z
[ "python", "pandas" ]
Pandas: when can I directly assign to values array
39,693,431
<p>I was messing with pandas in the interpreter and the following behavior took me by surprise:</p> <pre><code>&gt;&gt;&gt; data2 = [[1, np.nan], [2, -17]] &gt;&gt;&gt; f2 = pd.DataFrame(data2) &gt;&gt;&gt; f2 0 1 0 1 NaN 1 2 -17.0 &gt;&gt;&gt; f2.values[1, 1] = -99.0 &gt;&gt;&gt; f2 0 1 0 1 NaN 1 2 -17.0 &gt;&gt;&gt; type(f2.values[0, 0]), type(f2.values[1, 0]) (&lt;class 'numpy.float64'&gt;, &lt;class 'numpy.float64'&gt;) </code></pre> <p>I am unable to assign directly to the underlying array using the values attribute. However, if I explicitly start with floats, I can:</p> <pre><code>&gt;&gt;&gt; data = [[1.0, np.nan], [2.0, -17.0]] &gt;&gt;&gt; f = pd.DataFrame(data) &gt;&gt;&gt; f 0 1 0 1.0 NaN 1 2.0 -17.0 &gt;&gt;&gt; f.values[1, 1] = -99.0 &gt;&gt;&gt; f 0 1 0 1.0 NaN 1 2.0 -99.0 </code></pre> <p>Does anyone know a rule that would have allowed me to predict this? I feel like I must be missing something obvious.</p>
0
2016-09-26T01:15:10Z
39,693,522
<p>Pandas does not guarantee when assignments to <code>df.values</code> affect <code>df</code>, so I would recommend <em>never</em> trying to modify <code>df</code> via <code>df.values</code>. How and when this works is an implementation detail. As <a href="http://stackoverflow.com/a/39693521/190597">StevenG states</a>, use <code>df.iloc[1,1] = -99</code> to assign a new value at a location specified by ordinal indices, or use <code>df.set_value</code> to assign a new value at a location specified by index labels.</p> <p>Under the hood, <code>df</code> stores its values in "blocks". The blocks are segregated by dtype, though sometimes more than one block can have the same dtype. The data in each block is stored in a NumPy array.</p> <p>When you use</p> <pre><code>df2 = pd.DataFrame([[1, np.nan], [2, -17]]) </code></pre> <p>The first column has integer dtype while the second column has floating point dtype.</p> <pre><code>In [27]: df2.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 2 entries, 0 to 1 Data columns (total 2 columns): 0 2 non-null int64 1 1 non-null float64 dtypes: float64(1), int64(1) memory usage: 112.0 bytes </code></pre> <p>When you access the <code>df2.values</code> property, a <em>single</em> NumPy array of one homogenous dtype is returned. When the <code>df2</code> has columns of different dtypes, Pandas must promote the dtypes to a single common dtype. In the worst case, the common dtype may be <code>object</code>. In this case, the integers are promoted to floating point dtype. </p> <pre><code>In [28]: df2.values.dtype Out[28]: dtype('float64') </code></pre> <p>The dtype promotion requires that the underlying data from the various blocks be <em>copied</em> into a new NumPy array. Thus, modifying the copy returned by <code>df2.values</code> does not affect the original data in <code>df2</code>.</p> <p>In contrast, if the DataFrame's data is entirely of one dtype, then <code>f.values</code> returns a view of the original data. So in this special case, modifying <code>f.values</code> affects <code>f</code> itself.</p> <hr> <p>To summarize, when a DataFrame contains multiple blocks, <code>df.values</code> will be a copy of the data in <code>df</code>. Modifying the copy in <code>df.values</code> will not affect <code>df</code>.</p> <p>Since a DataFrame can sometimes have multiple blocks of the <em>same dtype</em>, even if all the data in the DataFrame has the same dtype, <code>df.values</code> may still be a copy.</p> <p>If you call <a href="https://github.com/pydata/pandas/blob/master/pandas/core/generic.py#L2802" rel="nofollow"><code>df.consolidate()</code></a> then data of each dtype will be grouped together in a single NumPy array. So if your DataFrame's data consists of a single dtype, and you call <code>df.consolidate()</code> first, then modifying <code>df.values</code> will modify <code>df</code>.</p>
1
2016-09-26T01:29:17Z
[ "python", "pandas" ]
In python how can I add a special case to a regex function?
39,693,490
<p>Say for example I want to remove the following strings from a string: </p> <pre><code>remove = ['\\u266a','\\n'] </code></pre> <p>And I have regex like this:</p> <pre><code>string = re.sub('[^A-Za-z0-9]+', '', string) </code></pre> <p>How can I add "remove" to my regex function?</p>
1
2016-09-26T01:25:12Z
39,693,576
<p>you can always remove them before doing the regex like so:</p> <pre><code>remove = ['\\u266a','\\n'] for substr in remove: string = string.replace(substr, '') </code></pre>
2
2016-09-26T01:36:56Z
[ "python", "regex" ]