Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
1,904,000
58,340,498
Reading YAML file in Python with accents and special charactets
<p>I'm trying to read the following YAML file in Python:</p> <pre><code>countries: IT: "Italia" PT: "Portugal" ES: "España" PE: "Perú" FR: "France" MX: "México" BR: "Brasil" CO: "Colombia" CL: "Chile" ZA: "South Africa" </code></pre> <p>Using this simple code:</p> <pre><code>import yaml with open('file.yaml') as file: countries = yaml.load(file, Loader='yaml.FullLoader') print(countries) </code></pre> <p>But the result I got is the following:</p> <pre><code>{'countries': {'IT': 'Italia', 'PT': 'Portugal', 'ES': 'España', 'PE': 'Perú', 'FR': 'France', 'MX': 'México', 'BR': 'Brasil', 'CO': 'Colombia', 'CL': 'Chile', 'ZA': 'South Africa'}} </code></pre> <p>As you can see, all accents and special characters like "ñ" are all messed up. Any idea why and how to fix it?</p> <p>I'm using Python 3.7</p>
<p>You should read it as UTF-8.</p> <pre><code>with open('file.yaml', 'rt', encoding='utf8') as file: countries = yaml.load(file) </code></pre>
python|yaml
5
1,904,001
45,551,056
Making lists from a dict of lists
<p>I have this <code>dict</code>:</p> <pre><code>{'Hours Outside Sprint': [5.25, 5.0, 0.0], 'Sprint End': ['2017-02-14', '2017-02-14', '2017-02-14'], 'Sprint Start': ['2017-01-31', '2017-01-31', '2017-01-31'], 'Status': ['done', 'done', 'done'], 'Story': ['SPGC-14075', 'SPGC-9456', 'SPGC-9445'], 'Story Actual (Hrs)': [11.0, 12.75, 0.0], 'Story Estimate (Hrs)': [16.0, 12.0, 0.0]} </code></pre> <p>I think this is a fairly simple task but the solution is not apparent at the moment. What I want to do is iterate through this <code>dict</code> and make the following:</p> <pre><code>[[done, 2017-02-14, SPGC-14075, 16.0, 5.25, 2017-01-31, 11.0], ... ] </code></pre> <p>So all the 1st elements of each list go together, all the 2nd, and so on until I have a list of lists. How do I do this?</p> <p>EDIT:</p> <p>Here is what the pandas dataframe looks liek that produced the above dict:</p> <pre class="lang-none prettyprint-override"><code>Story Status Story Estimate (Hrs) Story Actual (Hrs) Hours Outside Sprint Sprint Start Sprint End 0 SPGC-14075 done 16.0 11.00 5.25 2017-01-31 2017-02-14 1 SPGC-9456 done 12.0 12.75 5.00 2017-01-31 2017-02-14 2 SPGC-9445 done 0.0 0.00 0.00 2017-01-31 2017-02-14 </code></pre> <p>Would <code>iterrows</code> work?</p>
<p>Here's how I would do this in Python:</p> <pre><code>df_dict = {'Status': [u'done', u'done', u'done'], 'Sprint End': ['2017-02-14', '2017-02-14', '2017-02-14'], 'Story': [u'SPGC-14075', u'SPGC-9456', u'SPGC-9445'], 'Story Estimate (Hrs)': [16.0, 12.0, 0.0], 'Hours Outside Sprint': [5.25, 5.0, 0.0], 'Sprint Start': ['2017-01-31', '2017-01-31', '2017-01-31'], 'Story Actual (Hrs)': [11.0, 12.75, 0.0]} result = [] lengthOfFirstArrInDict = len(df_dict[df_dict.keys()[0]]) for i in range(0, lengthOfFirstArrInDict): nestedList = [] for key in df_dict.keys(): nestedList.append(df_dict[key][i]) result.append(nestedList) print(result) </code></pre> <p>And here's the output:</p> <pre><code>[['done', '2017-02-14', 'SPGC-14075', 16.0, 5.25, '2017-01-31', 11.0], ['done', '2017-02-14', 'SPGC-9456', 12.0, 5.0, '2017-01-31', 12.75], ['done', '2017-02-14', 'SPGC-9445', 0.0, 0.0, '2017-01-31', 0.0]] </code></pre>
python|list|dictionary
1
1,904,002
28,856,908
Variables in other folder are not the same (Python)
<p>I have a main folder, with a a main method.</p> <p>This is the structure:</p> <p>A main directory</p> <p>subdirectory A subdirectory B</p> <p>Now from the B subdirectory, I would like to access the static variables from a class in A. However, they always end up being 0 (initialization value). When I print from the Main method, the values are correct. When I print from B, the values are incorrect. I have correctly imported everyting, so the class in directory B <em>does</em> recognise classes in A. The only problem seems to be that the class is not correcly included in the total project, and so the variables are instantiated twice, even though the variables are static.</p> <p>How do I include the classes from subdirectory A in subdirectory B correctly?</p> <p>I hope anyone can help, been seaching for hours now to find the answer.</p>
<p>I did not get any response, so my solution was to make a class in my main directory that stores the variables and replace all references to those variables. I guess the way I designed this code was bad practice anyway. It is working now.</p>
python|import|subdirectory
0
1,904,003
28,528,932
MySQL - can't define foreign key
<p>I'm trying to create tables on Wamp server using Python. There are two tables - person and message. The table message has a column person_id which should be a foreign key for table person. </p> <p>After the tables are created, there is no foreign key in message table when I look at it via PhpMyAdmin. Is there something wrong with SQL queries? </p> <p>Creation of person:</p> <pre><code>@staticmethod def createTablePerson(): return "CREATE TABLE IF NOT EXISTS person (" \ "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," \ "name VARCHAR(100)," \ "surname VARCHAR(100)" \ ");" </code></pre> <p>Creation of message:</p> <pre><code>@staticmethod def createTableMessage(): return "CREATE TABLE IF NOT EXISTS message (" \ "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," \ "personID INT NOT NULL REFERENCES person (id)," \ "text VARCHAR(1000)" \ ");" </code></pre>
<blockquote> <p>MySQL parses but ignores “inline <code>REFERENCES</code> specifications” (as defined in the SQL standard) where the references are defined as part of the column specification. MySQL accepts <code>REFERENCES</code> clauses only when specified as part of a separate <code>FOREIGN KEY</code> specification.</p> </blockquote> <p>Reference: <a href="http://dev.mysql.com/doc/refman/5.5/en/create-table.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.5/en/create-table.html</a></p> <hr> <p>So, to add a foreign key constraint (for storage engines that support them), the foreign key has to be defined separately from the column.</p> <p>With this, the REFERENCES clause is ignored:</p> <pre><code>personID INT NOT NULL REFERENCES person (id), </code></pre> <p>To have MySQL add a foreign key constraint, do it like this:</p> <pre><code>personID INT NOT NULL, ... FOREIGN KEY (personID) REFERENCES person (id), ... </code></pre>
python|mysql|phpmyadmin|foreign-keys|wamp
1
1,904,004
28,463,938
a function that chages the structure of a python list
<p>I plan to write a python function that can change the structure of a list. The input is:</p> <pre><code>list=[['A B C','D E F'],['1 2 3 ', '4 5 6 ']] </code></pre> <p>The output is:</p> <pre><code>list=[['A','B','C','D','E','F'],['1','2','3','4','5','6']] </code></pre> <p>I know I need the <code>split()</code> and <code>append()</code>. The confusing part is the loops. Thanks so much!!</p>
<p>Use the join method to join the contain elements in the nested lists. Then split at the spaces.</p> <pre><code>my_list = [['A B C', 'D E F'], ['1 2 3 ', '4 5 6']] my_list = [' '.join(i).split() for i in my_list] </code></pre>
python|string|list
4
1,904,005
14,468,321
Recognize which model object is clicked in Tkinter
<p>I have many overlapping shapes representing irrelevant background items on a canvas. I also have a pattern of non-overlapping circles, each of which is a "hole". Each "hole" sprite (circle) has an associated "hole" object, though never explicitly in the code. (side note: I would love to have a logical association between model and view with these objects, but haven't found a smart way to do that). Each "hole" is different, and has different effects.</p> <p>There is a small circular "ball" which can be dragged into any "hole". I found how to drag and drop from <a href="https://stackoverflow.com/questions/6740855/board-drawing-code-to-move-an-oval/6789351#6789351">this question</a>. I need to find which hole the ball went into.</p> <p>The best way I have found to do that so far is to:</p> <ul> <li><p>create a dict mapping the coordinates of the center of the hole sprite to the hole object</p></li> <li><p>tag each hole like this: </p></li> </ul> <p><code>t=("hole", "hole_at_{}_{}".format(x, y))</code></p> <ul> <li><p>on releasing the ball, do this:</p> <p>def on_ball_release(self, event): '''Process button event when user releases mouse holding ball.'''</p> <pre><code># use small invisible rectangle and find all overlapping items items = self._canvas.find_overlapping(event.x - 10, event.y - 10, event.x + 10, event.y + 10) for item in items: # there should only be 1 overlapping hole if "hole" in self._canvas.gettags(item): # get the coordinates from the tag coords = tuple([int(i) for i in self._canvas.gettags(item)[1].replace("hole_at_", "").split("_")]) # get associated object using dictionary established before hole = self._hole_dict[coords] hole.process_ball() return </code></pre></li> </ul> <p>That seems very messy. I feel there should be some smarter way to do this.</p>
<p>Disclaimer: I don't use Python, but many Tkinter questions can be answered in a useful from an experience with Tcl/Tk, which I have. In this case, it takes some more work to figure out whether what I would do in Tcl is easy to represent with Tkinter.</p> <p>First, I wouldn't add "identifier tags" (<code>hole_at_...</code>): if I have model objects corresponding to canvas items, I would use the item <em>id</em> (which canvas returns during item creation) as an index, to be able to find an object for an item id without parsing tags. (And if I had to add string identifiers, even if I decided to make them from coordinates, I would use <em>that very string</em> as my dictionary key, to avoid reparsing it. Do we need coordinates later? Then make them properties of the <code>hole</code> object).</p> <p>Second, I would use <code>pathName find</code> subcommand with <em>multiple</em> criteria to find (canvas id of) item which is tagged as <code>hole</code> <em>and</em> is nearest to the given point (<code>overlapping</code> is fine when we want to ignore drops too far from any hole, <code>closest</code> is for the case where nearest hole should be used even if it's not too near). Here is the problematic part: does Tkinter support multiple criteria in canvases' <code>$pathName find</code>?</p>
python|tkinter
1
1,904,006
6,566,642
Prepend script's directory to a string
<p>When writing throwaway scripts it's often needed to load a configuration file, image, or some such thing from the same directory as the script. Preferably this should continue to work correctly regardless of the directory the script is executed from, so we may not want to simply rely on the current working directory.</p> <p>Something like this works fine if defined within the same file you're using it from:</p> <pre><code>from os.path import abspath, dirname, join def prepend_script_directory(s): here = dirname(abspath(__file__)) return join(here, s) </code></pre> <p>It's not desirable to copy-paste or rewrite this same function into every module, but there's a problem: if you move it into a separate library, and import as a function, <code>__file__</code> is now referencing some other module and the results are incorrect.</p> <p>We could perhaps use this instead, but it seems like the <code>sys.argv</code> may not be reliable either.</p> <pre><code>def prepend_script_directory(s): here = dirname(abspath(sys.argv[0])) return join(here, s) </code></pre> <p>How to write <code>prepend_script_directory</code> robustly and correctly?</p>
<p>I would personally just <code>os.chdir</code> into the script's directory whenever I execute it. It is just:</p> <pre><code>import os os.chdir(os.path.split(__file__)[0]) </code></pre> <p>However if you did want to refactor this thing into a library, you are in essence wanting a function that is aware of its caller's state. You thus have to make it </p> <pre><code>prepend_script_directory(__file__, blah) </code></pre> <p>If you just wanted to write</p> <pre><code>prepend_script_directory(blah) </code></pre> <p>you'd have to do cpython-specific tricks with stack frames:</p> <pre><code>import inspect def getCallerModule(): # gets globals of module called from, and prints out __file__ global print(inspect.currentframe().f_back.f_globals['__file__']) </code></pre>
python|file|module|path
4
1,904,007
25,674,532
Pythonic Way to Add Space Before Capital Letter If and Only If Previous Letter is Not Also Capital
<p>As the title says, I would like to add spaces before capital letters, but only if the prior letter is not also a capital letter. So <code>'HelloCHARLIE this isBob.'</code> should become <code>'Hello CHARLIE this is Bob.'</code></p>
<pre><code>(?&lt;![A-Z])(?&lt;!^)([A-Z]) print re.sub(r"(?&lt;![A-Z])(?&lt;!^)([A-Z])",r" \1",x) </code></pre> <p>This works.See demo.Use a negative lookbehind to ensure preceding character is not Capital or start of string.</p> <p>See demo.</p> <p><a href="http://regex101.com/r/cH8vN2/1" rel="nofollow">http://regex101.com/r/cH8vN2/1</a></p>
python|regex
3
1,904,008
44,387,283
Running python code on server
<p>I'm building a website with some backprocessing with python. I want to know how to execute my python code from the server ?</p> <p>There is no direct link between my HTML pages and my python code.</p> <p>Let's say I want to do an addition with python in the server, how can I do that ?</p> <p>Thanks so much in advence :)</p>
<p>is your server is linux or windows?</p> <p>for linux: you can add a script to run your script on runlevel 3 or 5 write a script put it under /etc/init.d/ folder then link your script /etc/rc3.d or /etc/rc5.d to be start </p>
python|server
0
1,904,009
23,497,599
COM "get property" with multiple arguments
<p>I'm trying to call <a href="http://msdn.microsoft.com/en-us/library/aa369461%28v=vs.85%29.aspx" rel="noreferrer">WindowsInstaller.Installer.ProductsEx</a> from python, and can't figure out how to make it work.</p> <p>Here's a vbscript version of what I want to call from python:</p> <pre class="lang-vb prettyprint-override"><code>dim msi, products set msi = CreateObject("WindowsInstaller.Installer") set products = msi.ProductsEx("", "s-1-1-0", 7) </code></pre> <p>I think my issue is <code>ProductsEx</code> is a read-only get property that takes 3 arguments, and I don't know how to convince <code>win32com</code> or <code>comtypes</code> to call it that way.</p> <p>I tried:</p> <pre><code>&gt;&gt;&gt; import win32com.client &gt;&gt;&gt; msi = win32com.client.Dispatch('WindowsInstaller.Installer') &gt;&gt;&gt; products = msi.ProductsEx('', 's-1-1-0', 7) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;COMObject WindowsInstaller.Installer&gt;", line 2, in ProductsEx pywintypes.com_error: (-2147352573, 'Member not found.', None, None) </code></pre> <p>and similiar using <code>comtypes</code>:</p> <pre><code>&gt;&gt;&gt; import comtypes.client &gt;&gt;&gt; msi = comtypes.client.CreateObject('WindowsInstaller.Installer') &gt;&gt;&gt; products = msi.ProductsEx['', 's-1-1-0', 7] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\site-packages\comtypes\client\dynamic.py", line 46, in __getitem__ **dict(_invkind=comtypes.automation.DISPATCH_PROPERTYGET)) File "C:\Python27\lib\site-packages\comtypes\automation.py", line 768, in Invoke args)) _ctypes.COMError: (-2147352571, 'Type mismatch.', ('TypeError: Parameter 1', (('', 's-1-1-0', 7),))) </code></pre> <p>I think I got closer in <code>comtypes</code> since <code>DISPATCH_PROPERTYGET</code> is what I want to do. In both libs I tried every syntax I could think of:</p> <ul> <li><code>msi.ProductsEx(['', 's-1-1-0', 7])</code></li> <li><code>msi.ProductsEx[['', 's-1-1-0', 7]]</code></li> <li><code>msi.ProductsEx['']['s-1-1-0'][7]</code></li> <li><code>None</code> instead of <code>''</code></li> <li>tuples instead of lists</li> </ul> <p>How do I call a COM "get" property with multiple arguments from python?</p>
<p>Use Get/Set </p> <pre><code>msi.<b>Get</b>ProductsEx("", "s-1-1-0", 7)</code></pre>
python|com|win32com|comtypes
0
1,904,010
23,597,533
List items are not changed in for loop
<p>I was shocked when the following code did not do what I expected it to do:</p> <pre><code>lines_list = ['this is line 1\n', 'this is line 2\n', 'this is line 3\n'] for line in lines_list: line = line.strip() </code></pre> <p>In <strong>Perl</strong> or in <strong>Java</strong>, my usage works well. Python is the one with the unique behavior.</p> <p>In Java this will work:</p> <pre class="lang-java prettyprint-override"><code>String[] lines = {&quot;this is line 1\n&quot;, &quot;this is line 2\n&quot;, &quot;this is line 3\n&quot;}; for (String line : lines) { line = line.trim(); } </code></pre> <p>In Perl this will work:</p> <pre class="lang-perl prettyprint-override"><code>my @lines = (&quot;this is line 1\n&quot;, &quot;this is line 2\n&quot;, &quot;this is line 3\n&quot;); foreach my $line (@lines) { $line =~ s/\s+$//; $line =~ s/^\s+//; } </code></pre> <p>I of course expected each item in the list to become <code>&quot;stripped&quot;</code>, i.e. in this case, to be free of the trailing <code>'\n'</code> char, but it did not...</p> <pre><code>print lines_list </code></pre> <p>The output:</p> <pre><code>['this is line 1\n', 'this is line 2\n', 'this is line 3\n'] </code></pre> <p>Is there an elegant way to change the list items during the <code>for</code> loop? I don't want to duplicate the list...</p>
<p>You can go through by index and modify in place that way</p> <pre><code>for i, _ in enumerate(lines_list): lines_list[i] = lines_list[i].strip() </code></pre> <p>though I think many would prefer the simplicity of duplicating the list if the list isn't so big that it causes an issue</p> <pre><code>lines_list = [line.strip() for line in lines_list] </code></pre> <p>The issue is using the <code>=</code> operator reassigns to the variable <code>line</code>, it doesn't do anything to affect the contents of the original string. New python programmers are equally as often surprised when:</p> <pre><code>for i in range(10): print(i) i += 1 </code></pre> <p>prints the numbers 0,1,2,3,4,5,6,7,8,9. This occurs because the for loop reassigns <code>i</code> at the beginning of each iteration to the next element in the range. It's not exactly your problem, but it's similar.</p> <p>Since you are reading lines out of a file, and stripping them afterwards, really what you should do is</p> <pre><code>with open(file_name) as f: lines_list = [line.strip() for line in f] </code></pre> <p>which reads and strips one line at a time, rather than reading everything first, then stripping the lines afterwards</p>
python|list|loops
4
1,904,011
24,182,043
Pygame Snake Game
<p>Okay, this is my first time on this site, so I hope I get this right.</p> <p>I am making a snake game in Pygame, for a school assessment task, and I have a problem. I am unable to get the snake's body parts to disappear.</p> <p>Currently, this is how a body part is generated:</p> <pre><code>def more_body(bodyparts, x, y, z): body = pygame.sprite.Sprite() body.image = pygame.image.load('body.png') body.rect = head.image.get_rect() body.rect.right = x body.rect.top = y body.timeleft = z bodyparts.add(body) </code></pre> <p>The body deletion check, as is, works like this.</p> <pre><code>for x in bodyparts: body.timeleft -= 1 if body.timeleft == 0: body = False </code></pre> <p>Bodyparts is, fairly obviously, the grouping for the bodyparts. It's an OrderedUpdates sprite group.</p> <p>The problem is that the code doesn't seem to like this solution. Currently, the error is listed as "NameError: name 'body' is not defined". If I try to expand it the the check to reference bodyparts.body.timeleft instead of body.timeleft, I instead get "AttributeError: 'OrderedUpdates' object has no attribute 'body'".</p> <p>There is a second solution I've come up with. As bodyparts is an OrderedUpdates group, it should be possible to select and delete specific pieces based on their location in the list. Therefore, the steps planned are as follows:</p> <ol> <li>Compare the len(bodyparts) to a previously-set variable.</li> <li>If the length exceeds how long the snake should be, delete the first item added to bodyparts - I'm not sure if this would be the first or last.</li> </ol> <p>My main questions are:</p> <p>Is this a viable solution, and would you be able to provide code to do it? Can I just treat it like a list, and split it so that the front (or back, depending on how they're added) of the bodyparts group is dropped? Any solutions you could provide would be of great help.</p>
<pre><code>for x in bodyparts: body.timeleft -= 1 if body.timeleft == 0: body = False </code></pre> <p>Here, you iterate over the sprite group, storing each sprite in the variable <code>x</code>. You never define <code>body</code>, so an exception is raised. </p> <p>Even if you did, setting <code>body</code> to <code>False</code> would not magically remove the sprite from the sprite group. To do so, you the <a href="http://pygame.org/docs/ref/sprite.html#pygame.sprite.Group.remove" rel="nofollow"><code>remove</code></a> method.</p> <p>So you should change your loop to:</p> <pre><code>for body in bodyparts: body.timeleft -= 1 if body.timeleft == 0: bodyparts.remove(body) </code></pre> <hr> <p>Instead of using a sprite group, you could also use a simple list, and remove elements once it gets too big:</p> <pre><code>max_len = 4 # current max length of snake bodyparts = [] def more_body(bodyparts, x, y, z): body = ... bodyparts.append(body) bodyparts=bodyparts[-max_len:] </code></pre> <p>Also, you should load your image <code>'body.png'</code> only once and reuse it, instead of loading it everytime.</p>
python|pygame
2
1,904,012
20,502,648
Motor error: callback is required
<p>Using sample code from <a href="https://motor.readthedocs.org/en/latest/tutorial.html" rel="nofollow">motor tutorial</a>.</p> <pre><code>from tornado import gen db = motor.MotorClient('localhost', 1235).open_sync().packmon @gen.coroutine def do_find(): cursor = db.test_collection.find() for document in (yield cursor.to_list(length=100)): print document tornado.ioloop.IOLoop.current().run_sync(do_find) </code></pre> <p>Getting traceback:</p> <pre><code>Traceback (most recent call last): File "app_main.py", line 51, in run_toplevel File "chat.py", line 22, in &lt;module&gt; tornado.ioloop.IOLoop.current().run_sync(do_find) File "/home/user/venv/packmon-pypy/site-packages/tornado/ioloop.py", line 370, in run_sync return future_cell[0].result() File "/home/user/venv/packmon-pypy/site-packages/tornado/concurrent.py", line 129, in result raise_exc_info(self.__exc_info) File "/home/user/venv/packmon-pypy/site-packages/tornado/gen.py", line 221, in wrapper runner.run() File "/home/user/venv/packmon-pypy/site-packages/tornado/gen.py", line 507, in run yielded = self.gen.send(next) File "chat.py", line 19, in do_find for document in (yield cursor.to_list(length=100)): File "/home/user/venv/packmon-pypy/site-packages/motor/__init__.py", line 1465, in to_list check_callable(callback, required=True) File "/home/user/venv/packmon-pypy/site-packages/motor/__init__.py", line 74, in check_callable raise TypeError("callback is required") TypeError: callback is required </code></pre> <p>The documentation says this should return a Future if no callback is passed, but it throws an exception instead. Using gen.Task does the work, but I don't understand why a straightforward example from the tutorial does not work.</p>
<p>You used the "latest" tutorial with the "stable" code. <a href="http://motor.readthedocs.org/en/stable/tutorial.html" rel="nofollow">Read the "stable" tutorial instead.</a></p> <p>Background: <a href="https://pypi.python.org/pypi/motor" rel="nofollow">Motor on PyPI is at version 0.1.2</a>. Version 0.1.2 is the current "stable" version with a callback-based API. You can use it with <code>gen.Task</code>, as the "stable" tutorial demonstrates. As the tutorial will tell you, you should actually use <code>motor.Op</code>, which is like <code>gen.Task</code> with better exception semantics.</p> <p>The "latest" tutorial you were reading reflects the extremely unstable code I have in Motor's master branch on GitHub. This will be released as Motor 0.2 within the next couple months and become the new "stable." Meanwhile, please follow the current "stable" documentation.</p>
python|mongodb|tornado|tornado-motor
2
1,904,013
20,429,857
How to remove a string from a list of strings if its length is lower than the length of the string with max length in Python 2.7?
<p><em>How to remove a string from a list of strings if its length is lower than the length of the string with max length in Python 2.7?</em></p> <p>Basically, if I have a list such as:</p> <pre><code>test = ['cat', 'dog', 'house', 'a', 'range', 'abc'] max_only(test) </code></pre> <p>The output should be:</p> <pre><code>['house', 'range'] </code></pre> <p>'cat''s length is 3, 'dog' is 3, 'house' is 5, 'a' is 1, 'range' is 5, 'abc' is 3. The string with the highest length are 'house' and 'range', so they're returned.</p> <p>I tried with something like this but, of course, it doesn't work :)</p> <pre><code>def max_only(lst): ans_lst = [] for i in lst: ans_lst.append(len(i)) for k in range(len(lst)): if len(i) &lt; max(ans_lst): lst.remove(lst[ans_lst.index(max(ans_lst))]) return lst </code></pre> <p>Could you help me?</p> <p>Thank you.</p> <p><strong>EDIT: What about the same thing for the min length element?</strong></p>
<p>Use a list comprehension and <code>max</code>:</p> <pre><code>&gt;&gt;&gt; test = ['cat', 'dog', 'house', 'a', 'range', 'abc'] &gt;&gt;&gt; max_ = max(len(x) for x in test) #Find the length of longest string. &gt;&gt;&gt; [x for x in test if len(x) == max_] #Filter out all strings that are not equal to max_ ['house', 'range'] </code></pre>
python|list|string-length
7
1,904,014
71,889,836
pycharm debug on m1 mac fails with: `pydevd_cython_darwin_310_64.cpython-310-darwin.so incompatible architecture`
<p>I just upgraded to pycharm 2022.01 and got an error when debugging a python program using m1 mac:</p> <pre><code>Traceback (most recent call last): File &quot;/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_cython_wrapper.py&quot;, line 8, in &lt;module&gt; from _pydevd_bundle_ext import pydevd_cython as mod ModuleNotFoundError: No module named '_pydevd_bundle_ext' During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_cython_wrapper.py&quot;, line 11, in &lt;module&gt; from _pydevd_bundle import pydevd_cython as mod ImportError: cannot import name 'pydevd_cython' from '_pydevd_bundle' (/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py&quot;, line 55, in &lt;module&gt; from _pydevd_bundle.pydevd_trace_dispatch import ( File &quot;/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_trace_dispatch.py&quot;, line 42, in &lt;module&gt; from _pydevd_bundle.pydevd_cython_wrapper import trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func File &quot;/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_cython_wrapper.py&quot;, line 35, in &lt;module&gt; mod = getattr(__import__(check_name), mod_name) ImportError: dlopen(/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_cython_darwin_310_64.cpython-310-darwin.so, 0x0002): tried: '/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_cython_darwin_310_64.cpython-310-darwin.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')) Process finished with exit code 1 </code></pre> <p>I installed the right version of pycharm. Couldn't find the right <code>.so</code> version on pypi. How can I fix this? Is it possible to recompile pydevd for arm64e?</p>
<p>Managed to rebuild <a href="https://github.com/fabioz/PyDev.Debugger" rel="nofollow noreferrer"><code>pydevd</code></a> that comes with PyCharm:</p> <h3>Rebuild the binaries</h3> <p>Make sure you have <a href="https://pypi.org/project/Cython/" rel="nofollow noreferrer"><code>cython</code></a> installed to update and compile the cython sources:</p> <pre><code>sudo pip3 install cython export PYTHONPATH=/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev:$PYTHONPATH cd /Applications/PyCharm.app/Contents/plugins/python/helpers/pydev python3.10 build_tools/build.py </code></pre> <p>After that, debugging in PyCharm worked fine.</p> <h3>Check the binaries</h3> <p>What the rebuild apparently did:</p> <ol> <li>removed all <code>_pydevd_bundle/pydevd_cython_darwin_*.so</code> files</li> <li>created only <code>_pydevd_bundle/pydevd_cython.cpython-310-darwin.so</code></li> </ol> <p>Use the <a href="https://superuser.com/questions/180458/what-command-shows-the-architecture-of-a-binary-file-on-mac#180459"><code>file</code></a> command to confirm the binary has the architecture required for new M1 (Apple Silicon) chips:</p> <pre class="lang-sh prettyprint-override"><code>file _pydevd_bundle/pydevd_cython.cpython-310-darwin.so` </code></pre> <p>It should output required architecture for M1 like <code>arm64</code> below:</p> <pre><code>_pydevd_bundle/pydevd_cython.cpython-310-darwin.so: Mach-O 64-bit bundle arm64 </code></pre>
python|pycharm|apple-m1
2
1,904,015
15,257,534
Django forms.ModelForm, Pylint, and new/old style classes
<p>I have a Django 1.5 form that looks like this (simplified):</p> <pre><code>class BidForm(forms.ModelForm): class Meta: fields = ( ) model = Bid def __init__(self, *args, **kwargs): super(BidForm, self).__init__(*args, **kwargs) something() </code></pre> <p>When I run Pylint on this, I get a this error:</p> <pre><code>E1002:&lt;line,row&gt;:BidForm.__init__: Use of super on an old style class </code></pre> <p>I assume this means the Django's forms.ModelForm is an old-style class and per the <a href="http://docs.python.org/2/library/functions.html#super">python docs</a> my call to super is not happening and is therefore extraneous. Is this true? Can I just delete the super call without effect?</p>
<p>No. Pylint, great though it is, is far from infallible, and in this case has just got it wrong. ModelForm is a new style class and the super is needed.</p>
python|django|pylint
9
1,904,016
29,371,970
Unable to get repr for <class 'mongoengine.queryset.queryset.QuerySet'>
<p>When using mongoengine and django ORM the following exception is thrown. </p> <pre><code>Unable to get repr for &lt;class 'mongoengine.queryset.queryset.QuerySet'&gt; </code></pre> <p>the strange thing is that it is running on one machine without throwing this error (after installing the needed packages on both)</p> <p>the model as following: </p> <pre><code>class Purchase(Document): _id = DynamicField(primary_key=True) customer_id = IntField() product_id = IntField() price = DynamicField() page = IntField() name = DynamicField() </code></pre> <p>and the exception is thrown when: </p> <p>Tags.objects.all()</p> <p>i looked the internet to find about this issue, and i could not find an answer.</p> <p>anyone have any idea of what might cause this? (i'm guessing that differences between module versions)</p>
<p>you need to implement the <code>__repr__</code> method on the class like:</p> <pre><code>class Purchase(Document): enter code here`_id = DynamicField(primary_key=True) customer_id = IntField() product_id = IntField() price = DynamicField() page = IntField() name = DynamicField() def __repr__(self): return 'Customer ID: ' + str(self.custmer.id) </code></pre>
python|orm|mongoengine
1
1,904,017
46,307,916
Using raw_input to create a list of numbers and making the list an integer
<p>I'm creating a bubble sort program and need need the raw_input list to be integers. </p> <pre><code>alist=int(raw_input('Enter list of numbers----&gt;') print(alist) for k in range(0,5): for i in range(0,5): if alist[i]&gt;alist[i+1]: swap=alist[i] alist[i]=alist[i+1] alist[i+1]=swap print(alist) print(alist) </code></pre>
<p>I don't know what you trying to achieve but to get a list of numbers from raw_input try this.</p> <pre><code>list_input = raw_input('Enter list of numbers----&gt; ') # Using list comprehension separate the string by commas, then convert to an integer. int_list = [int(i) for i in list_input.split(',')] print int_list </code></pre>
python|integer|raw-input
0
1,904,018
49,477,563
How to remove the grey background from canvases in tkinter
<p>I am making my first GUI just for fun, and was wondering if it's possible, and if so how to remove the greyish background from around my canvases. I am also aware the code is very messy; this is my first time doing anything with Tkinter.</p> <p>Also just to clarify the project itself is 100% hypothetical and I have no intention whatsoever to use it for any malicious purposes.</p> <pre><code> import tkinter as tk canvas_width = 400 canvas_height = 20 colours = ("#476042", "yellow") box=[] #---- Main Window ---- window = tk.Tk() window.title("Krypto Locker V1.0") window.geometry("400x400") window.resizable(width=True, height=True) #--- Background ----- C = tk.Canvas(window, bg="blue", height=250, width=300) filename = tk.PhotoImage(file = "C:\\Users\\lauchlan\\Desktop\\Programing\\project\\resources\\image.png") background_label = tk.Label(window, image=filename) background_label.place(x=0, y=0, relwidth=1, relheight=1) C.pack() #--------------------- #--- Functions ----- def countdown(count): # change text in label label['text'] = count if count &gt; 0: # call countdown again after 1000ms (1s) window.after(1000, countdown, count-1) #--- Main Interface ---- #-- Text Widget 1 -- w = tk.Canvas(window, width=canvas_width, height=canvas_height) w.pack() w.create_text(canvas_width / 2, canvas_height / 2, text="Welcome to Krytpto Locker V1.0 ") w.place(x=10, y=20,) #-- Text Widget 2 -- e = tk.Canvas(window, width=500, height=20) e.pack() e.create_text(canvas_width / 2, canvas_height / 2, text="All your personal files will soon be encrypted! ") e.place(x=10, y=40,) #-- Text Widget 3 -- h = tk.Canvas(window, width=500, height=500) h.pack() h.create_text( 195 / 1, 40 / 1, text="‌‌ ‌‌ Hello, you're computer has been infected by Krypto Locker all your \npersonal files will soon be encrypted and deleted in order to prevent this \n‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ you will be required to send $300 to a secure bitcoin wallet\n ‌‌ ‌‌ ‌‌ ‌‌ you will then recieve an email containing a recovery password") h.place(x=10, y=70,) #--- Countdown Timer ------------------------------------- #-- Text -- m = tk.Canvas(window, width=500, height=500) m.pack() m.create_text(80 / 1, 50 / 1, text="Time Until Files Encrypted : ") m.place(x=1, y=339,) #-- Timer -- label = tk.Label(window) label.place(x=155, y=380,) countdown(1000) #--------------------------------------------------------- #--- Recovery Password Box ------------------------------------- #---- Text --- l = tk.Canvas(window, width=500, height=100) l.pack() l.create_text(80 / 1, 50 / 1, text="Enter Recovery Password : ") l.place(x=1, y=250,) #---- Entry Box ---- password = tk.Entry(window) password.place(x=165, y=292) #---- Submit Button ---- submit = tk.Button(window, text="Submit",) submit.place(x=300, y=289) #---------------------------------------------------------------- tk.mainloop() </code></pre> <p><a href="https://i.stack.imgur.com/DAvd2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DAvd2.png" alt="What the program looks like currently"></a></p>
<p>Add the following to change the colour, just before the tk.mainloop:</p> <pre><code>h.config(background="snow") l.config(background="snow") m.config(background="snow") e.config(background="snow") w.config(background="snow") C.config(background="snow") </code></pre> <p>You can't make the canvas transparent. Also, the better practice is to add the text and other widgets to the tkinter window (if you want the image to show maximum).</p>
python|tkinter|tkinter-canvas
0
1,904,019
21,002,755
Returning in multiprocessing - Python
<p>I'm working on a code for visualization. First of all, I have to generate a large number of images. So, I though about parallelize this process. Until now, I have this code:</p> <pre><code>class ImageData(object): def __init__(self, width, height, range_min=-1, range_max=1): """ The ImageData constructor """ self.width = width self.height = height #The values range each pixel can assume self.range_min = range_min self.range_max = range_max self.data = [] for i in range(width): self.data.append([0] * height) def shepard_interpolation(self, queue, seeds=10): """ Perform a Shepard shepard_interpolation :param queue :param seeds """ points = [] f = [] for s in range(seeds): # Generate a pixel position pos_x = random.randrange(self.width) pos_y = random.randrange(self.height) # Save the f(x,y) data x = Utils.translate_range(pos_x, 0, self.width, self.range_min, self.range_max) y = Utils.translate_range(pos_y, 0, self.height, self.range_min, self.range_max) z = Utils.function(x, y) points.append([x, y]) f.append(z) for i in range(self.width): xt = (Utils.translate_range(i, 0, self.width, self.range_min, self.range_max)) for j in range(self.height): yt = (Utils.translate_range(j, 0, self.height, self.range_min, self.range_max)) self.data[i][j] = Utils.shepard_euclidian(points, f, [xt, yt], 3) queue.put(self) class Utils: def __init__(self): pass @staticmethod def shepard_euclidian(x, z, p, u): n = len(x) d = [0.0] * n for i in range(n-1): pi = x[i] d[i] = math.pow(math.hypot(pi[0]-p[0], pi[1]-p[1]), u) w = [0.0] * n sw = 0.0 for i in range(n-1): w[i] = 1.0 for k in range(n-1): if i != k: w[i] *= d[k] sw += w[i] for i in range(len(w)-1): if sw != 0.0: w[i] /= sw else: w[i] = 0.0 c = 0.0 for i in range(n): c += (w[i] * z[i]) return c if __name__ == '__main__': q = Queue() processes = [Process(target=ImageData.shepard_interpolation, args=(ImageData(50, 50), q,)) for _ in range(2)] for process in processes: process.start() for process in processes: print "Trying to join" process.join() if hasattr(os, 'getppid'): # only available on Unix print process.pid, 'joining', os.getppid() print "Finish" </code></pre> <p>The problem is cause some of my process never ends. I found that if I comment the line <code>queue.put(self)</code>, in <code>queue.put(self)</code>, all process finish, but I don't receive any return. But if I uncommented this line, I receive the print <strong>Trying to join</strong>, but it never ends. I really don't know what is the problem. I though about process trying to write in the queue at the same time, but I discovered that this is already managed by it. I don't have any clue about what is the problem.</p> <p>Any help would be very appreciated. Thank you in advance.</p>
<p>You're probably overflowing the queue. Multiprocessing queues are based on FIFOs, and have a fixed buffer size. You should try to queue.get() the data in the main routine before you join the processes.</p> <p>shameless plug: consider using my <a href="https://github.com/gatoatigrado/vimap" rel="nofollow">vimap</a> library. it works around a lot of multiprocessing weirdness.</p>
python|queue|return|multiprocessing
1
1,904,020
53,617,511
Python3, round() type inconsistent. Proper way to round a float value to index a list or an array
<p>I precise that I am aware of the concepts about decimal representation and the supposedly relevant questions such as <a href="https://stackoverflow.com/questions/13716057/how-to-round-a-float-value">this</a>, <a href="https://stackoverflow.com/questions/43968097/python-float-vs-numpy-float32">this</a> and <a href="https://stackoverflow.com/questions/588004/is-floating-point-math-broken">this</a>, and the suggested <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow noreferrer">documentation</a>.</p> <p>Still <strong>I am astonished that in Python3 <code>round()</code> sometimes returns an integer</strong> (as per the <a href="https://docs.python.org/3.5/library/functions.html#round" rel="nofollow noreferrer">documentation</a>) <strong>and sometimes a float</strong> (weird to me), <strong>depending upon an unsignificant difference in the <em>type</em> of its <em>first</em> argument</strong>. </p> <p>I understand that, e.g., <code>floor()</code> or <code>ceil()</code> <em>always</em> return a float, and of course I found reasonable that <code>round(x, digits)</code> returns an integer or a float depending on the second parameter <code>digits</code> being specified or not, and even that different implementations of <code>round</code> exist (e.g. the <code>builtin</code> and the <code>numpy</code> one). </p> <p>Specifically, <strong>the following code shows that a <code>float32</code> and a <code>numpy.float32</code> make <code>round()</code> return different types</strong>:</p> <pre><code> &gt;&gt;&gt; x=101/100 &gt;&gt;&gt; x 1.01 &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; nx=np.float32(x) &gt;&gt;&gt; nx 1.01 &gt;&gt;&gt; round(x) 1 &gt;&gt;&gt; round(nx) 1.0 </code></pre> <p>For the curious, I get my <code>x</code> value as the prediction of a classification model in Keras, and need to obtain an index out of it, by rounding to the nearest integer, to select the right label out of a list of strings.</p> <p>And a search in StackOverflow/Stackexchange doesn't reveal the matter was already treated. Pls give me a helpful link in case.</p> <p>To be more specific, I am getting a predicted value out of a Neural Network classifier, i.e. a number approaching either 0 or 1 or another integer, and want to use it as an index to print the correct label associated to the prediction (it should be an almost basic need).</p> <p>The solution is quite simple, although ugly: <code>int(round(x))</code> (also explained <a href="https://stackoverflow.com/questions/36371424/round-a-float-and-convert-it-to-an-integer-in-a-python2-and-python3-compatible-m">here</a>); but I still consider it a kind of workaround to an undesired behaviour.</p> <p>I know that <em>why does this work so</em> questions are not appreciated, so let's ask <em>what</em> is the correct pythonic way to obtain that integer and that label out of a <code>numpy.float32</code> value, in the hope that somebody unveils also an interesting rationale behind this ...ehm... functionality.</p>
<p><code>round</code> delegates to the object's <code>__round__</code> method.</p> <pre><code>In [367]: x = 123.34 In [368]: x.__round__() Out[368]: 123 In [369]: np.float64(x).__round__() Out[369]: 123.0 </code></pre> <p>Apparently this numpy round returns a matching type</p> <pre><code>In [376]: type(np.float(x).__round__()) Out[376]: int In [377]: type(np.float32(x).__round__()) Out[377]: numpy.float32 In [378]: type(np.float64(x).__round__()) Out[378]: numpy.float64 In [379]: type(np.int32(x).__round__()) Out[379]: numpy.int32 </code></pre> <p>So <code>int(round(x))</code> probably is the cleanest way of making sure you have an integer if there's a possibility that <code>x</code> is one of the numpy floats.</p>
python-3.x|list|numpy|indexing|rounding
3
1,904,021
73,698,041
How retain_grad() in pytorch works? I found its position changes the grad result
<p>in a simple test in pytorch, I want to see grad in a non-leaf tensor, so I use retain_grad():</p> <pre><code>import torch a = torch.tensor([1.], requires_grad=True) y = torch.zeros((10)) gt = torch.zeros((10)) y[0] = a y[1] = y[0] * 2 y.retain_grad() loss = torch.sum((y-gt) ** 2) loss.backward() print(y.grad) </code></pre> <p>it gives me a normal output:</p> <pre><code>tensor([2., 4., 0., 0., 0., 0., 0., 0., 0., 0.]) </code></pre> <p>but when I use retain grad() before y[1] and after y[0] is assigned:</p> <pre><code>import torch a = torch.tensor([1.], requires_grad=True) y = torch.zeros((10)) gt = torch.zeros((10)) y[0] = a y.retain_grad() y[1] = y[0] * 2 loss = torch.sum((y-gt) ** 2) loss.backward() print(y.grad) </code></pre> <p>now the output changes to:</p> <pre><code>tensor([10., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) </code></pre> <p>I can't understand the result at all.</p>
<p>Okay so what's going on is really weird.</p> <p>What <code>.retain_grad()</code> essentially does is convert any non-leaf tensor into a leaf tensor, such that it contains a <code>.grad</code> attribute (since by default, pytorch computes gradients to leaf tensors only).</p> <p>Hence, in your first example, after calling <code>y.retain_grad()</code>, it basically converted <code>y</code> into a leaf tensor with an accessible <code>.grad</code> attribute.</p> <p>However, in your second example, you initially converted the entire <code>y</code> tensor into a leaf tensor; <strong>then</strong>, you created a non-leaf tensor <code>(y[1])</code> <strong>within</strong> your leaf tensor <code>(y)</code>, which is what caused the confusion.</p> <pre><code>y = torch.zeros((10)) # y is a non-leaf tensor y[0] = a # y[0] is a non-leaf tensor y.retain_grad() # y is a leaf tensor (including y[1]) y[1] = y[0] * 2 # y[1] is a non-leaf tensor, BUT y[0], y[2], y[3], ..., y[9] are all leaf tensors! </code></pre> <p>The confusing part is:</p> <p><code>y[1]</code> <strong>after</strong> calling <code>y.retain_grad()</code> <strong>is</strong> now a leaf tensor with a <code>.grad</code> attribute. However, <code>y[1]</code> <strong>after</strong> the computation <code>(y[1] = y[0] * 2)</code> is now <strong>not</strong> a leaf tensor with a <code>.grad</code> attribute; it is now treated as a new non-leaf variable/tensor.</p> <p>Therefore, when calling <code>loss.backward()</code>, the Chain rule of the <code>loss</code> w.r.t <code>y</code>, and particularly looking at the Chain rule of the <code>loss</code> w.r.t leaf <code>y[1]</code> now looks something like this:</p> <hr /> <p><a href="https://i.stack.imgur.com/uvCQo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uvCQo.png" alt="Chain rule" /></a></p>
python|pytorch
1
1,904,022
21,519,639
Level system based off points
<p>I'm trying to make a level system based off of points, but it's kinda getting too long of a code. If you can help me make it smaller I really would appreciated it. To describe what it's suppose to do is get the points and to see what level they are at and if they level up it will tell how many times they level and what level they are at now. I want it to go up to 100 and get harder to level up when getting higher up.. Here's what I have so far:</p> <pre><code> def pointLevel(name): point = Point.dPoint[name] points, lvl = int(point), int(lvl) if points &lt; 500: lvl = 1 elif points &lt; 1500: lvl = 2 elif points &lt; 2500: lvl = 3 elif points &lt; 5000: lvl = 4 elif points &lt; 10000: lvl = 5 elif points &lt; 15000: lvl = 6 elif points &lt; 20000: lvl = 7 elif points &lt; 30000: lvl = 8 elif points &lt; 50000: lvl = 9 elif points &lt; 100000: lvl = 10 elif points &lt; 250000: lvl = 11 notes.store("levels", user.name, "You have leveled up. You are now level "+str(lvl)+"!", int(time.time())) </code></pre>
<p>Just to shorten your code you can save levels as a list and then count how many levels user have passed by comparing points to the level splits:</p> <pre><code>levels = [100, 200, 300, 400, 500] lvl = len([x for x in levels if points &gt; x]) </code></pre> <p>I wouldn't worry about the speed here, but using generator could be considered as a better practice (or not, a matter of taste in this case):</p> <pre><code>lvl = sum(1 for x in levels if points &gt; x) </code></pre>
python
5
1,904,023
21,554,357
Defining function to check if string is valid
<pre><code>letters1 = "abcdefghijklmnopqrstuvwxyz" letters2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def is_valid(strs): char_b = True for char in range(0, len(strs)): if strs[char] not in (letters1 or letters2): char_b == False return char_b </code></pre> <p>I don't understand why this won't work, anyone mind giving me a hint? It just always returns true.</p>
<p>You need to <strong>set</strong> <code>char_b</code>, not test for equality. Replace:</p> <pre><code>char_b == False </code></pre> <p>with</p> <pre><code>char_b = False </code></pre> <p>Your test is incorrect:</p> <pre><code>if strs[char] not in letters1 + letters2: </code></pre> <p>or simplify your function to:</p> <pre><code>def is_valid(strs): return strs.isalpha() </code></pre>
python
2
1,904,024
24,846,639
In python/pandas how to search for nearest value?
<p>I have an array like this</p> <pre><code>sp500=Quandl.get("YAHOO/INDEX_GSPC") Open High Low Close Volume Adjusted Close returns vols Date 1950-05-26 18.67 18.67 18.67 18.67 1330000 18.67 -0.001070 0.091246 1950-05-29 18.72 18.72 18.72 18.72 1110000 18.72 0.002678 0.078494 1950-05-31 18.78 18.78 18.78 18.78 1530000 18.78 0.003205 0.073638 1950-06-01 18.77 18.77 18.77 18.77 1580000 18.77 -0.000532 0.069189 1950-06-02 18.79 18.79 18.79 18.79 1450000 18.79 0.001066 0.059300 </code></pre> <p>At any date I want to find the days since vol was lower than 5%. So for instance at 1950-05-26, I will start searching backwards until I find a vol &lt; 5% and calculate the day difference between that day and 1950-05-26. The exact functionality is simply "Days Since" this happened!</p> <p>Is there any easier way to do this?</p> <p>What I had in mind was using np.where(x&lt;0.10) and then using the index to calculate day difference. np.where can be inside pd.rolling_apply for a window of 100 indices backwards. yes 100 indices backward will be the assumption of max lookup before it finds the sweet spot.</p> <p>Any better ideaz than my extremely crude one highlighted above???</p>
<p>Assuming that your data-frame is sorted in the index, you may combine <code>numpy.where</code> and <code>Series.fillna</code> to obtain the last day which vols where below some threshold. for example, starting with </p> <pre><code>&gt;&gt;&gt; df vols Date 2014-07-10 0.045 2014-07-11 0.057 2014-07-12 0.064 2014-07-13 0.003 2014-07-14 0.021 2014-07-15 0.052 2014-07-16 0.090 </code></pre> <p>this would be</p> <pre><code>&gt;&gt;&gt; df['tick'] = np.where(df.vols &lt; .05, df.index, pd.tslib.NaT) &gt;&gt;&gt; df vols tick Date 2014-07-10 0.045 2014-07-10 2014-07-11 0.057 NaN 2014-07-12 0.064 NaN 2014-07-13 0.003 2014-07-13 2014-07-14 0.021 2014-07-14 2014-07-15 0.052 NaN 2014-07-16 0.090 NaN </code></pre> <p>and then forward fill, and obtain the day difference with respect to index:</p> <pre><code>&gt;&gt;&gt; df['tick'].fillna(method='ffill', inplace=True) &gt;&gt;&gt; df vols tick Date 2014-07-10 0.045 2014-07-10 2014-07-11 0.057 2014-07-10 2014-07-12 0.064 2014-07-10 2014-07-13 0.003 2014-07-13 2014-07-14 0.021 2014-07-14 2014-07-15 0.052 2014-07-14 2014-07-16 0.090 2014-07-14 &gt;&gt;&gt; df['days'] = df.index.values - df['tick'] &gt;&gt;&gt; df vols tick days Date 2014-07-10 0.045 2014-07-10 0 days 2014-07-11 0.057 2014-07-10 1 days 2014-07-12 0.064 2014-07-10 2 days 2014-07-13 0.003 2014-07-13 0 days 2014-07-14 0.021 2014-07-14 0 days 2014-07-15 0.052 2014-07-14 1 days 2014-07-16 0.090 2014-07-14 2 days </code></pre> <p>Note that you need <code>.values</code> in the last step otherwise <code>-</code> would do sort of set difference operation.</p>
python|numpy|pandas
2
1,904,025
24,814,024
Default dict keys to avoid KeyError
<p>I'm calling some JSON and parsing relevant data as CSV. I cannot figure out how to fill in the intermediate JSON dict file with default keys, as many are unpopulated. The result is a KeyError as I attempt to parse the content into a CSV.</p> <p>I'm now receiving a 'NoneType' error for (manufacturer):</p> <pre><code>import urllib2, json, csv, sys, os, codecs, re from collections import defaultdict output = 'bb.csv' csv_writer = csv.writer(open(output, 'w')) header = ['sku', 'name', 'description', 'image', 'manufacturer', 'upc', 'department', 'class', 'subclass'] csv_writer.writerow(header) i=1 while i&lt;101: print i bb_url = urllib2.Request(&quot;http://api.remix.bestbuy.com/v1/products(sku=*)?show=sku,name,description,image,manufacturer,upc,department,class,subclass&amp;format=json&amp;sort=sku.asc&amp;page=&quot; + str(i) + &quot;&amp;pageSize=100&amp;apiKey=*****************&quot;) bb_json = json.load(urllib2.urlopen(bb_url)) print bb_json for product in bb_json['products']: row = [] row.append(product['sku']) if product['name']: row.append(str((product['name']).encode('utf-8'))) else: row.append(&quot;&quot;) row.append(str(product.get('description',&quot;&quot;))) row.append(str(product['image'])+ &quot; &quot;) if product['name']: row.append(str(product.get('manufacturer',&quot;&quot;).encode('utf-8'))) else: row.append(&quot;&quot;) row.append(str(product.get('upc','').encode('utf-8'))) row.append(str((product['department']).encode('utf-8'))) row.append(str((product['class']).encode('utf-8'))) row.append(str((product['subclass']).encode('utf-8'))) csv_writer.writerow(row) i = i+1 </code></pre>
<p>You can use <code>your_dict.get(key, "default value")</code> instead of directly referencing a key.</p>
python|json|csv|dictionary|keyerror
73
1,904,026
24,937,138
UnicodeDecodeError in django top-level template code
<p>I have code in my views that returns information to be displayed in a textbox. My name has fadas (Irish accent) over the letters which is causing UnicodeDecodeErrors. The line in my logic is as follows:</p> <pre><code>return { ... 'wrap_up_form': WrapUpForm(data={u'message': settings.DEFAULT_WRAP_UP_MESSAGE.format(name=customer.given_name.encode('utf-8'))}), } </code></pre> <p>and the traceback I get is this</p> <pre><code>ERROR 2014-07-24 14:48:26,540 exception_handlers.py:65] 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128) Traceback (most recent call last): File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__ rv = self.router.dispatch(request, response) File "/home/rony/Documents/clone-attempt/personal-shopping/vendor/nacelle/core/dispatcher.py", line 24, in nacelle_dispatcher response = router.default_dispatcher(request, response) File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1065, in __call__ return self.handler(request, *args, **kwargs) File "/home/rony/Documents/clone-attempt/personal-shopping/app/utils/decorators.py", line 43, in _arguments_wrapper return view_method(request, *args, **kwargs) File "/home/rony/Documents/clone-attempt/personal-shopping/app/utils/decorators.py", line 89, in _arguments_wrapper output = render_jinja2_template(template_name, context) File "/home/rony/Documents/clone-attempt/personal-shopping/vendor/nacelle/core/template/renderers.py", line 19, in render_jinja2_template return renderer.render_template(template_name, **context) File "/home/rony/google_appengine/lib/webapp2-2.5.2/webapp2_extras/jinja2.py", line 158, in render_template return self.environment.get_template(_filename).render(**context) File "/home/rony/google_appengine/lib/jinja2-2.6/jinja2/environment.py", line 894, in render return self.environment.handle_exception(exc_info, True) File "templates/cms/appointments_form.html", line 2, in top-level template code {% import 'cms/macros.html' as cms_macros %} UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128) </code></pre> <p>Do I need to add some sort of encoding to my templates?</p>
<p>As Daniel Roseman answered, I also suspect that <code>customer.given_name</code> is byte string; trying to <code>encode</code> on it cause Python try to decode it.</p> <p>Another issue is that <code>DEFAULT_WRAP_UP_MESSAGE</code> is byte string literal.</p> <p><code>str.format(unicode)</code> has same issue.</p> <hr> <p>Solution:</p> <ul> <li>remove <code>.decode(..)</code> part.</li> <li>Make a DEFAULT_WRAP_UP_MESSAGE unicode object instead of byte string.</li> </ul>
python|django|python-2.7
0
1,904,027
38,059,242
Can't delete a row with SQLAlchemy / Flask-SQLAlchemy
<p>I can't seem to get this method to delete a row. It runs without error, but the row remains in the db (mysql). I have add and updates working using a similar approach.</p> <p>Basically, I'm creating a list of ids (ParentPage.id) and comparing those against a temp table (ParentPageTemp.id), with the intention of deleting rows in ParentPage which are not found in ParentPageTemp. Additional I have a relationship between ParentPage and Page where the row in Page should be deleted following the ParentPage delete. Admittedly my understanding of relationships in SQLAlchemy is novice at best.</p> <p>models.py</p> <pre><code>class ParentPage(Model): __tablename__ = 'parent_page' id = Column(Integer, primary_key=True) url = Column(String(255)) def __repr__(self): this_id = str(self.id) return this_id class Page(Model): __tablename__ = 'pages' id = Column(Integer, ForeignKey('parent_page.id'), primary_key=True) parent_id = Column(Integer, ForeignKey('parent_page.id')) type = Column(String(255)) default_code = Column(String(255)) name = Column(String(255)) header = Column(String(255)) title = Column(String(255)) keywords = Column(String(255)) description = Column((Text)) priority = Column(String(255)) list_price = Column((Float)) standard_price = Column((Float)) image_filename = Column((Text)) image_alt_text = Column(String(255)) pdf_filename = Column((Text)) lastupdate = Column(Date) page = relationship('ParentPage', foreign_keys=[id], backref='page') parent = relationship('ParentPage', foreign_keys=[parent_id], backref='children') def __repr__(self): return self.name </code></pre> <p>method in views.py</p> <pre><code>def delete_temp_not_in_test(): parent_test_ids = db.session.query(ParentPage.id).all() print "parent in test - %s" % (parent_test_ids) for item in parent_test_ids: q = db.session.query(ParentPageTemp).get(item) if q is None: print "ID doesnt exist - %s" % (item) db.session.query(Page).filter(Page.id==item).delete(synchronize_session='fetch') db.session.query(ParentPage).filter(ParentPage.id==item).delete(synchronize_session='fetch') db.session.commit() print "%s deleted from Temp" % (item) # return False else: print "ID is %s" % (q.id) # return True return </code></pre> <p>Thanks.</p>
<p>Probably, this is what you want:</p> <p>1 - Add a <code>relationship</code> attribute and mention the <code>backref</code> column in <code>ParentPage</code> table, basically this <code>backref</code> will be like an added attribute to the <code>Page</code> model, by which and from <code>Page</code> model, you can get the <code>ParentPage</code> of the corresponding <code>Page</code> model:</p> <pre><code>class ParentPage(Model): __tablename__ = 'parent_page' id = Column(Integer, primary_key=True) url = Column(String(255)) pages = relationship('pages', backref='parentpage') def __repr__(self): this_id = str(self.id) return this_id </code></pre> <p>2 - In <code>Page</code> model, specify only the <code>foreignKey</code> to <code>ParentPage</code>, as follows:</p> <pre><code>class Page(Model): __tablename__ = 'pages' id = Column(Integer, primary_key=True) #Leave this as a primary key parent_id = Column(Integer, ForeignKey('parent_page.id')) type = Column(String(255)) # ... </code></pre>
python|mysql|flask|sqlalchemy|flask-sqlalchemy
0
1,904,028
30,859,857
xml.etree.ElementTree.Element.remove not removing all elements
<p>Please see the following code:</p> <pre><code>import xml.etree.ElementTree as ET for x in ("&lt;a&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;", "&lt;a&gt;&lt;q /&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;", "&lt;a&gt;&lt;m /&gt;&lt;q /&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;"): root = ET.fromstring(x) for e in root: root.remove(e) print(ET.tostring(root)) </code></pre> <p>I expect it to output <code>&lt;a&gt;&lt;/a&gt;</code> in all instances but instead it gives:</p> <pre><code>b'&lt;a&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;' b'&lt;a&gt;&lt;b /&gt;&lt;/a&gt;' b'&lt;a&gt;&lt;q /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;' </code></pre> <p>I totally don't grok this. I don't see any pattern to the specific elements that were removed either.</p> <p>The documentation merely says: </p> <blockquote> <p>Removes subelement from the element. Unlike the find* methods this method compares elements based on the instance identity, not on tag value or contents.</p> </blockquote> <p>What am I doing/assuming wrong? I am getting basically the same output with both Python 2.7.5 and 3.4.0 on Kubuntu Trusty.</p> <p>Thanks!</p>
<p>This demonstrates the problem:</p> <pre><code>&gt;&gt;&gt; root = ET.fromstring("&lt;a&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;") &gt;&gt;&gt; for e in root: ... print(e) ... &lt;Element 'b' at 0x7f76c6d6cd18&gt; &lt;Element 'c' at 0x7f76c6d6cd68&gt; &gt;&gt;&gt; for e in root: ... print(e) ... root.remove(e) ... &lt;Element 'b' at 0x7f76c6d6cd18&gt; </code></pre> <p>So, modifying the object that you are iterating affects the iteration. This is not entirely unexpected, it is the same if you alter a list while iterating over it:</p> <pre><code>&gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; for i in l: ... l.remove(i) &gt;&gt;&gt; print l [2, 4] </code></pre> <p>As a workaround you can repetitively remove the first subelement like this:</p> <pre><code>import xml.etree.ElementTree as ET for x in ("&lt;a&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;", "&lt;a&gt;&lt;q /&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;", "&lt;a&gt;&lt;m /&gt;&lt;q /&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;"): root = ET.fromstring(x) for i in range(len(root)): root.remove(root[0]) ET.tostring(root) </code></pre> <p>Output</p> <pre><code>b'&lt;a /&gt;' b'&lt;a /&gt;' b'&lt;a /&gt;' </code></pre> <p>This works because the iterator is not varying while the loop is executed. Or, if you want to remove all subelements of the root element <strong><em>and</em></strong> its all of its attributes, you can use <code>root.clear()</code>:</p> <pre><code>&gt;&gt;&gt; root = ET.fromstring('&lt;a href="blah"&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;') &gt;&gt;&gt; root.clear() &gt;&gt;&gt; ET.tostring(root) b'&lt;a /&gt;' </code></pre>
python|xml|elementtree
5
1,904,029
39,969,308
Finding average of n numbers in a list
<p>Everything is working except when the user types N to end the while loop, it doesn't go to the For Statement (this happens when you run the program, works fine in the shell and in the py).</p> <pre><code>potato = [] count = 0 avg = 0 question = input('Finding averages, continue? Y or N: ') while question == 'Y' and count &lt;= 12: num = int(input('Enter a number: ')) potato.append(num) count += 1 question = input('Continue? Y or N: ') for fries in potato: avg = sum(potato)/count print(fries,fries-avg) print('average is: ' + str(avg)) </code></pre>
<pre><code>#!/usr/bin/python my_list=[] val=int sum1=int n=int(input('Enter the limit:')) for i in range(0,n): val=int(input('number:')) my_list.append(val) sum1=sum(my_list) print sum1 res=float(sum1/n) print 'The average is:',res </code></pre>
python|python-3.x|input
0
1,904,030
29,314,177
Python home_ajax() takes exactly 1 argument (0 given)
<pre><code>def all_ajax(request, *x): if request.is_ajax(): Path = request.GET.get('Path') print Path return HttpResponse('ajax called with myvar: %s' % Path) for var in x: lists = var for w in lists: print w def home_ajax(request): if request.is_ajax(): climg = request.GET.get('climg') simg = 'C:\Users\ikesavan\Desktop\searchengine' + climg path = 'C:\Users\ikesavan\Desktop\images' pathindex='C:\Users\ikesavan\Desktop\searchengine\index.cpickle' qimg= str(simg) i=1 queryImage = cv2.imread(qimg) desc = RGBHistogram([8, 8, 8]) queryFeatures = desc.describe(queryImage) index = cPickle.loads(open(pathindex).read()) searcher = Searcher(index) results = searcher.search(queryFeatures) print "query: %s" % (qimg) for j in xrange(0, 100): (score, imageName) = results[j] if score &lt; 0.6: path = qimg + "/%s" % (imageName) lists = all_ajax(imageName) else: break cv2.waitKey(0) return HttpResponse('ajax called with myvar: %s' % climg) home_ajax() </code></pre> <p>Here I want pass the imageName value to the function all_ajax from call_ajax function, and in call_ajax function its already having argument.</p>
<p>Remove the last line of your code in which you call the <code>home_ajax</code> function without any arguments:</p> <pre><code>home_ajax() </code></pre>
python|django|function
2
1,904,031
28,877,032
How to force apscheduler to add jobs to the job store?
<p>I'm adding a job to a scheduler using apscheduler using a script. Unfortunately, the job is not properly scheduled when using a script as I didn't start the scheduler. </p> <pre><code>scheduler = self.getscheduler() # initializes and returns scheduler scheduler.add_job(trigger=trigger, func = function, jobstore = 'mongo') #sample code. Note that I did not call scheduler.start() </code></pre> <p>I'm seeing a message: <code>apscheduler.scheduler - INFO - Adding job tentatively -- it will be properly scheduled when the scheduler starts</code></p> <p>The script is supposed to add jobs to the scheduler (not to run the scheduler at that particular instance) and there are some other info which are to be added on the event of a job added to the database. Is it possible to add a job and force the scheduler to add it to the jobstore without actually running the scheduler?</p> <p>I know, that it is possible to start and shutdown the scheduler after addition of each job to make the scheduler save the job information into the jobstore. Is that really a good approach?</p> <p>Edit: My original intention was to isolate initialization process of my software. I just wanted to add some jobs to a scheduler, which is not yet started. The real issue is that I've given permission for the user to start and stop scheduler. I cannot assure that there is a running instance of scheduler in the system. I've temporarily fixed the problem by starting the scheduler and shutting it down after addition of jobs. It works.</p>
<p>You would have to have some way to notify the scheduler that a job has been added, so that it could wake up and adjust the delay to its next wakeup. It's better to do this via some sort of RPC mechanism. What kind of mechanism is appropriate for your particular use case, I don't know. But RPyC and Execnet are good candidates. Use one of them or something else to remotely control the scheduler process to add said jobs, and you'll be fine.</p>
python|cron|apscheduler
0
1,904,032
52,392,130
AttributeError when building list comprehension for Wordnet.Synsets().Definition()
<p>First off, I'm a python noob and I only half-undestand how some of this stuff works. I've been trying to build word matrices for a tagging project and I hoped I could figure this out on my own, but I'm not seeing a lot of documentation around my particular error. So I apologize up front if this is something super-obvious.</p> <p>I've tried to get a set of functions to work in a few different variations, but I keep getting "AttributeError: 'list' has no attribute definition."</p> <pre><code>import pandas as pd from pandas import DataFrame, Series import nltk.data from nltk.corpus import stopwords from nltk.corpus import wordnet as wn from nltk.tokenize import TreebankWordTokenizer # Gets synsets for a given term. def get_synset(word): for word in wn.synsets(word): return word.name() #Gets definitions for a synset. def get_def(syn): return wn.synsets(syn).defnition() # Creates a dataframe called sector_matrix based on another dataframe's column. Should be followed with an export. def sector_tagger(frame): sentences = frame.tolist() tok_list = [tok.tokenize(w) for w in frame] split_words = [w.lower() for sub in tok_list for w in sub] clean_words = [w for w in split_words if w not in english_stops] synset = [get_synset(w) for w in clean_words] sector_matrix = DataFrame({'Categories': clean_words, 'Synsets': synset}) sec_syn = sector_matrix['Synsets'].tolist() sector_matrix['Definition'] = [get_def(w) for w in sector_matrix['Synsets']] return sector_matrix </code></pre> <p>The functions get called on a dataframe that I read in from excel:</p> <pre><code>test = pd.read_excel('data.xlsx') </code></pre> <p>And the sector_tagger function is called as such:</p> <pre><code>agri_matrix = sector_tagger(agri['Category']) </code></pre> <p>A previous version called wn.synsets(w).definition() in a list comprehension that populated the DataFrame. Another tried to call the definition after the fact in a Jupyter Notebook. I almost always get the Attribute Error. That said, when I call the datatype on sector_matrix['Synsets'] I get an "object" type, and when I print that column I don't see [] around the items.</p> <p>I've tried:</p> <ul> <li>Wrapping "w" in str() </li> <li>Calling the list comprehension in and out of the function (ie - deleting the line and calling it in my notebook)</li> <li>Passing the 'Synsets' column to a new list and building a list comprehension around that</li> </ul> <p>Curiously enough, I was playing around with this yesterday and was able to make something work in my notebook directly, but (a) it's messy (b) there's no scalability, and (c) it doesn't work on other categories that I apply it to.</p> <pre><code>agrimask = (df['Agri-Food']==1) &amp; (df['Total']==1) df_agri = df.loc[agrimask,['Category']] agri_words = [tok.tokenize(a) for a in df_agri['Category']] agri_cip_words = [a.lower() for sub in agri_words for a in sub] agri_clean = [w for w in agri_cip_words if w not in english_stops] df_agri_clean = DataFrame({'Category': agri_clean}) df_agri_clean = df_agri_clean[df_agri_clean != ','].replace('horticulture/horticultural','horticulture').dropna().drop_duplicates() df_agri_clean['Synsets'] = [x[0].name() for x in df_agri_clean['Category'].apply(syn)] df_agri_clean['Definition'] = [wn.synset(x).definition() for x in df_agri_clean['Synsets']] df_agri_clean['Lemma'] = [wn.synset(x).lemmas()[0].name() for x in df_agri_clean['Synsets']] df_agri_clean </code></pre> <p>Edit1: Here's a link to a <a href="https://docs.google.com/spreadsheets/d/1Ec_IAGjLtIqBoXAh72itDax7D-4pp3xmUAGcpu80aQI/edit?usp=sharing" rel="nofollow noreferrer">sample of the data</a>.</p> <p>Edit2: Also, the static variables I'm using are here (all based around the standard NLTK library):</p> <pre><code>tok = TreebankWordTokenizer() english_stops = set(stopwords.words('english')) french_stops = set(stopwords.words('french')) </code></pre> <p>Edit3: You can see a working version of this code here: <a href="https://github.com/shawnanctil/ed_scripts/tree/master/CIP" rel="nofollow noreferrer">Working Code</a></p>
<p><a href="https://github.com/trenton3983/stack_overflow/blob/master/complete_solutions/2018-09-18_CIP.ipynb" rel="nofollow noreferrer">2018-09-18_CIP.ipynb</a></p> <pre><code>import pandas as pd import nltk from nltk.corpus import stopwords from nltk.corpus import wordnet as wn from nltk.tokenize import TreebankWordTokenizer as tok english_stops = set(stopwords.words('english')) # Gets synsets for a given term. def get_synset(word): for word in wn.synsets(word): return word.name() #Gets definitions for a synset. def get_def(syn): return wn.synset(syn).definition() # your definition is misspelled # Creates a dataframe called sector_matrix based on another dataframe's column. Should be followed with an export. def sector_tagger(frame): tok_list = tok().tokenize(frame) split_words = [w.lower() for w in tok_list] clean_words = [w for w in split_words if w not in english_stops] synset = [get_synset(w) for w in clean_words] sector_matrix = pd.DataFrame({'Categories': clean_words, 'Synsets': synset}) sec_syn = list(sector_matrix['Synsets']) sector_matrix['Definition'] = [get_def(w) if w != None else '' for w in sec_syn] return sector_matrix agri_matrix = df['Category'].apply(sector_tagger) </code></pre> <p><strong>if this answers your question, please check it as the answer</strong></p> <p>The output of <code>get_def</code> is a list of phrases</p> <p><strong>Alternate Approach</strong></p> <pre><code>def sector_tagger(frame): mapping = [('/', ' '), ('(', ''), (')', ''), (',', '')] for k, v in mapping: frame = frame.replace(k, v) tok_list = tok().tokenize(frame) # note () after tok split_words = [w.lower() for w in tok_list] clean_words = [w for w in split_words if w not in english_stops] synset = [get_synset(w) for w in clean_words] def_matrix = [get_def(w) if w != None else '' for w in synset] return clean_words, synset, def_matrix poo = df['Category'].apply(sector_tagger) poo[0] = (['agricultural', 'domestic', 'animal', 'services'], ['agricultural.a.01', 'domestic.n.01', 'animal.n.01', 'services.n.01'], ['relating to or used in or promoting agriculture or farming', 'a servant who is paid to perform menial tasks around the household', 'a living organism characterized by voluntary movement', 'performance of duties or provision of space and equipment helpful to others']) list_clean_words = [] list_synset = [] list_def_matrix = [] for x in poo: list_clean_words.append(x[0]) list_synset.append(x[1]) list_def_matrix.append(x[2]) agri_matrix = pd.DataFrame() agri_matrix['Categories'] = list_clean_words agri_matrix['Synsets'] = list_synset agri_matrix['Definition'] = list_def_matrix agri_matrix Categories Synsets Definition 0 [agricultural, domestic, animal, services] [agricultural.a.01, domestic.n.01, animal.n.01... [relating to or used in or promoting agricultu... 1 [agricultural, food, products, processing] [agricultural.a.01, food.n.01, merchandise.n.0... [relating to or used in or promoting agricultu... 2 [agricultural, business, management] [agricultural.a.01, business.n.01, management.... [relating to or used in or promoting agricultu... 3 [agricultural, mechanization] [agricultural.a.01, mechanization.n.01] [relating to or used in or promoting agricultu... 4 [agricultural, production, operations] [agricultural.a.01, production.n.01, operation... [relating to or used in or promoting agricultu... </code></pre> <p><strong>Split each list of lists into a long list (they're ordered)</strong></p> <pre><code>def create_long_list_from_list_of_lists(list_of_lists): long_list = [] for one_list in list_of_lists: for word in one_list: long_list.append(word) return long_list long_list_clean_words = create_long_list_from_list_of_lists(list_clean_words) long_list_synset = create_long_list_from_list_of_lists(list_synset) long_list_def_matrix = create_long_list_from_list_of_lists(list_def_matrix) </code></pre> <p><strong>Turn it into a DataFrame of Uniques Categories</strong></p> <pre><code>agri_df = pd.DataFrame.from_dict(dict([('Categories', long_list_clean_words), ('Synsets', long_list_synset), ('Definitions', long_list_def_matrix)])).drop_duplicates().reset_index(drop=True) agri_df.head(4) Categories Synsets Definitions 0 ceramic ceramic.n.01 an artifact made of hard brittle material prod... 1 horticultural horticultural.a.01 of or relating to the cultivation of plants 2 construction construction.n.01 the act of constructing something 3 building building.n.01 a structure that has a roof and walls and stan... </code></pre> <p><strong>Final Note</strong></p> <pre><code>import from nltk.tokenize import TreebankWordTokenizer as tok </code></pre> <p>or:</p> <pre><code>import from nltk.tokenize import word_tokenize </code></pre> <p>to use:</p> <pre><code>tok().tokenize(string_text_phrase) # text is a string phrase, not a list of words </code></pre> <p>or:</p> <pre><code>word_tokenize(string_text_phrase) </code></pre> <p><strong>Both methods appear to produce the same output, which is a list of words.</strong></p> <pre><code>input = "Agricultural and domestic animal services" output_of_both_methods = ['Agricultural', 'and', 'domestic', 'animal', 'services'] </code></pre>
python|pandas|list-comprehension|attributeerror|wordnet
1
1,904,033
51,788,718
Python Format traceback
<p>The goal is to print the traceback from a failed python script. I have referenced a ton of stack articles, but I can not find one tailored to my needs. The goal is to email the traceback when there is a failure. I can email everything fine, it is just formating said traceback.</p> <p>To get my traceback:</p> <pre><code>trace = traceback.format_exc() send_email("Python Failure", trace, "bj@mydomain.com") </code></pre> <p>Email is being run through an html emailing with smtpObj and MIMEMultipart:</p> <pre><code>def send_email(subject, message, receivers): sender = "mydomain.com" msg = MIMEMultipart("alternative") msg["Subject"] = subject msg["From"] = sender msg["To"] = ", ".join(receivers) html = """ &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;p&gt;&lt;b&gt;""" + subject + """&lt;/b&gt;&lt;/p&gt; &lt;p&gt;""" + message + """&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; """ part1 = MIMEText(message, "plain") part2 = MIMEText(html, "html") msg.attach(part1) msg.attach(part2) smtpObj = smtplib.SMTP("thats.not.cheddar") smtpObj.sendmail(sender, receivers, msg.as_string()) smtpObj.quit() </code></pre> <p>When I receive the email, the traceback is there but it is all on one line. I was just wondering if anyone could help format a little bit better.</p>
<p>Promoting @snakecharmerb's comment to an answer because it worked for me. Wrap the traceback in <code>&lt;pre&gt;</code> tags:</p> <pre><code>f&quot;&lt;pre&gt;{traceback.format_exc()}&lt;/pre&gt;&quot; </code></pre>
python
0
1,904,034
59,706,071
how to scrape value using id in beautiful soup
<p>I want to store the text of <strong>value</strong> in a variable <strong>status</strong><br> which is either <strong>Discharging</strong> or <strong>Charging</strong></p> <pre><code>&lt;input id="batterystatus" value="Discharging" type="hidden"&gt; </code></pre> <p>I have tried to store text in status</p> <pre><code>site="http://jiofi.local.html/" opener=uo(site) page=opener.read() opener.close() parser = bs(page, "html.parser") status=parser.find(id='batterystatus') </code></pre>
<p>Try this.</p> <pre><code>Print(status['value']) </code></pre>
python|html|web-scraping|beautifulsoup
1
1,904,035
67,249,246
Does IPython support ctypes?
<p>I am trying to execute C code in IPython (using ctypes), but IPython crashes every time a C function is called.</p> <h3>Environment</h3> <ul> <li>Windows 10 (64bit)</li> <li>Python 3.8.5 64bit</li> <li>GCC 9.1.0 (tdm-gcc)</li> </ul> <h3>Minimum working example</h3> <p>File <code>test.c</code>:</p> <pre class="lang-c prettyprint-override"><code>int func(){ return 10; } </code></pre> <p>Compile in commandline:</p> <pre><code>gcc -shared -o test.dll -fPIC test.c </code></pre> <p>Start IPython in the same directory, then run:</p> <pre><code>In [1]: import ctypes ...: lib = ctypes.CDLL(&quot;test.dll&quot;) ...: lib.func() Out[1]: 10 </code></pre> <p>The output <code>Out[1]</code> is correct, but IPython crashes immediately after <code>Out[1]: 10</code> is printed. (sometimes it crashes before <code>Out[1]: 10</code> is printed)</p> <h3>Question</h3> <p>Does IPython support ctypes?</p> <p>If so, why the aforementioned problem occured?</p> <p>If not so, is there a workaround to use ctypes in IPython/Jupyter Notebook?</p> <h3>Updates</h3> <ul> <li>Tried the same code on WSL (on the same machine); IPython did not crash.</li> <li>Tried Tim Roberts's solution (changing <code>CDLL</code> to <code>WinDLL</code>; see comments); did not work.</li> </ul> <h3>Update: problem solved</h3> <p>Switched from TDM-GCC to Mingw-w64, and this somehow solves the problem.</p>
<p>As mentioned in above comment it is likely not due to IPython there is no reasons for it to not work.</p> <p>Though to simplify using c-defined function in IPython, you can also try to look at how the <a href="https://pypi.org/project/cffi_magic/" rel="nofollow noreferrer">cffi_magic</a> prototype package that use libffi works. It makes it slightly easier to (re)define function.</p> <pre><code> $ ipython Python 3.8.5 | packaged by conda-forge | (default, Sep 16 2020, 17:43:11) Type 'copyright', 'credits' or 'license' for more information IPython 7.23.0.dev -- An enhanced Interactive Python. Type '?' for help. In [1]: import cffi_magic In [2]: %%cffi int func(int, int); ...: int func(int a, int b){ ...: return a+b; ...: } clang-10: warning: -Wl,-export_dynamic: 'linker' input unused [-Wunused-command-line-argument] ld: warning: -pie being ignored. It is only used when linking a main executable In [3]: func(1, 2) Out[3]: 3 </code></pre>
python|jupyter-notebook|ipython|ctypes
1
1,904,036
63,321,972
I get a 'none' at the bottom of the result when I run my code
<p>Hi I am a beginner in python and I am currently using Automate the boring stuff with python. This is my second book learning python. I practiced doing this code (transferring items in list to a dictionary) my code worked the way I wanted it to work but there is a 'none' at the bottom. Can someone enlighten my tiny brain on how to fix this please?</p> <pre><code>def addToInventory(inventory, addedItems): for i in addedItems: if i == 'gold coin': inventory['gold coin'] += 1 else: inventory.setdefault(i, 0) inventory[i] += 1 print('Inventory:') total_item = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) total_item += v print('\nTotal number of items: ' + str(total_item)) inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] print(addToInventory(inv, dragonLoot)) </code></pre> <p>This is the result: <a href="https://i.stack.imgur.com/fP1Ol.png" rel="nofollow noreferrer">https://i.stack.imgur.com/fP1Ol.png</a></p>
<p>The logic of your function is sound. It returns <code>None</code> because unlike some other languages, Python functions return <code>None</code> by default, unless you tell it to explicitly return something. For example:</p> <pre><code>def func_A(): x=5 def func_B(): x=5 return x print(func_A()) # prints &quot;None&quot; print(func_B()) # prints 5 </code></pre> <p>Therefore, try this instead:</p> <pre><code>def addToInventory(inventory, addedItems): for i in addedItems: if i == 'gold coin': inventory['gold coin'] += 1 else: inventory.setdefault(i, 0) inventory[i] += 1 print('Inventory:') total_item = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) total_item += v print('\nTotal number of items: ' + str(total_item)) return total_item # this is key </code></pre>
python-3.x|pycharm
1
1,904,037
22,187,279
Why do circular imports seemingly work further up in the call stack but then raise an ImportError further down?
<p>I'm getting this error</p> <pre><code>Traceback (most recent call last): File &quot;/Users/alex/dev/runswift/utils/sim2014/simulator.py&quot;, line 3, in &lt;module&gt; from world import World File &quot;/Users/alex/dev/runswift/utils/sim2014/world.py&quot;, line 2, in &lt;module&gt; from entities.field import Field File &quot;/Users/alex/dev/runswift/utils/sim2014/entities/field.py&quot;, line 2, in &lt;module&gt; from entities.goal import Goal File &quot;/Users/alex/dev/runswift/utils/sim2014/entities/goal.py&quot;, line 2, in &lt;module&gt; from entities.post import Post File &quot;/Users/alex/dev/runswift/utils/sim2014/entities/post.py&quot;, line 4, in &lt;module&gt; from physics import PostBody File &quot;/Users/alex/dev/runswift/utils/sim2014/physics.py&quot;, line 21, in &lt;module&gt; from entities.post import Post ImportError: cannot import name Post </code></pre> <p>and you can see that I use the same import statement further up and it works. Is there some unwritten rule about circular importing? How do I use the same class further down the call stack?</p> <hr /> <p><sub>See also <a href="https://stackoverflow.com/questions/744373">What happens when using mutual or circular (cyclic) imports in Python?</a> for a general overview of what is allowed and what causes a problem WRT circular imports. See <a href="https://stackoverflow.com/questions/9252543/">What can I do about &quot;ImportError: Cannot import name X&quot; or &quot;AttributeError: ... (most likely due to a circular import)&quot;?</a> for techniques for resolving and avoiding circular dependencies.</sub></p>
<p>I think the <a href="https://stackoverflow.com/a/22187343/4298200">answer by jpmc26</a>, while by no means <em>wrong</em>, comes down too heavily on circular imports. They can work just fine, if you set them up correctly.</p> <p>The easiest way to do so is to use <code>import my_module</code> syntax, rather than <code>from my_module import some_object</code>. The former will almost always work, even if <code>my_module</code> included imports us back. The latter only works if <code>my_object</code> is already defined in <code>my_module</code>, which in a circular import may not be the case.</p> <p>To be specific to your case: Try changing <code>entities/post.py</code> to do <code>import physics</code> and then refer to <code>physics.PostBody</code> rather than just <code>PostBody</code> directly. Similarly, change <code>physics.py</code> to do <code>import entities.post</code> and then use <code>entities.post.Post</code> rather than just <code>Post</code>.</p>
python|import|circular-dependency
238
1,904,038
43,654,497
Read data from text table
<p>I have a table like this:</p> <pre><code>protocol packets bytes bytes/pkt ------------------------------------------------------------------------ total 78913220 (100.00%) 47623614577 (100.00%) 603.49 ip 76930821 ( 97.49%) 45706321977 ( 95.97%) 594.12 tcp 45432316 ( 57.57%) 38990240707 ( 81.87%) 858.20 </code></pre> <p>Actually, you can find some example in <a href="http://mawi.wide.ad.jp/mawi/ditl/ditl2017/201704120145.html" rel="nofollow noreferrer">WIDE MAWI WorkingGroup</a>. I got data with a simple Python code and then I wanna to store each item in some struct like <code>dict</code>.</p> <p>For example:</p> <blockquote> <p>It's not a practical code! It's a semi code just for example of that I need.</p> </blockquote> <pre><code>import httplib2 from BeautifulSoup import BeautifulSoup, SoupStrainer import pandas as pd http = httplib2.Http() status, response = http.request('http://mawi.wide.ad.jp/mawi/ditl/ditl2017/201704131545.html') for item in BeautifulSoup(response, parseOnlyThese=SoupStrainer('pre')): res = item.text pd.read_somefunction_to_read_string(res) if pd['protocol']['ip'] &gt; .09 * pd['protocol']['total'] do_something </code></pre> <p>Expected Output:</p> <pre><code> [ {'protocol' : 'total', 'packet' : 78913220, 'bytes' : 47623614577}, {'protocol' : 'ip', 'packet' : 76930821, 'bytes' : 45706321977} ] </code></pre>
<p>Firstly response can be splitted into rows by the newline character. Then for every row: <code>protocol</code>, <code>packet</code> and <code>bytes</code> fields can be extracted using regex. Then append them a list of dict (<code>lst_dict</code>). Lastly convert the <code>lst_dict</code> to a pandas DataFrame.</p> <pre><code>import httplib2 from BeautifulSoup import BeautifulSoup, SoupStrainer import pandas as pd import re lst_dict = [] http = httplib2.Http() status, response = http.request('http://mawi.wide.ad.jp/mawi/ditl/ditl2017/201704131545.html') res = BeautifulSoup(response, parseOnlyThese=SoupStrainer('pre')) items = res.text.split("\n") for item in items[2:]: item = item.strip() protocol = re.search('(\w+)\s.*', item).group(1) packet = re.search('\w+\s*(\w+)\s.*', item).group(1) byts = re.search('\w+\s*\w+\s\(.*\)\s+(\w+)\s.*', item).group(1) dict = {'protocol': protocol, 'packet': packet, 'bytes': byts} lst_dict.append(dict) df = pd.DataFrame(lst_dict) print df </code></pre>
python|python-2.7|pandas|beautifulsoup
1
1,904,039
54,606,373
Sending 1gb data as a response to POST request
<p>I am running a django web app where I have one form which accepts text area input. I am sending that text to my view by POST request. After processing that input at server my generated output is of 1GB. Now the question is how can I send that data back to browser. I want that whole data at client side. How can I do it.</p>
<p>You generally don't want the webserver to do much heavy work. The ideal way would be to generate the output to a file, upload this file to a django storage and return the file path to the client. You might want to consider doing calculations and generation of the output on a different server as well.</p> <p>Take a look at these links</p> <p>[<a href="https://docs.djangoproject.com/en/2.1/ref/models/fields/#filefield" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.1/ref/models/fields/#filefield</a></p> <p><a href="https://django-storages.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://django-storages.readthedocs.io/en/latest/</a></p> <p>Also here is a related question: </p> <p><a href="https://stackoverflow.com/questions/12408414/django-let-user-download-a-large-file">Django: let user download a large file</a></p>
python|django|django-forms
1
1,904,040
54,410,109
python 3 imaplib different between windows/anaconda command prompts
<p>I have some python code I use for emails that recently stopped working. Trying to debug it, I discovered that imaplib.IMAP4_SSL exists in python started from an anaconda prompt, but not a regular windows command prompt. How is this possible?</p> <p>Here's the simplest way I know to show:</p> <ol> <li>open anaconda prompt and windows command prompt</li> <li>in both prompts, type 'python' to start python</li> <li>both show the same python version (3.7.1 for me)</li> <li>type the following:</li> </ol> <p><b></b></p> <pre><code>import imaplib imaplib.IMAP4_SSL </code></pre> <p>The anaconda prompt returns a class and works fine, while the windows cmd prompt returns an error:</p> <pre><code>AttributeError: module 'imaplib' has no attribute 'IMAP4_SSL' </code></pre> <p>I thought maybe I had multiple versions of python installed, so I uninstalled everything related to python that I could find, then reinstalled anaconda. It didn't help. </p>
<p>I found a workaround in <a href="https://stackoverflow.com/questions/46305569/how-to-make-batch-files-run-in-anaconda-prompt">this post</a> by using a batch file. Now I can get my code to work by double clicking in windows. This is the batch file that works for me (in directory with code):</p> <pre><code>set root=C:\Users\usernamen\AppData\Local\Continuum\anaconda3 call %root%\Scripts\activate.bat %root% call PythonFileToRun.py pause </code></pre> <p>I still don't understand what the activate.bat file does or why ssl doesn't work in the windows cmd prompt though.</p>
python|windows|cmd|anaconda|imaplib
0
1,904,041
71,300,902
How to prevent different user types to view each other dashboard in django
<p>I have a website with 3 user types, admin, instructor and students, I used login mixing to redirect each of them to their respective dashboard but if the student modify their url to /instructor or /admin ; it will give them access to the page; I want to restrict student to only student page and admin to only admin page.</p> <p>I tried writing the function</p> <p>If user.student.is_authenticated: class Student_dashboard(): ......</p> <p>However it's not restricting them</p>
<p>You can use the <a href="https://docs.djangoproject.com/en/4.0/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin" rel="nofollow noreferrer">UserPassesTestMixin</a> mixin to add a test function to validate that users have permission to access the view</p> <pre><code>from django.contrib.auth.mixins import UserPassesTestMixin from django.views import View class Student_dashboard(UserPassesTestMixin, View): def test_func(self): return self.request.user.is_student </code></pre>
python|django|django-views
0
1,904,042
71,224,813
how to use range slider in tkinter
<p>I am trying to use a range slider widget for my problem. I looked into the net but I couldn't find an example of this widget <code>RangeSliderH</code>. I found this library for that. <a href="https://pypi.org/project/RangeSlider/" rel="nofollow noreferrer">https://pypi.org/project/RangeSlider/</a></p> <p>Does anyone know how to update this code to make that show on the screen?currently I am getting this error: <code>Exception: padX too small, value won't be visible completely, expected padX to be atleast 16.96px</code></p> <pre><code>from RangeSlider.RangeSlider import RangeSliderH from tkinter import * import tkinter as tk root = tk.Tk() root.geometry(&quot;750x750&quot;) hVar1 = DoubleVar() # left handle variable hVar2 = DoubleVar() # right handle variable rs1 = RangeSliderH(root, [hVar1, hVar2], Width=400, Height=60, min_val=0, max_val=400, show_value= True) rs1.pack() root.mainloop() </code></pre>
<p>Just follow the suggestion in the exception message to set <code>padX</code> to value &gt;= 16.96.</p> <p>However after fixing it, another exception on <code>Height</code> is raised:</p> <pre><code>Exception: Dimensions incompatible, consider decreasing bar_radius or consider increasing widget height, as per given configuration height should be atleast .63.56px. </code></pre> <p>Adjust the value of <code>Height</code> as suggested in the exception message as well. So the final fix is:</p> <pre class="lang-py prettyprint-override"><code>rs1 = RangeSliderH(root, [hVar1, hVar2], Width=400, Height=65, padX=17, min_val=0, max_val=400, show_value= True) </code></pre>
python|tkinter|rangeslider
0
1,904,043
71,341,796
regular expression to split a string with comma outside parentheses with more than one level python
<p>I have a string like this in python</p> <pre><code>filter=&quot;eq(Firstname,test),eq(Lastname,ltest),OR(eq(ContactID,12345),eq(ContactID,123456))&quot; rx_comma = re.compile(r&quot;(?:[^,(]|\([^)]*\))+&quot;) result = rx_comma.findall(filter) </code></pre> <p>Actual result is:</p> <pre><code>['eq(Firstname,test)', 'eq(Lastname,ltest)', 'OR(eq(ContactID,12345)', 'eq(ContactID,123456))'] </code></pre> <p>Expected result is:</p> <pre><code>['eq(Firstname,test)', 'eq(Lastname,ltest)', 'OR(eq(ContactID,12345),eq(ContactID,123456))'] </code></pre> <p>Any help is appreciated.</p>
<p>The OP's issue was already solved by using the <code>regex</code> module though, I'd like to introduce <a href="https://github.com/pyparsing/pyparsing" rel="nofollow noreferrer">pyparsing</a> as an alternative solution here. It can be installed by the following command:</p> <pre class="lang-sh prettyprint-override"><code>pip install pyparsing </code></pre> <h2>Code:</h2> <pre class="lang-py prettyprint-override"><code>import pyparsing as pp s = &quot;eq(Firstname,test),eq(Lastname,ltest),OR(eq(ContactID,12345),eq(ContactID,123456))&quot; expr = pp.delimited_list(pp.original_text_for(pp.Regex(r'.*?(?=\()') + pp.nested_expr('(', ')'))) output = expr.parse_string(s).as_list() assert output == ['eq(Firstname,test)', 'eq(Lastname,ltest)', 'OR(eq(ContactID,12345),eq(ContactID,123456))'] </code></pre> <h2>Explanation:</h2> <p>The key point is the <code>expr</code> in the above code. I added some explanatory comments to its definition as follows:</p> <pre class="lang-py prettyprint-override"><code>pp.delimited_list( # Separate a given string at the default comma delimiter pp.original_text_for( # Get original text instead of completely parsed elements. pp.Regex(r'.*?(?=\()') # Search everything before the first opening parenthesis '(' + pp.nested_expr('(', ')') # Parse nested parentheses ) ) </code></pre>
python|regex|string
2
1,904,044
9,160,294
Malloc failing when called via ctypes from a c thread
<p>I'm using Python's CTypes to bind to a shared library; I have a callback registered with this library, which is called in the context of a thread that the library itself creates. I've found that if I call <code>libc.malloc()</code> (<code>libc = cdll.LoadLibrary('libc.so.6')</code>) from within my callback, that it returns bogus values. Not <code>NULL</code>, but an address which will cause a segfault if I dereference it.</p> <p>Can anyone provide me with any insight to what may be happening, or alternatively, tell me that they call <code>malloc()</code> in the same way, and that it works for them.</p>
<p>Are you properly anottating the malloc call so that ctypes know it should return pointers not integers? (Doubly so if you are working on a 64bit box?)</p>
python|multithreading|ctypes
1
1,904,045
39,282,355
Pandas Group to Divide by Max
<p>I'm trying to normalize a user count by dividing by the max users in each group. I'm able to get the results to calculate (commented out the print that works), but I'm having trouble getting the results to save back to the original table. The code below doesn't throw an error, but it also doesn't add any data to weeklyPerson:</p> <pre><code>weeklyPersonGroups=weeklyPerson.groupby('Person') PersonMax=weeklyPersonGroups['users'].max() for name, group in weeklyPersonGroups: #print(weeklyPerson[weeklyPerson['Person']==name]['users']/PersonMax[name]) weeklyPerson[weeklyPerson['Person']==name]['usersNorm']=weeklyPerson[weeklyPerson['Person']==name]['users']/PersonMax[name] </code></pre>
<p>Use <code>groupby</code> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a></p> <pre><code>weeklyPerson.groupby('Person').users.transform(lambda x: x / x.max()) </code></pre> <p>Per <a href="https://stackoverflow.com/users/644898">@Jeff</a>'s <a href="https://stackoverflow.com/questions/39282355/pandas-group-to-divide-by-max#comment65899739_39282362">suggestion</a></p> <pre><code>weeklyPerson.users / weeklyPerson.groupby('Person').users.transform(np.max) </code></pre> <p>This avoids using <code>lambda</code> when it isn't necessary.</p>
python|pandas
7
1,904,046
39,262,493
PyCharm - always show inspections
<p>PyCharm displays little bars on the scroll bar for things like code warnings. This feature is called "inspection".</p> <p>If you move the mouse cursor over a bar, it shows a preview of the code annotated with the inspection.</p> <p>I find this really fiddly, and I'd actually like full inspection notices to be displayed <em>all the time</em> in the normal editor, just like it appears in the small preview.</p> <p>Is there any way I can achieve this?</p> <p><a href="https://i.stack.imgur.com/NMRlg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NMRlg.png" alt="screenshot showing an example PyCharm inspection"></a></p>
<p>Using the default keymap, you can use <code>F2</code> to jump to the next highlighted error and then <code>Ctrl+F1</code> to show the tooltip.</p>
python|ide|pycharm|lint
2
1,904,047
52,677,769
Extract text from div class with scrapy
<p>I am using python along with scrapy. I want to extract the text from the div tag which is inside a div class. For example:</p> <pre><code> &lt;div class="ld-header"&gt; &lt;h1&gt;2013 Gulfstream G650ER for Sale&lt;/h1&gt; &lt;div id="header-price"&gt;Price - $46,500,000&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I've extracted text from h1 tag</p> <pre><code>result.xpath('//div[@class="ld-header"]/h1/text()').extract() </code></pre> <p>but I can't extract Price. I've tried </p> <pre><code>'price': result.xpath('//div[@class="ld-header"]/div[@id="header-price"]/text()').extract() </code></pre>
<p>As you have an id, you do not need to use the complete path to the element. Ids are unique per Webpage:</p> <p>This Xpath:</p> <pre><code>//div[@id="header-price"]/text() </code></pre> <p>used on the give XML will return:</p> <pre><code>'Price - $46,500,000' </code></pre> <p>For debugging Xpath and CSS Selectors, I always find it helpful to use an online checker (just use Google to find some suggestions).</p>
python|xpath|scrapy
1
1,904,048
52,728,273
python selenium white page
<p>I want get html from <a href="https://www.elal.com/en/PassengersInfo/Useful-Info/Flight-Schedule/Pages/Flight-Updates.aspx" rel="nofollow noreferrer">here</a>. This link work OK in my browser. But if I disable cookies in settings, this page reload endless.</p> <p>My basic code return blank page</p> <pre><code>options = Options() options.add_argument("--start-maximized") cpll = "C:\Users\aaa\chromedriver.exe" driver = webdriver.Chrome(cpll,chrome_options=options) driver.get("https://www.elal.com/en/PassengersInfo/Useful-Info/Flight-Schedule/Pages/Flight-Updates.aspx") </code></pre> <p><a href="https://i.stack.imgur.com/fGnct.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fGnct.png" alt="enter image description here"></a></p> <p>I tried <a href="https://stackoverflow.com/questions/15058462/how-to-save-and-load-cookies-using-python-selenium-webdriver">add cookies</a>, <a href="https://stackoverflow.com/questions/24507078/how-to-deal-with-certificates-using-selenium">ignore SSL</a>, change driver version, but I get this page...</p> <p>What could be the problem?</p>
<p>with</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.elal.com/en/PassengersInfo/Useful-Info/Flight-Schedule/Pages/Flight-Updates.aspx") </code></pre> <p>... i get a normal page <a href="https://i.stack.imgur.com/Vjvx8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vjvx8.png" alt="enter image description here"></a></p>
python|selenium|cookies|web-crawler
0
1,904,049
47,782,076
How to add hours onto Day of Year
<p>I am working with oceanographic data in Python. I am currently trying to create a contour plot of time on the x axis, pressure on the y axis, and temperature as the contours. Right now I am trying to format the time array with values that I got from the data itself. The code I have only produces the day of the year without the corresponding hours added onto it. I need a way to add on 6 hours, 12 hours, and 18 hours to each day because the data came from profiles of the water column that ran 4 times each day, separated by 6 hours. There were 1260 profiles and i corresponds to the file for each profile.</p> <pre><code>import numpy from matplotlib import pyplot as plt import math from datetime import tzinfo, timedelta, datetime, time import time i = 1 temp = numpy.zeros((1260, 1000)) pressure = numpy.zeros((1260, 1000)) time2 = numpy.zeros(1260) for i in range(1, 1260): filename = '/Users/ryanschubert/InternProject/itp47final/itp47grd' + str(i).zfill(4) + '.dat' if os.path.isfile(filename): data = open(filename, "r") else: continue depthcounter=-1 text = data.read() data.close() text = text.replace(' ', ',') #this line and the next 5 lines are text = text.replace(' ', ',') #fixing formatting errors in the code text = text.replace(' ', '') text = text.replace('NaN', '-98') text = text.replace(',,', ',') text = text.split('\n') for line in text: depthcounter=depthcounter+1 if depthcounter == 1: if i ==1: words4 = line.split(',') year = int(words4[0]) doy = float(words4[1]) - 1 hour = int((doy - math.floor(doy))*24) t = datetime(year=year, month=1, day=1, hour=hour,tzinfo=utc) + timedelta(days=int(doy)) time1 = t.timetuple().tm_yday timetemp = numpy.array([t + timedelta(days=j/4.) for j in xrange(1260)]) else: time2[i] = timetemp[i].timetuple().tm_yday print(time2[i])` </code></pre> <p>The code currently returns values like this;</p> <pre><code>102 102.0 102.0 103.0 103.0 103.0 103.0 104.0 104.0 104.0 104.0 105.0 105.0 105.0 105.0 106.0 106.0 106.0 106.0 107.0 107.0 107.0 107.0 </code></pre> <p>and so on...</p> <p>I need help adding 6 hours to each previous day of year so that the array looks like-</p> <pre><code>102 102.25 102.5 102.75 103.0 103.25 103.5 103.75 104.0 </code></pre> <p>and so on.</p>
<p>Instead of adding a <code>timedelta</code> of <code>1/4.</code> day, you could add a <code>timedelta(hours=6)</code>.</p> <p>Otherwise, since you know you want your time to increase in <code>0.25</code> increments, you could simply generate an array of floats from the get go.</p> <p>Note that, on my version of python3, <code>timetuple().tm_yday</code> returns an integer, not a float.</p>
python|python-3.x|datetime|contourf
0
1,904,050
37,276,954
Issue with get_yticklabels in matplotlib
<p>I am using matplotlib to plot a bar graph, and I am experiencing an issue when I try to access the labels (both on the X and Y axis) to change them. In particular, this code:</p> <pre><code>fig = plot.figure(figsize=(16,12), dpi=(300)) ax1 = fig.add_subplot(111) ax1.set_ylabel("simulated quantity") ax1.set_xlabel("simulated peptides - from most to least abundant") # create the bars, and set a different color for the bars referring to experimental peptides barlist = ax1.bar( numpy.arange(len(quantities)), [numpy.log10(x) for x in quantities] ) for index, peptide in enumerate(peptides) : if peptide in experimentalPeptidesP or peptide in experimentalPeptidesUP : barlist[index].set_color('b') labelsY = ax1.get_yticklabels(which='both') print "These are the label objects on the Y axis:", labelsY print "These are the labels on the Y axis:", [item.get_text() for item in ax1.get_xticklabels( which='both')] for label in labelsY : label.set_text("AAAAA") ax1.set_yticklabels(labelsY) </code></pre> <p>Gives the following output:</p> <pre><code>These are the label objects on the Y axis: &lt;a list of 8 Text yticklabel objects&gt; These are the labels on the Y axis: [u'', u'', u'', u'', u'', u''] </code></pre> <p>And the resulting figure has "AAAAA" as the text of every label on the Y axis, as requested. My issue is, while I am able to correctly SET the labels, apparently I cannot GET their text...and the text should exist, because if I don't replace the labels with "AAAAA" I get the following figure: <a href="https://i.stack.imgur.com/olUt9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/olUt9.jpg" alt="enter image description here"></a></p> <p>As you can see, there are labels on the Y axis, and I'd need to "get" their text. Where is the error?</p> <p>Thank you in advance for your help.</p> <p><strong>EDIT</strong>: Thanks to Mike Müller's answer, I managed to make it work. Apparently, in my case invoking draw() is not enough, I have to get the values AFTER saving the figure using savefig(). It might depend on matplotlib's version, I am running 1.5.1 and Mike is running 1.5.0 . I will also take a look at FuncFormatter, as suggested below by tcaswell</p>
<p>You need to render the plot first to actually get labels. Adding a <code>draw()</code>works:</p> <pre><code>plot.draw() labelsY = ax1.get_yticklabels(which='both') </code></pre> <p>Without:</p> <pre><code>from matplotlib import pyplot as plt fig = plt.figure(figsize=(16,12), dpi=(300)) ax1 = fig.add_subplot(111) p = ax1.bar(range(5), range(5)) &gt;&gt;&gt; [item.get_text() for item in ax1.get_yticklabels(which='both')] ['', '', '', '', '', '', '', '', ''] </code></pre> <p>and with <code>draw()</code>:</p> <pre><code>from matplotlib import pyplot as plt fig = plt.figure(figsize=(16,12), dpi=(300)) ax1 = fig.add_subplot(111) p = ax1.bar(range(5), range(5)) plt.draw() &gt;&gt;&gt; [item.get_text() for item in ax1.get_yticklabels(which='both')] ['0.0', '0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0'] </code></pre>
python|matplotlib
7
1,904,051
37,516,298
Find next available IP address in python
<p>Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...</p> <pre><code>IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5'] </code></pre> <p>When I ask for the next IP address I need it to return '10.220.1.4'. The next request would return '10.220.1.6' and so on.</p>
<p>If you're using Python 3.3 (or newer), you can use the <a href="https://docs.python.org/3/library/ipaddress.html" rel="noreferrer"><code>ipaddress</code></a> module. Example for all hosts in the subnet <code>10.220.1.0/24</code> except for those in <code>reserved</code>:</p> <pre><code>from ipaddress import IPv4Network network = IPv4Network('10.220.1.0/24') reserved = {'10.220.1.1', '10.220.1.2', '10.220.1.3', '10.220.1.5'} hosts_iterator = (host for host in network.hosts() if str(host) not in reserved) # Using hosts_iterator: print(next(hosts_iterator)) # prints 10.220.1.4 print(next(hosts_iterator)) # prints 10.220.1.6 print(next(hosts_iterator)) # prints 10.220.1.7 # Or you can iterate over hosts_iterator: for host in hosts_iterator: print(host) </code></pre> <p>So basically this can be done in a single line (+ imports and definition of network and reserved addresses).</p>
python
8
1,904,052
65,922,125
Python Numpy - if array is in array
<p>I want to check with most efficiency way (the fastest way), if some array (or list) is in numpy array. But when I do this:</p> <pre><code>import numpy a = numpy.array( [ [[1, 2]], [[3, 4]] ]) print([[3, 5]] in a) </code></pre> <p>It only compares the first value and returns <code>True</code></p> <p>Somebody knows, how can I solve it? Thank you.</p>
<p>You could just add <code>tolist()</code> in your last line:</p> <pre><code>print([[3, 5]] in a.tolist()) </code></pre> <p>gives</p> <pre><code>False </code></pre>
python|arrays|python-3.x|list|numpy
1
1,904,053
65,939,149
How to replace repeated NaNs with a different value from lone NaNs from Pandas data frame
<p>I have several timeseries arranged in a data frame, similar to below:</p> <pre><code> category value time_idx 0 810 0.118794 0 1 830 0.552947 0 2 1120 0.133193 0 3 1370 0.840183 0 4 810 0.129385 1 ... ... ... ... 6095 1370 0.157391 1523 6096 810 0.141377 1524 6097 830 0.212254 1524 6098 1120 0.069970 1524 6099 1370 0.134947 1524 </code></pre> <p>Some values are NaN. What I would like is to replace any NaN values that are NOT repeated with 0, as I am assuming the value is 0 for that category at that time. However, any time that every single category has a value of NaN at that same time (i.e. at the same time_idx), then I want to replace every value with -1.</p> <p>Just replacing the NaNs with a value is of course trivial in Pandas, but the added complexity of specifically replacing NaNs that are NaN for every category at a given time has stumped me. I know I can just loop through the time indices, but my actual datasets will have over 900 categories, so I would like to find a more efficient Pandas-esque method.</p> <p>The only thing I could think of was list comprehension, which I don't think is even necessarily more efficient than an explicit loop anyway, plus I couldn't come up with one that worked properly.</p> <p>I know that I can just replace all NaNs like so:</p> <p><code>data[&quot;value&quot;] = data[&quot;value&quot;].replace(np.nan, 0)</code></p> <p>but I'm not sure how to implement this in my case, where I only want to replace long NaNs with 0. This is the loop I have currently:</p> <pre><code>num_channels = data[&quot;category&quot;].nunique() nan_vals = data[lambda x: np.isnan(x.value)] nan_times = nan_vals[&quot;time_idx&quot;] for time in nan_times: if nan_vals[lambda x: x.time_idx == time][&quot;category&quot;].nunique() &lt; num_channels: # Set 0 for every channel that has nan at time t index = nan_vals[lambda x: x.time_idx == time].index data.loc[index, [&quot;value&quot;]] = data.loc[index, &quot;value&quot;].replace(np.nan, 0) else: index = nan_vals[lambda x: x.time_idx == time].index data.loc[index, [&quot;value&quot;]] = data[lambda x: x.time_idx == time][&quot;value&quot;].replace(np.nan, -1) </code></pre> <p>Any ideas are appreciated.</p> <p>Here is an example:</p> <p>given the following data frame:</p> <pre><code> category value time_idx 0 810 NaN 0 1 830 NaN 0 2 1120 NaN 0 3 1370 NaN 0 4 810 0.129385 1 5 830 NaN 1 6 1120 0.144378 1 7 1370 NaN 1 8 810 0.124334 2 9 830 0.487274 2 10 1120 0.119153 2 11 1370 0.871687 2 </code></pre> <p>I would like this output:</p> <pre><code> category value time_idx 0 810 -1.000000 0 1 830 -1.000000 0 2 1120 -1.000000 0 3 1370 -1.000000 0 4 810 0.129385 1 5 830 0.000000 1 6 1120 0.144378 1 7 1370 0.000000 1 8 810 0.124334 2 9 830 0.487274 2 10 1120 0.119153 2 11 1370 0.871687 2 </code></pre> <p>In this example, at time = 0 every category's value was NaN, so they would be replaced with -1. At time = 1, there were non-NaN values, so any NaN values present (category 830 and 1370) would be replaced with 0.</p>
<p>You can find those <code>time_idx</code> where all entries are NaN using <code>groupby</code> and then <code>group.isna().all()</code>. You can use that mask to fill the NaNs with <code>-1</code>.</p> <p>Afterwards fill all other NaNs with <code>0</code> using <code>fillna</code>.</p> <pre><code>all_nas = df.groupby(&quot;time_idx&quot;).value.apply(lambda group: group.isna().all()) df = df.set_index(&quot;time_idx&quot;) df.loc[all_nas, &quot;value&quot;] = -1 df = df.reset_index().fillna(0) print(df) # time_idx category value # 0 0 810 -1.000000 # 1 0 830 -1.000000 # 2 0 1120 -1.000000 # 3 0 1370 -1.000000 # 4 1 810 0.129385 # 5 1 830 0.000000 # 6 1 1120 0.144378 # 7 1 1370 0.000000 # 8 2 810 0.124334 # 9 2 830 0.487274 # 10 2 1120 0.119153 # 11 2 1370 0.871687 </code></pre>
python|pandas|dataframe|nan|repeat
1
1,904,054
39,796,344
How can I call prompt_toolkit from the tornado event loop?
<p>I am trying to use prompt_toolkit from an application that uses the tornado event loop, but I can not work out the correct way to add the prompt_toolkit prompt to the event loop.</p> <p>The prompt_toolkit documentation has an example of using it in asyncio (<a href="http://python-prompt-toolkit.readthedocs.io/en/stable/pages/building_prompts.html#prompt-in-an-asyncio-application" rel="nofollow">Asyncio Docs</a>):</p> <pre><code>from prompt_toolkit.shortcuts import prompt_async async def my_coroutine(): while True: result = await prompt_async('Say something: ', patch_stdout=True) print('You said: %s' % result) </code></pre> <p>I have managed to make this work from the asyncio event loop:</p> <pre><code>import asyncio l = asyncio.get_event_loop() l.create_task(my_coroutine()) l.run_forever() Say something: Hello You said: Hello </code></pre> <p>However, I have failed to make it work from the tornado event loop. I have tried the following:</p> <pre><code>from tornado.ioloop import IOLoop IOLoop.current().run_sync(my_coroutine) </code></pre> <p>This will issue the initial prompt but then appears to block the console.</p> <p>I have also tried:</p> <pre><code>IOLoop.current().add_callback(my_coroutine) IOLoop.current().start() </code></pre> <p>This does the same thing, but also produces the error message:</p> <pre><code>RuntimeWarning: coroutine 'my_coroutine' was never awaited </code></pre> <p>And I have tried:</p> <pre><code>IOLoop.current().spawn_callback(my_coroutine) IOLoop.current().start() </code></pre> <p>I am clearly not understanding something here.</p> <p>Can anyone throw any light on how this should be done?</p> <p>I am using: Python 3.5.0, tornado 4.3.</p>
<p>To use <a href="http://www.tornadoweb.org/en/stable/asyncio.html" rel="nofollow">Tornado's asyncio integration</a>, you must tell Tornado to use the asyncio event loop. Usually, that means doing this at the start of your app:</p> <pre><code>from tornado.platform.asyncio import AsyncIOMainLoop AsyncIOMainLoop().install() </code></pre>
python|tornado|prompt|toolkit
0
1,904,055
31,816,938
ansible unexpected exception no escaped character
<p>I am fairly new to Ansible and to configuration management tools in general. I've been playing around with it for the last two days and for the life of me I can't get past typing out ansible testserver. It comes back with an error message that says Unexpected Exception: No escaped character. The full error message is: </p> <pre><code>mac-dgarcia:playbooks dgarcia$ ansible testserver -i hosts -m ping -vvv Using /Users/dgarcia/Documents/Playbooks/ansible.cfg as config file Unexpected Exception: No escaped character the full traceback was: Traceback (most recent call last): File "/Users/dgarcia/Documents/Playbooks/ansible/bin/ansible", line 79, in &lt;module&gt; sys.exit(cli.run()) File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/cli/adhoc.py", line 106, in run inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=self.options.inventory) File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/__init__.py", line 135, in __init__ self.parser = InventoryParser(filename=host_list) File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/ini.py", line 45, in __init__ self._parse() File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/ini.py", line 49, in _parse self._parse_base_groups() File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/ini.py", line 107, in _parse_base_groups tokens = shlex.split(line) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 279, in split return list(lex) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 269, in next token = self.get_token() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 96, in get_token raw = self.read_token() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 191, in read_token raise ValueError, "No escaped character" ValueError: No escaped character </code></pre> <p>Have searched everywhere I can on Google and came back with nothing. Any ideas?</p>
<p>I had the same issue and changing my host file to have only one line fixed the problem.</p> <p>My host file looks like the following: testserver ansible_ssh_host=128.0.0.1 ansible_ssh_port=2222 \ ansible_ssh_user=vagrant \ ansible_ssh_private_key_file=/home/bibryam/Desktop/.vagrant/machines/fabric/virtualbox/private_key</p>
python|ansible
6
1,904,056
38,909,156
Python Rainfall Calculator
<p>I'm trying to solve a problem but I've been working on it for so long and have tried so many things but I'm really new to python and don't know how to get the input I'm after.</p> <p>The calculator needs to be in a format of a nested loop. First it should ask for the number of weeks for which rainfall should be calculated. The outer loop will iterate once for each week. The inner loop will iterate seven times, once for each day of the week. Each itteration of the inner loop should ask the user to enter number of mm of rain for that day. Followed by calculations for total rainfall, average for each week and average per day. </p> <p>The main trouble I'm having is getting the input of how many weeks there are and the days of the week to iterate in the program eg:</p> <pre><code>Enter the amount of rain (in mm) for Friday of week 1: 5 Enter the amount of rain (in mm) for Saturday of week 1: 6 Enter the amount of rain (in mm) for Sunday of week 1: 7 Enter the amount of rain (in mm) for Monday of week 2: 7 Enter the amount of rain (in mm) for Tuesday of week 2: 6 </code></pre> <p>This is the type out output I want but so far I have no idea how to get it to do what I want. I think I need to use a dictionary but I'm not sure how to do that. This is my code thus far:</p> <pre><code>ALL_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] total_rainfall = 0 total_weeks = 0 rainfall = {} # Get the number of weeks. while True: try: total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: ")) except ValueError: print("Number of weeks must be an integer.") continue if total_weeks &lt; 1: print("Number of weeks must be at least 1") continue else: # age was successfully parsed and we're happy with its value. # we're ready to exit the loop! break for total_rainfall in range(total_weeks): for mm in ALL_DAYS: mm = int(input("Enter the amount of rain (in mm) for ", ALL_DAYS, "of week ", range(total_weeks), ": ")) if mm != int(): print("Amount of rain must be an integer") elif mm &lt; 0 : print("Amount of rain must be non-negative") # Calculate totals. total_rainfall =+ mm average_weekly = total_rainfall / total_weeks average_daily = total_rainfall / (total_weeks*7) # Display results. print ("Total rainfall: ", total_rainfall, " mm ") print("Average rainfall per week: ", average_weekly, " mm ") print("Average rainfall per week: ", average_daily, " mm ") if __name__=="__main__": __main__() </code></pre> <p>If you can steer me in the right direction I will be so appreciative! </p>
<p>I use a list to store average rallfall for each week. and my loop is:</p> <p>1.while loop ---> week (using i to count)</p> <p>2.in while loop: initialize week_sum=0, then use for loop to ask rainfall of 7 days.</p> <p>3.Exit for loop ,average the rainfall, and append to the list weekaverage.</p> <p>4.add week_sum to the total rainfall, and i+=1 to next week</p> <pre><code>weekaverage=[] i = 0 #use to count week while i&lt;total_weeks: week_sum = 0. print "---------------------------------------------------------------------" for x in ALL_DAYS: string = "Enter the amount of rain (in mm) for %s of week #%i : " %(x,i+1) mm = float(input(string)) week_sum += mm weekaverage.append(weeksum/7.) total_rainfall+=week_sum print "---------------------------------------------------------------------" i+=1 print "Total rainfall: %.3f" %(total_rainfall) print "Day average is %.3f mm" %(total_rainfall/total_weeks/7.) a = 0 for x in weekaverage: print "Average for week %s is %.3f mm" %(a,x) a+=1 </code></pre>
python|calculator
0
1,904,057
40,529,519
Change constant in tensoflow session while looping
<p>How can I change the tensorflow constant inside session <strong><em>for loop</em></strong>.<br> I am a learner and I am wondering how to update it in for loop</p> <hr> <pre><code>import tensorflow as tf import numpy as np looperCount = 10 data = np.random.randint(2, size=looperCount) x = tf.constant(data, name='x') y = tf.Variable((5 * (x * x)) - (3 * x) + 15, name="y") model = tf.initialize_all_variables() with tf.Session() as sess: for i in range(looperCount): sess.run(model) data = np.random.randint(2, size=looperCount) x = tf.constant(data, name='x') avg = np.average(sess.run(y)) print "avg - {}, sess - {}".format(avg, sess.run(y)) </code></pre> <hr> <p>Updated working code</p> <pre><code>import tensorflow as tf import numpy as np looperCount = 10 x = tf.placeholder("float", looperCount) y = (5 * (x * x)) - (3 * x) + 15 with tf.Session() as sess: for i in range(looperCount): data = np.random.randint(10, size=looperCount) result_y = sess.run(y, feed_dict={x: data}) avg = np.average(result_y) print "avg - {:10} valy - {:10}".format("{:.2f}".format(avg), result_y) </code></pre>
<p>In TensorFlow, "constant" means exactly that: once you set it, you can't change it. To change the value that your TensorFlow program uses in the loop, you have two main choices: (1) using a <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/io_ops.html#placeholder" rel="noreferrer"><code>tf.placeholder()</code></a> to feed in a value, or (2) using a <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/state_ops.html#Variable" rel="noreferrer"><code>tf.Variable</code></a> to store the value between steps, and <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/state_ops.html#Variable.assign" rel="noreferrer"><code>tf.Variable.assign()</code></a> to update it.</p> <p>Option 1 is much easier. Here's an example of how you could use it to implement your program using a placeholder:</p> <pre><code>import tensorflow as tf import numpy as np looperCount = 10 data = np.random.randint(2, size=looperCount) x = tf.placeholder(tf.float64, shape=[2], name="x") y = tf.Variable((5 * (x * x)) - (3 * x) + 15, name="y") init_op = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init_op) for i in range(looperCount): data = np.random.randint(2, size=looperCount) avg = np.average(sess.run(y, feed_dict={x: data})) print "avg - {}, sess - {}".format(avg, sess.run(y, feed_dict={x: data})) </code></pre>
tensorflow
10
1,904,058
9,857,059
Python infinite while loop inside a function
<p>No matter what I try I keep getting an infinite loop with this function:</p> <pre><code> # Excercise 33 - LPTHW i = 0 numbers = [] #Ec 1 #numb = 6 #iplus = 10 def theloop(numb): global i #i = 0 #number = [] while i &lt; numb: print "At the top of i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num theloop(7) </code></pre> <p>When I run the script it just keeps printing:</p> <pre><code>At the top of i is 0 At the top of i is 0 ... </code></pre> <p>Thanks in advance.</p>
<p>Your code works for me as written, but looks to have weird indentation due to use of mixed tabs and spaces. When I read your script using .readlines, you can see this:</p> <pre><code> ' def theloop(numb):\n', ' \t\tglobal i\n', ' \t\t#i = 0\n', ' #number = []\n', ' \t\twhile i &lt; numb:\n', ' \t\t\tprint "At the top of i is %d" % i\n', ' \t\tnumbers.append(i)\n', ' \n', ' \t\ti = i + 1\n', </code></pre> <p>So I'd recommend switching to four spaces everywhere and having another go. Note the difference in the number of tabs between the print statement and the append/increment statements.</p>
python|function|while-loop
2
1,904,059
68,205,965
Create Dummy variables from multiple variables in python
<p>I am having trouble to create dummy variables from a dataset like this one:</p> <pre><code>x = pd.DataFrame({'Temp':['Hot','Cold','Warm','Cold'],'Temp_2':[np.nan,'Warm','Cold',np.nan] </code></pre> <p>Note that the values are the same in both variables (Hot, Cold or Warm).</p> <pre><code> Temp Temp_2 0 Hot NaN 1 Cold Warm 2 Warm Cold 3 Cold NaN </code></pre> <p>So my problem is when using pd.get_dummies, the function does not take into consideration this relationship and codifies both variables independently.</p> <pre><code> Temp_Cold Temp_Hot Temp_Warm Temp_2_Cold Temp_2_Warm 0 0 1 0 0 0 1 1 0 0 0 1 2 0 0 1 1 0 3 1 0 0 0 0 </code></pre> <p>Is there a way I can codify it so i can get it like this?</p> <pre><code> Cold Hot Warm 0 0 1 0 1 1 0 1 2 1 0 1 3 1 0 0 </code></pre> <p>Thanks,</p>
<p>You can do something like this:</p> <pre><code>x = pd.DataFrame({'Temp':['Hot','Cold','Warm','Cold'],'Temp_2':[np.nan,'Warm','Cold',np.nan]}) print(x) a = pd.get_dummies(x, prefix=['','']) b = a.groupby(lambda x:x, axis=1).sum() print(b) </code></pre> <p>It is not so clean but works. Using prefix allows to have the same name in the columns generated from temp and temp_2.</p> <pre><code> _Cold _Hot _Warm 0 0 1 0 1 1 0 1 2 1 0 1 3 1 0 0 </code></pre>
python|categorical-data|dummy-variable
1
1,904,060
60,274,170
Python Regex: Apostrophes only when placed within letters, not as quotation marks
<p>define each word to be the longest contiguous sequence of alphabetic characters (or just letters), including up to one apostrophe if that apostrophe is sandwiched between two letters. </p> <pre><code>[a-z]+[a-z/'?a-z]*[a-z$] </code></pre> <p>It doesn't match the letter 'a'. </p>
<p>I'd use:</p> <pre><code>^(?:[a-z]+|[a-z]+'[a-z]+)$ </code></pre> <p>with <code>re.IGNORECASE</code></p> <p><a href="https://regex101.com/r/lXnqW0/1" rel="nofollow noreferrer">Demo &amp; explanation</a></p>
python|regex
0
1,904,061
60,262,725
Unable to load a pandas dataframe having a JSON column into mysql database
<p>I have a pandas dataframe that looks like this when I print it out in the terminal in pycharm. This is inside a django project</p> <pre><code>` exception recommendation time_dimension_id 0 {'exception': []} 0 217 1 {'exception': []} 0 218 2 {'exception': []} 0 219 3 {'exception': []} 546 220 4 {'exception': []} 2876 221 5 {'exception': []} 7855 222 6 {'exception': [{'error... , 5041 223 7 {'exception': []} 57 224 8 {'exception': []} 0 225 9 {'exception': []} 0 226 10 {'exception': []} 0 227 11 {'exception': []} 108 228 12 {'exception': []} 0 229 13 {'exception': []} 12 230 14 {'exception': []} 0 231 15 {'exception': []} 0 232 16 {'exception': []} 0 233 17 {'exception': []} 0 234 18 {'exception': []} 0 235 19 {'exception': []} 0 236 20 {'exception': []} 0 237 21 {'exception': []} 0 238 22 {'exception': []} 0 239 23 {'exception': []} 0 240 ` </code></pre> <p>I tried to insert this dataframe into a table using the below code.</p> <pre><code>connection = engine.connect() df.to_sql('table_name', con=connection, if_exists='append', index=False) </code></pre> <p>Then, I got the below error </p> <blockquote> <p>graphql.error.located_error.GraphQLLocatedError: (MySQLdb._exceptions.OperationalError) (3140, 'Invalid JSON text: "Missing a name for object member." at position 1 in value for column \'fact_exception.exception\'.') [SQL: 'INSERT INTO fact_exception (exception, recommendation, time_dimension_id) VALUES (%s, %s, %s)'] [parameters: (({'exception': []}, 0, 217), ({'exception': []}, 0, 218), ({'exception': []}, 0, 219), ({'exception': []}, 546, 220), ({'exception': []}, 2876, 221), ({'exception': []}, 7855, 222), ({'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn ... (6923 characters truncated) ... "resource.type":"index_or_alias","resource.id":"null","index_uuid":"<em>na</em>","index":"null"},"status":404}\n', 'time_stamp': '2020-02-11T06:26:23,694'}]}, 5041, 223), ({'exception': []}, 57, 224) ... displaying 10 of 24 total bound parameter sets ... ({'exception': []}, 0, 239), ({'exception': []}, 0, 240))] (Background on this error at: <a href="http://sqlalche.me/e/e3q8" rel="nofollow noreferrer">http://sqlalche.me/e/e3q8</a>)</p> </blockquote> <p>Below the relevant code used to create the dataframe column-wise</p> <pre><code> fact_excep["exception"] = excep_df_column #this is a list of dictionaries fact_excep["recommendation"] = recommendation_col #this is a list integers fact_excep["time_dimension_id"] = time_dimension_id_col #this is a list integers # print(fact_excep) connection = engine.connect() fact_excep.to_sql("fact_exception", con=connection, if_exists="append", index=False) response = "fact_exception data created" return response </code></pre> <p>Below is the model</p> <pre><code>class FactException (models.Model): #this is the model fact_exception_id = models.AutoField(primary_key=True) time_dimension_id = models.ForeignKey( TimeDimension, null=False, blank=True, db_column="time_dimension_id", on_delete=models.CASCADE) recommendation = models.IntegerField() exception = JSONField(null=True, blank=True) objects = models.Manager() class Meta: db_table = 'fact_exception' def __int__(self): return self.fact_exception_id </code></pre> <p>Any help will be appreciated.</p>
<p>Your column does not contain valid JSON:</p> <pre><code>{'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn...'}]} # and {'exception': []} </code></pre> <p>is not valid because the keys and strings have single quotes, which isn't valid in JSON. You should use double quotes and the whole column should be strings:</p> <pre><code>'{"exception": [{"error": "", "fatal": "com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn..."}]}' # and '{"exception": []}' </code></pre> <p>You're setting the column using a list of python dicts, but since you use <code>df.to_sql()</code> to save, this requires your data frame to have the exact data required by the SQL query. If you were using your model, you could just assign <code>my_factexception.exception = some_dict</code> and it would save as JSON. But you're essentially bypassing the Django ORM that knows your model and knows how to map a dictionary to a <code>jsonb</code> field so you have to do it yourself.</p> <p>So when you set the values for your exception column, use <code>json.dumps(some_dict)</code> to create json strings.</p>
python|mysql|django|pandas|graphql
2
1,904,062
2,197,891
How to Handle EOFError for raw_input() in python in Mac OS X
<p>My python program has two calls to <code>raw_input()</code> </p> <p>The first <code>raw_input()</code> is to take multiline input from the user. The user can issue Ctrl+D (Ctrl+Z in windows) for the end of input.</p> <p>Second <code>raw_input()</code> should take another input from user with (y/n) type prompt.</p> <p>Unfortunately (in Mac OS X only?), second <code>raw_input()</code> raises <code>EOFError</code> when the stdin is terminated (with Ctrl+D) at first <code>raw_input()</code> prompt.</p> <p>Please see my example code below for more explanation -</p> <pre><code>mailBody = '' signature = 'Later!' print 'Compose your mail:' while True: try: # Hit ^D after entering some text mailBody+= raw_input() mailBody+='\n' except EOFError: break # This raw_input() throws EOFError too. Because, stdin is terminated for the session # when EOF (^D) is issues at first raw_input() method (Where as, it doesn't raise EOFError in Linux) opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower() print '-'*10+'Your Mail' if opt == 'y': print mailBody+"\n"+signature else: print mailBody print '-'*19 </code></pre> <p>The program output:</p> <pre><code>-1- abhinay@MacBook code/py % python prompt.py Compose your mail: hello there! how is everybody? Do you want to add signature to your mail? (y/N): Traceback (most recent call last): File "prompt.py", line 11, in &lt;module&gt; opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower() EOFError </code></pre> <p>How can I make second prompt not to raise <code>EOFError</code>. Please help!</p> <p><strong>EDIT:</strong></p> <p>I've edited my question to keep it simple.</p> <p>I ran my above code in Linux System, it works without any issue. That is, the user was prompted at second raw_input() to receive '(y/N)' choice.</p>
<p>It's quite normal that when standard input is terminated (by hitting control-D, in Unix-derived systems -- I think it's control-Z in Windows), it <em>stays</em> terminated thereafter (unless you close and re-open it in the meantime, of course).</p>
python|macos|eof|eoferror
6
1,904,063
2,247,394
Bisect, is it possible to work with descending sorted lists?
<p>How can I use bisect module on lists that are sorted descending? e.g.</p> <pre><code>import bisect x = [1.0,2.0,3.0,4.0] # normal, ascending bisect.insort(x,2.5) # --&gt; x is [1.0, 2.0, 2.5, 3.0, 4.0] ok, works fine for ascending list # however x = [1.0,2.0,3.0,4.0] x.reverse() # --&gt; x is [4.0, 3.0, 2.0, 1.0] descending list bisect.insort(x,2.5) # --&gt; x is [4.0, 3.0, 2.0, 1.0, 2.5] 2.5 at end, not what I want really </code></pre> <p>The only methods are insort (insort_right) or insort_left - none of which work for me.</p>
<p>Probably the easiest thing is to borrow the code from the library and make your own version</p> <pre><code>def reverse_insort(a, x, lo=0, hi=None): """Insert item x in list a, and keep it reverse-sorted assuming a is reverse-sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo &lt; 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo &lt; hi: mid = (lo+hi)//2 if x &gt; a[mid]: hi = mid else: lo = mid+1 a.insert(lo, x) </code></pre>
python
24
1,904,064
32,437,842
Weird while loop causes infinite loop
<p>This is a small code snippet which is causing my program to crash due to an infinite loop</p> <pre><code>while not stack.is_empty(): if operators[stack.peek()] &gt;= operators[character]: result += stack.pop() </code></pre> <p>where stack is a Stack object and operators is a dictionary. The below code however does not cause an infinite loop</p> <pre><code>while not stack.is_empty() and operators[stack.peek()] &gt;= operators[character]: result += stack.pop() </code></pre> <p>My question is: Aren't these code snippets basically the same thing ? Why is one causing an infinite loop while the other isn't?</p> <p>Thanks</p>
<p>The first one keeps looping through and peeking at the stack and checking whether a condition is true, but continuing. In the second one it cuts off after the condition is false</p>
python|while-loop
3
1,904,065
44,183,545
Correct MIME Type for css.map files
<p>looking for a bit of help that will most likely help other devs.</p> <p>When serving files that are extension <code>.css.map</code> what should their MIME type be?</p> <p>This problem arose for me when serving files from s3 and in the upload process using boto3, one must set the MIME type for each files using the Python <a href="https://docs.python.org/2/library/mimetypes.html" rel="nofollow noreferrer">mimetypes</a> library. However <code>mimetypes</code> does not have all newer standards (i.e. '.scss', '.svg', '.js.map'). With that what is the appropriate MIME type for <code>.css.map</code> files?</p>
<p><code>.css.map</code> files should be <code>application/json</code></p> <p>As an educated guess, I will say that <code>.css.map</code> files MIME type should be <code>application/json</code> as determined from the <code>.css.map</code> and <code>.js.map</code> files being returned when navigating to <a href="http://getbootstrap.com/" rel="noreferrer">http://getbootstrap.com/</a></p> <p>The file is being served from <a href="http://getbootstrap.com/assets/css/docs.min.css.map" rel="noreferrer">http://getbootstrap.com/assets/css/docs.min.css.map</a></p>
python|http|amazon-s3|mime-types|boto3
8
1,904,066
34,492,203
How to apply Scroll VIew to Box Layout in kivy
<p>I have lots of Button and I want to apply scrollview to Box Layout like below</p> <pre><code>&lt;My Class&gt;: ScrollView: BoxLayout: Button: text:"buttone1" Button: text:"buttone1" Button: text:"buttone1" Button: text:"buttone1" Button: text:"buttone1" Button: text:"buttone1" GridLayout: rows:4 cols:4 Button: text:"buttone1" Button: text:"buttone1" Button: text:"buttone1" Button: text:"buttone1" Button: text:"buttone1" </code></pre> <p>how can i Apply Scrollview to above Content</p>
<p>put all the buttons and textviews inside a SINGLE layout and put that layout inside ScrollView. It should be working</p>
android|python|scroll|kivy
1
1,904,067
34,795,658
Python concatenating different size arrays stored in a list
<p>I have a list 'Z' with:</p> <pre><code>import numpy as np z[0] = np.random.normal( 0, 1, ( 500, 20 ) ) z[1] = np.random.normal( 0, 1, ( 500, 30 ) ) </code></pre> <p>There are about 100 arrays in the list. I am using only size 2 list for illustration. The stored arrays are all of dimension 0 of 500</p> <p>I want to achieve:</p> <pre><code>C = np.concatenate( ( z[0] , z[1] ),1) </code></pre> <p>I tried:</p> <pre><code>z1 = [ np.concatenate( z[ii], 1 ) for ii in range(0,len(z)) ] </code></pre> <p>but it still returns the original list and doesn't concatenate the stored arrays</p>
<p>Concatenation for multidimensional arrays is somewhat ill-defined without specifying an axis along which to concatenate. I assume you want to stack your arrays horizontally because the number of rows is the same for both. The simplest call is</p> <pre><code>stacked = np.hstack(Z) </code></pre> <p>which will concatenate along axis 1. You can find documentation <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.hstack.html" rel="noreferrer">here</a>. </p> <p>More generally, you can also use</p> <pre><code>stacked = np.concatenate(Z, axis=1) </code></pre> <p>which works for higher-dimensional arrays, too. The corresponding documentation is <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.concatenate.html" rel="noreferrer">here</a>.</p>
python|list
5
1,904,068
34,806,109
Why does if test fail to work with my parsing arg?
<p>I'm having a puzzle here trying to figure out what goes on in the machine. This is my code:</p> <pre><code>import argparse, sys from scitools.StringFunction import StringFunction parser = argparse.ArgumentParser() parser.add_argument('--f', '--function', type=str, default=None,\ help='Function', metavar='f') parser.add_argument('--fn', '--filename', type=str, default=None,\ help='Filename', metavar='fn') args = parser.parse_args() print args.f and args.fn == None, type(args.fn), type(args.f) if args.f and args.fn == str: f = StringFunction(args.f); filename = args.fn else: print 'Failed to provide f, filename or both!' sys.exit(1) </code></pre> <p>Running: <code>--f x**2 --fn somename</code> in terminal.</p> <p>Now the print statement yields:</p> <pre class="lang-none prettyprint-override"><code>False &lt;type 'str'&gt; &lt;type 'str'&gt; </code></pre> <p>in my terminal, but the if test gives:</p> <pre class="lang-none prettyprint-override"><code>Failed to provide f, filename or both! </code></pre> <p>right afterwards! Why does this happen?</p>
<p>The <em>type</em> of <code>args.fn</code> is <code>str</code>, but you test if <code>args.fn</code> is <em>itself</em> equal to it's type. It can't be both.</p> <p>You are doing this:</p> <pre><code>&gt;&gt;&gt; type('foo') &lt;type 'str'&gt; &gt;&gt;&gt; 'foo' == str False </code></pre> <p>Use <code>isinstance()</code> instead:</p> <pre><code>if args.f and isinstance(args.fn, str): </code></pre> <p>The better test would be to see if <code>args.fn</code> is <em>not <code>None</code></em>:</p> <pre><code>if args.f and args.fn is not None: </code></pre>
python|argparse
2
1,904,069
34,861,431
Adding new apps to django
<p>I have followed the guidelines for starting up learning django, but i have a question. if I want to add a new app onto the <code>polls</code> app they instructed, called <code>poll2</code>, can I just copy + paste the polls folder? (this is for example if I want to make an identical app, with same functionality). Is there anything else special i need to do, other than make <code>admin.py</code> load <code>poll2</code> along with polls?</p>
<p>There is a reason people say "copy paste is evil"</p> <p>However if you're willing to, you just need to make sure to change references (if they exist) to <code>poll</code> inside your new app to <code>poll2</code>.</p> <p>Because e.g. in poll/somefile.py there may be an absolute import in this form:</p> <pre><code>from poll import someting </code></pre> <p>Which isn't going to do well if that gets copied into <code>poll2</code> app and the goal is to use <code>poll2</code> and not use <code>poll</code> from <code>poll2</code></p> <p>And the list of things to rename from <code>poll</code> to <code>poll2</code> goes on and on. E.g. templates in <code>poll/templates/poll/something.html</code>, and perhaps URL namespaces, etc</p> <p>Bottom line, doable, just make sure absolute references are renamed to <code>poll2</code></p>
python|django
3
1,904,070
26,957,068
Python empty list Exception
<p>I have this function:</p> <pre><code>def foo(): a = [] if not a: print "empty" return None else: print "not empty" return a </code></pre> <p>Is there any Exception that do the same? Just to remove the if condition. Something like this:</p> <pre><code>def foo(list): try: a = list return a except: return None </code></pre>
<p>I would just use <code>return l if l else None</code>, you could try to index the list but I would not recommend it.</p> <pre><code>def foo(l): try: l[0] return l except IndexError: return None </code></pre>
python|python-2.7|exception|except
11
1,904,071
8,313,310
Selenium Grid2 - Is it possible to run 10 Chrome instances?
<p>Currently Selenium Grid2 running with the default config shows that it can run 5 firefox browsers, 5 chrome browsers and 1 IE. With a max of 5 instances at the same time.</p> <p>How can I change this so that it runs 10 chrome instances at the same time?</p> <p>I have succesfully changed the maxsession parameter of the node with <strong>-maxSession 10</strong>. However when I run 10 tests, the hub shows that 5 are in queue waiting to be executed. </p> <p>I dont know if this matters or not, but the hub itself shows a maxSession params of 5. Yet this one I couldn't change.</p> <p>Any ideas on how to do this?</p>
<p>I figured it out:</p> <p>run the node with the argument of MaxSession, and let the browser Configuration have the MaxInstances parameter, ie: </p> <pre><code>java -jar $JARFILE -Dwebdriver.chrome.driver=$CHROMEDRIVER -role webdriver -hub http://$HUB_IP:4444/grid/register -maxSession 10 -browser browserName=chrome,maxInstances=10" </code></pre> <p>pretty straightforward actually...</p>
python|google-chrome|selenium-webdriver|selenium-grid
7
1,904,072
41,767,102
Pandas Convert Week Date to Weekend Friday Date
<p>I have a pandas data frame with a column that has dates like so:</p> <pre><code>DATE 01/16/2017 01/17/2017 01/18/2017 01/19/2017 01/20/2017 </code></pre> <p>I need to convert each of those dates to a weekend date that is the date of the Friday of that corresponding week. So add a new column resulting in a data frame that looks like this:</p> <pre><code>DATE WEEK_ENDING 01/16/2017 01/20/2017 01/17/2017 01/20/2017 01/18/2017 01/20/2017 01/19/2017 01/20/2017 01/20/2017 01/20/2017 </code></pre> <p>Essentially I am looking for a Pandas solution to this question <a href="https://stackoverflow.com/questions/41068602/for-a-date-get-the-friday-of-the-week-ending">for a date get the friday of the week ending</a></p> <p>The format of the date itself is not that important. Is there a built in function that can do this or will I have to write one? Thanks!</p>
<p>You can use the built in <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#parametric-offsets" rel="noreferrer">DateOffsets</a> to achieve this:</p> <pre><code>In [310]: from pandas.tseries.offsets import * df['WEEK ENDING'] = df['DATE'] + Week(weekday=4) df Out[310]: DATE WEEK ENDING 0 2017-01-16 2017-01-20 1 2017-01-17 2017-01-20 2 2017-01-18 2017-01-20 3 2017-01-19 2017-01-20 4 2017-01-20 2017-01-27 </code></pre> <p>Note that technically because the last day rolls onto the following week, also your date strings need to be converted to datetime first using <code>pd.to_datetime</code>:</p> <pre><code>df['DATE'] = pd.to_datetime(df['DATE']) </code></pre> <p>You can fix the last row by testing if the calculated offset is the same as the original data by subtracting a week and using <code>where</code>:</p> <pre><code>In [316]: from pandas.tseries.offsets import * df['WEEK ENDING'] = df['DATE'].where( df['DATE'] == (( df['DATE'] + Week(weekday=4) ) - Week()), df['DATE'] + Week(weekday=4)) df Out[316]: DATE WEEK ENDING 0 2017-01-16 2017-01-20 1 2017-01-17 2017-01-20 2 2017-01-18 2017-01-20 3 2017-01-19 2017-01-20 4 2017-01-20 2017-01-20 </code></pre> <p>Here it leaves the last row untouched</p>
python|date|pandas
12
1,904,073
42,054,131
Customising code of Qt designer widget?
<p>I need to add some features to a graphics widget in a form I created using the Qt Designer. </p> <p>For example I would normally do something like this:</p> <pre><code>class custom_gv(QGraphicsView): def __init__(self): super().__init__() def zoom(self): # custom code here </code></pre> <p>But in this case the graphics view is a part of the window I made in Qt Designer. I know you can use the "promote to" feature in Qt designer but I don't know how to utilise that in code, especially considering that I use this method to use Qt Designer windows:</p> <pre><code>from PyQt5.uic import loadUiType custom_window = loadUiType('ui.ui') class Window(QMainWindow, custom_window): def __init__(self): QMainWindow.__init__(self) custom_window.__init__(self) self.setupUi(self) </code></pre> <p>So how would I go about customising the code of the graphics view in my window when I use Qt Designer?</p>
<p>The most common way to solve this is by using <a href="https://doc.qt.io/qt-5/designer-using-custom-widgets.html#promoting-widgets" rel="noreferrer">widget promotion</a>. This will allow you to replace a widget defined in Qt Designer with your own custom class. The steps for doing this are as follows:</p> <p>In Qt Designer, select the <code>QGraphicsView</code> you want to replace, then right-click it and select <em>Promote to...</em> . In the dialog, set <em>Promoted class name</em> to "custom_gv", and set <em>Header file</em> to the python import path for the module that contains this class (e.g. "mypkg.widgets"). Then click <em>Add</em>, and <em>Promote</em>, and you will see the class change from "QGraphicsView" to "custom_gv" in the Object Inspector pane.</p> <p>When the Qt Designer <code>ui</code> file is converted into PyQt code, it will automatically add an import statement like this:</p> <pre><code>from mypkg.widgets import custom_gv </code></pre> <p>and then in the converted code it will replace something like this:</p> <pre><code> self.graphicsView = QtWidgets.QGraphicsView(MainWindow) </code></pre> <p>with this:</p> <pre><code> self.graphicsView = custom_gv(MainWindow) </code></pre> <p>So the code in the <code>ui</code> file knows nothing about the custom class: it's just a name that is imported from elsewhere. That means you are completely free to write the custom class in any way you like.</p> <p>In PyQt, this mechanism works in the same way with <code>pyuic</code> as it does with the <code>uic</code> module. The <code>loadUi</code> and <code>loadUiType</code> functions generate exactly the same code as <code>pyuic</code> does. The only difference is that the <code>pyuic</code> tool writes the generated code to a file, whereas the <code>uic</code> module loads it directly via <a href="https://docs.python.org/3/library/functions.html#exec" rel="noreferrer"><code>exec</code></a>.</p>
python|pyqt|pyqt5|qt-designer|uic
5
1,904,074
41,906,117
While loop not iterating
<p>Everything is correct but what's going on in my while loop. I'm trying to write this function recursively, and this is what i've come up with. </p> <pre><code>def fp(f, guess, error=0.0000000000001): p_guess = guess c_guess = f(p_guess) iterations = 0 while not close(p_guess, c_guess, error=error): next = f(guess) iterations += 1 return fp(f, next, error=error) return (iterations, c_guess) def fp_sqrt(x): return fp(lambda y: (y + x/y)/2, 1.0) </code></pre> <p>I know I'm missing something. Someone told me to take the return statement out of the scope from the while loop, but that just made an infinite loop.</p> <p>From shell:</p> <blockquote> <blockquote> <blockquote> <p>fp_sqrt(2)</p> </blockquote> </blockquote> </blockquote> <p>Expected output: (5, 1.414213562373095)</p> <p>My output: (0, 1.414213562373095) So the variable isn't incrementing to show how many iterations i went through in the loop. </p>
<p>You should not resolve this with recursion but just by iterating and reassigning the results back to the loop variables, e.g.:</p> <pre><code>while not close(p_guess, c_guess, error=error): p_guess, c_guess = c_guess, f(c_guess) iterations += 1 return iterations, c_guess #fp_sqrt(2) -&gt; (5, 1.414213562373095) </code></pre> <p>Note: <code>next</code> is a builtin and you shouldn't use it as a variable name</p> <p>You could have made this recursive but it makes the <code>while</code> just a verbose <code>if</code> statement:</p> <pre><code>while not close(p_guess, c_guess, error=error): # if would suffice iterations, result = fp(f, c_guess, error=error) return iterations+1, result return (0, c_guess) #fp_sqrt(2) -&gt; (5, 1.414213562373095) </code></pre>
python|loops|while-loop|increment
0
1,904,075
47,403,407
Is Tensorflow Dataset API slower than Queues?
<p>I replaced CIFAR-10 preprocessing pipeline in the project with Dataset API approach and it resulted in performance decrease of about 10-20%.</p> <p>Preporcessing is rather standart: - read image from disk - make random/crop and flip - shuffle, batch - feed to the model</p> <p>Overall i see that batche processing is now 15% faster, but every once in a while (or, more precisely, whenever I reinitialize dataframe or expect reshuffling) the batch is being blocked for up long time (30 sec) which totals to slower epoch-per-epoch processing.</p> <p>This behaviour seems to do something with internal hashing. If I reduce N in ds.shuffle(buffer_size=N) delays are shorter but proportionally more frequent. Removing shuffle at all results to delays as if buffer_size was set to dataset size.</p> <p>Can somebody explain internal logic of Dataset API when it comes to reading/caching? Is there any reason at all to expect Dataset API to work faster than manually created Queues?</p> <p>I am using TF 1.3.</p>
<p>If you implement the <strong>same</strong> pipeline using the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="noreferrer"><code>tf.data.Dataset</code></a> API and using queues, the performance of the Dataset version should be better than the queue-based version.</p> <p>However, there are a few performance best practices to observe in order to get the best performance. We have collected these in a <a href="https://www.tensorflow.org/performance/datasets_performance" rel="noreferrer">performance guide for <code>tf.data</code></a>. Here are the main issues:</p> <ul> <li><p>Prefetching is important: the queue-based pipelines prefetch by default and the Dataset pipelines do not. Adding <code>dataset.prefetch(1)</code> to the end of your pipeline will give you most of the benefit of prefetching, but you might need to tune this further.</p> </li> <li><p>The shuffle operator has a delay at the beginning, while it fills its buffer. The queue-based pipelines shuffle a concatenation of all epochs, which means that the buffer is only filled once. In a Dataset pipeline, this would be equivalent to <code>dataset.repeat(NUM_EPOCHS).shuffle(N)</code>. By contrast, you can also write <code>dataset.shuffle(N).repeat(NUM_EPOCHS)</code>, but this needs to restart the shuffling in each epoch. The latter approach is slightly preferable (and truer to the definition of SGD, for example), but the difference might not be noticeable if your dataset is large.</p> <p>We are adding a fused version of shuffle-and-repeat that doesn't incur the delay, and a nightly build of TensorFlow will include the custom <a href="https://github.com/tensorflow/tensorflow/blob/97a4c226e8a9e7c5c36fc38e2b9f8459c77abd5a/tensorflow/contrib/data/python/ops/shuffle_ops.py#L88" rel="noreferrer"><code>tf.contrib.data.shuffle_and_repeat()</code></a> transformation that is equivalent to <code>dataset.shuffle(N).repeat(NUM_EPOCHS)</code> but doesn't suffer the delay at the start of each epoch.</p> </li> </ul> <p>Having said this, if you have a pipeline that is significantly slower when using <code>tf.data</code> than the queues, please file a <a href="https://github.com/tensorflow/tensorflow/issues" rel="noreferrer">GitHub issue</a> with the details, and we'll take a look!</p>
performance|tensorflow|tensorflow-datasets
10
1,904,076
47,227,280
pandas groupby apply on multiple columns to generate a new column
<p>I like to generate a new column in pandas dataframe using groupby-apply.</p> <p>For example, I have a dataframe:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3,4],'B':['A','B','A','B'],'C':[0,0,1,1]}) </code></pre> <p>and try to generate a new column 'D' by groupby-apply. </p> <p>This works:</p> <pre><code>df = df.assign(D=df.groupby('B').C.apply(lambda x: x - x.mean())) </code></pre> <p>as (I think) it returns a series with the same index with the dataframe:</p> <pre><code>In [4]: df.groupby('B').C.apply(lambda x: x - x.mean()) Out[4]: 0 -0.5 1 -0.5 2 0.5 3 0.5 Name: C, dtype: float64 </code></pre> <p>But if I try to generate a new column using multiple columns, I cannot assign it directly to a new column. So this doesn't work:</p> <pre><code> df.assign(D=df.groupby('B').apply(lambda x: x.A - x.C.mean())) </code></pre> <p>returning</p> <pre><code>TypeError: incompatible index of inserted column with frame index </code></pre> <p>and in fact, the groupby-apply returns:</p> <pre><code>In [8]: df.groupby('B').apply(lambda x: x.A - x.C.mean()) Out[8]: B A 0 0.5 2 2.5 B 1 1.5 3 3.5 Name: A, dtype: float64 </code></pre> <p>I could do</p> <pre><code>df.groupby('B').apply(lambda x: x.A - x.C.mean()).reset_index(level=0,drop=True)) </code></pre> <p>but it seems verbose and I am not sure if this will work as expected always.</p> <p>So my question is: (i) when does pandas groupby-apply return a like-indexed series vs a multi-index series? (ii) is there a better way to assign a new column by groupby-apply to multiple columns?</p>
<p>For this case I do not think include the column A in apply is necessary, we can use <code>transform</code></p> <pre><code>df.A-df.groupby('B').C.transform('mean') Out[272]: 0 0.5 1 1.5 2 2.5 3 3.5 dtype: float64 </code></pre> <p>And you can assign it back</p> <pre><code>df['diff']= df.A-df.groupby('B').C.transform('mean') df Out[274]: A B C diff 0 1 A 0 0.5 1 2 B 0 1.5 2 3 A 1 2.5 3 4 B 1 3.5 </code></pre>
python|pandas|pandas-groupby|pandas-apply
5
1,904,077
70,998,061
How to convert a polynomial user input into python readable form
<p>I have the following input:</p> <p><img src="https://i.stack.imgur.com/VtTb4.png" alt="enter image description here" /></p> <p>and I want to convert it into python readable form like this <code>'x**2 + 2*x + 2'</code> so that I can use it as an input to other functions. I have:</p> <pre><code>def func_parse(func): return func.replace(&quot;^&quot;,&quot;**&quot;) </code></pre> <p>but this will only resolve the power part. I also want to add '*' in between '2x' to conform with the python syntax.</p>
<p>Install <a href="https://www.sympy.org/en/index.html" rel="nofollow noreferrer"><code>sympy</code></a>:</p> <pre><code>from sympy.parsing.sympy_parser import ( parse_expr, stringify_expr, standard_transformations, implicit_multiplication_application, convert_xor ) transformations = (standard_transformations + (implicit_multiplication_application, convert_xor)) f = 'x^2 + 2x + 3' expr = parse_expr(f, transformations=transformations) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; str(expr) 'x**2 + 2*x + 3' </code></pre> <p><strong>Update</strong></p> <blockquote> <p>Evaluate the polynomial output with an integer value, let's say (x =2).</p> </blockquote> <pre><code>&gt;&gt;&gt; expr.evalf(subs=dict(x=2)) 11.0000000000000 </code></pre>
python|function|user-input|numerical-methods|polynomials
1
1,904,078
70,773,718
Coloring a random graph in python
<p>I have a script that implements greedy coloring in python, in other words it colors a graph with four colors. I wanted to generate a random graph and then pass it into the script found on the link above to color it. This is how I generate a random graph (in the shape of a dictionary):</p> <pre><code>list = [1,2,3,4,5] d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1)) for i in q} </code></pre> <p>So what i need now is some kind of function that passes the created dictionary into the greedy coloring script, because if i enter the graph d in the function in the script called <em>greedycoloring</em> I get the following error:</p> <pre><code> Traceback (most recent call last): File &quot;/private/var/mobile/Containers/Shared/AppGroup/9244016A-6D10-4627-B39B-6D63D3F9D22C/Pythonista3/Documents/nuovaprova.py&quot;, line 88, in &lt;module&gt; greedyColoring(d, 5) File &quot;/private/var/mobile/Containers/Shared/AppGroup/9244016A-6D10-4627-B39B-6D63D3F9D22C/Pythonista3/Documents/nuovaprova.py&quot;, line 33, in greedyColoring if (result[i] != -1): IndexError: list index out of range </code></pre>
<p>Start <code>list</code> q from 0 as shown below:</p> <pre><code>q = [0, 1, 2, 3, 4] d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1)) for i in q} </code></pre> <p>Then, you can directly pass dictionary <code>d</code> into the script as :</p> <pre><code> greedyColoring(d, 5) </code></pre> <p>The given script represents graph as <code>list of lists</code> where index of list represents the node and its corresponding value represents its adjacent nodes, so you can also convert <code>d</code> into list of list as <code>[node for node in d.values()]</code> and then pass into the function as:</p> <pre><code>greedyColoring([node for node in d.values()], 5) </code></pre>
python|arrays|list|dictionary|random
1
1,904,079
33,903,560
scipy: finding optimal parameters with fmin and odeint, bad fit
<p>Below I solve a second order ODE that describes a spring-mass dashpot system: u'' +c<em>u'+k</em>u=0. I have no problems with the odeint solver.The odeint function correctly solves the position U(t) over the specified time. </p> <pre><code>#modeling spring mass system import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint from scipy import integrate #Make the following substitution to make system first order #Y[1]=y′(t) and Y[0]=y(t), #system: Y[0]'=Y[1] and Y[1]'=-c*Y[1]-k*Y[0] #======================================================= def eq(par,initial_cond,start_t,end_t,incr): #-time-grid----------------------------------- t = np.linspace(start_t, end_t,incr) #differential-eq-system---------------------- def funct(y,t): ut=y[0] ut_dt=y[1] c,k=par # the model equations u'=Y[1], u''=-k*Y[0]-c*Y[1] from u''+c*u'+k*u=0 f0 =ut_dt f1 =-k*ut-c*ut_dt return [f0, f1] #integrate------------------------------------ ds = integrate.odeint(funct,initial_cond,t) return (ds[:,0],ds[:,1],t) #======================================================= #parameters c=2. #spring coefficient k=10. #dampening coefficient #collect parameters in tuple coefs=(c,k) # initial conditions u0=6. ud0=0. y0=[u0,ud0] start,stop,incr=0,20,100 #Solve and plot solution F0,F1,T=eq(coefs,y0,start,stop,incr) plt.figure() plt.plot(T,F0,'-b',T,F1,'-r') plt.legend(('u0', 'u1'),'upper center') plt.title('Mass-Spring System') </code></pre> <p>However, I would like to use scipy.optimize.fmin() to find the optimal fitting parameters (c,k) for this system if given simulated measurements. So I use the solution from above where c=2, and k=10 and add random noise.</p> <pre><code>rand_i=randn(incr) #noiselevel nl=.05 noisy_data=F0+nl*rand_i plt.plot(noisy_data,label="noisy_data:c=2,k=10") plt.legend() </code></pre> <p>Next, I set up a scoring function for fmin() to minimize. I use a guess for the parameters, c=1,k=1.</p> <pre><code>from scipy.optimize import fmin #1.Get 'Real' Data #==================================================== nd=noisy_data#solution with parameters: c=2,k=10 #==================================================== #2.Set up Info for Model System #=================================================== # guess parameters c=1 #spring coefficient k=1 #dampening coefficient #collect parameters in tuple coefs=(c,k) # initial conditions u0=6. ud0=0. y0=[u0,ud0] # model steps #--------------------------------------------------- start_time=0 end_time=20 intervals=100 mt=np.linspace(start_time,end_time,intervals) #3.Score Fit of System #========================================================= def score(parms): #a.Get Solution to system F0,F1,T=eq(coefs,y0,start_time,end_time,intervals) #b.Pick of Model Points to Compare um=F0 #c.Score Difference between model(ode output) and data points (noisy data) ss=lambda data,model:((data-model)**2).sum() return ss(nd,um) #======================================================== #4.Optimize Fit #======================================================= fit_score=score(coefs) answ=fmin(score,(coefs)) </code></pre> <p>The problem is that fmin doesn't find the correct parameters. It finds that the guess parameters are the best, even though the score function is high. Below I print the fmin solution answ and show that it is the same as the initial guess even after fmin() has been called. </p> <pre><code>print(answ==[c,k]) </code></pre> <p>Does anyone know why fmin() doesn't find the correct parameters, c=2, k=10?</p>
<p>There is a trivial bug in your code: you define <code>score</code> with input parameter <code>parms</code>, but then refer to said variable as <code>coefs</code>. Fix:</p> <pre><code>def score(coefs): #changed #a.Get Solution to system F0,F1,T=eq(coefs,y0,start_time,end_time,intervals) #b.Pick of Model Points to Compare um=F0 #c.Score Difference between model(ode output) and data points (noisy data) ss=lambda data,model:((data-model)**2).sum() return ss(nd,um) </code></pre> <p>Before:</p> <pre><code>In [369]: answ Out[369]: array([ 1., 1.]) </code></pre> <p>After:</p> <pre><code>In [373]: answ Out[373]: array([ 2.0425695 , 9.96937966]) </code></pre> <p>However, note that <code>answ==(c,k)</code> will <em>always</em> be <code>False</code>, even for a perfect fit: you're working with floating-point numbers. Any meaningful comparison should look like <code>max(abs(answ-[2,10])/abs(answ))&lt;tol</code> or something similar. (I know your original question used this to show that the values <em>didn't</em> change, but still.)</p>
python|numpy|scipy
0
1,904,080
37,974,359
how to extract a headline form a url?
<p>I have a dataset of headlines, such as</p> <pre><code>http://www.stackoverflow.com/lifestyle/tech/this-is-a-very-nice-headline-my-friend/2013/04/26/acjhrjk-2e1-1krjke4-9el8c-2eheje_story.html?tid=sm_fb http://www.stackoverflow.com/2015/07/15/sports/baseball/another-very-nice.html?smid=tw-somedia&amp;seid=auto http://worldnews.stack.com/news/2013/07/22/54216-hello-another-one-here?lite http://www.stack.com/article_email/hello-one-here-that-is-cool-1545545554-lMyQjAxMTAHFJELMDgxWj http://www.stack.com/2013/11/13/tech/tricky-one/the-real-one/index.html http://www.stack.com/2013/11/13/tech/the-good-one.html http://www.stack.com/news/science-and-technology/54512-hello-world-here-is-a-weird-character#b02g07f20b14 </code></pre> <p>I need to extract from these kind of links the proper headline, that is:</p> <ul> <li>this-is-a-very-nice-headline-my-friend</li> <li>another-very-nice</li> <li>hello-another-one-here</li> <li>hello-one-here-that-is-cool</li> <li>the-real-one </li> <li>the-good-one</li> <li>hello-world-here-is-a-weird-character</li> </ul> <p>so the rule seems to find the <strong>longest</strong> string of the form <code>word1-word2-word3</code>- that has a <code>/</code> at the right or left border and <strong>without</strong> considering </p> <ol> <li>words with more than 3 digits (for instance <code>acjhrjk-2e1-1krjke4-9el8c-2eheje</code> in the first link, or <code>54216</code> in the third one ,</li> <li>excluding stuff like <code>.html</code>.</li> </ol> <p>How can I do that using <strong>regex</strong> in Python? I believe regex is the only viable solution here unfortunately. Packages such as <code>yurl</code> or <code>urlparse</code> can capture the path of the url, but then I am back to using regex to get the headline..</p> <p>Many thanks!</p>
<p>After all, regular expressions might not be your best bet.<br> However, with the specifications you came up with, you could do the following:</p> <pre><code>import re urls = ['http://www.stackoverflow.com/lifestyle/tech/this-is-a-very-nice-headline-my-friend/2013/04/26/acjhrjk-2e1-1krjke4-9el8c-2eheje_story.html?tid=sm_fb', 'http://www.stackoverflow.com/2015/07/15/sports/baseball/another-very-nice.html?smid=tw-somedia&amp;seid=auto', 'http://worldnews.stack.com/news/2013/07/22/54216-hello-another-one-here?lite', 'http://www.stack.com/article_email/hello-one-here-that-is-cool-1545545554-lMyQjAxMTAHFJELMDgxWj', 'http://www.stack.com/2013/11/13/tech/tricky-one/the-real-one/index.html', 'http://www.stack.com/2013/11/13/tech/the-good-one.html', 'http://www.stack.com/news/science-and-technology/54512-hello-world-here-is-a-weird-character#b02g07f20b14'] regex = re.compile(r'(?&lt;=/)([-\w]+)(?=[.?/#]|$)') digits = re.compile(r'-?\d{3,}-?') for url in urls: substrings = regex.findall(url) longest = max(substrings, key=len) headline = re.sub(digits, '', longest) print headline </code></pre> <p><hr> This will print </p> <pre><code> this-is-a-very-nice-headline-my-friend another-very-nice hello-another-one-here hello-one-here-that-is-coollMyQjAxMTAHFJELMDgxWj the-real-one the-good-one hello-world-here-is-a-weird-character </code></pre> <p>See <a href="http://ideone.com/9eHKQt" rel="nofollow"><strong>a demo on ideone.com</strong></a>.</p> <hr> <h3>Explanation</h3> <p>Here, the regex uses <strong>lookarounds</strong> to look for a <code>/</code> behind and one of <code>.?/#</code> ahead. Any word character and dash in between is captured.<br> This is not very specific but if you're looking for the longest substring and eliminate more then three consecutive digits afterwards, it might be a good starting point.<br> As already said in the comments, you might perhaps be better off using linguistic tools.</p>
python|regex|string|url-parameters|urlparse
1
1,904,081
37,720,639
How do i figure out the multiple of a number python
<p>ok, I am studying python in my computing course and i have been challenged with designing a code which validates a GTIN-8 code, I have came to a hurdle that i can not jump. I have looked on how to find the equal or higher multiple of a 10 and i have had no success so far, hope you guys can help me! </p> <p>Here is a small piece of code, i need to find the equal or higher multiple of 10;</p> <blockquote> <pre><code>NewNumber = (NewGtin_1 + Gtin_2 + NewGtin_3 + Gtin_4 + NewGtin_5 + Gtin_6 + NewGtin_7) print (NewNumber) </code></pre> </blockquote>
<p>The easiest way, involving no functions and modules, could be using floor division operator <code>//</code>.</p> <pre><code>def neareast_higher_multiple_10(number): return ((number // 10) + 1) * 10 </code></pre> <p>Examples of usage:</p> <pre><code>&gt;&gt;&gt; neareast_higher_multiple_10(15) 20 &gt;&gt;&gt; neareast_higher_multiple_10(21) 30 &gt;&gt;&gt; neareast_higher_multiple_10(20.1) 30.0 &gt;&gt;&gt; neareast_higher_multiple_10(20) 30 </code></pre> <p>We can also make a generalized version:</p> <pre><code>def neareast_higher_multiple(number, mult_of): return ((number // mult_of) + 1) * mult_of </code></pre> <p>If you need nearest lower multiple, just remove <code>+ 1</code>:</p> <pre><code>def neareast_lower_multiple(number, mult_of): return (number // mult_of) * mult_of </code></pre> <p>To find the nearest multiple, you can call both these functions and use that one with a lower difference from the original number.</p>
python|numbers
2
1,904,082
29,854,530
Is there any smart way to combine overlapping paths in python?
<p>Let's say I have two path names: <strong>head</strong> and <strong>tail</strong>. They can overlap with any number of segments. If they don't I'd like to just join them normally. If they overlap, I'd like to detect the common part and combine them accordingly. To be more specific: If there are repetitions in names I'd like to find as long overlapping part as possible. Example</p> <pre><code>"/root/d1/d2/d1/d2" + "d2/d1/d2/file.txt" == "/root/d1/d2/d1/d2/file.txt" and not "/root/d1/d2/d1/d2/d1/d2/file.txt" </code></pre> <p>Is there any ready-to-use library function for such case, or I have to implement one?</p>
<p>I would suggest you to use <a href="https://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher" rel="nofollow">difflib.SequenceMatcher</a> followed by <a href="https://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks" rel="nofollow">get_matching_blocks</a></p> <pre><code>&gt;&gt;&gt; p1, p2 = "/root/d1/d2/d1/d2","d2/d1/d2/file.txt" &gt;&gt;&gt; sm = difflib.SequenceMatcher(None,p1, p2) &gt;&gt;&gt; size = sm.get_matching_blocks()[0].size &gt;&gt;&gt; path = p1 + p2[size:] &gt;&gt;&gt; path '/root/d1/d2/d1/d2/file.txt' </code></pre> <p>Ans a General solution</p> <pre><code>def join_overlapping_path(p1, p2): sm = difflib.SequenceMatcher(None,p1, p2) p1i, p2i, size = sm.get_matching_blocks()[0] if not p1i or not p2i: None p1, p2 = (p1, p2) if p2i == 0 else (p2, p1) size = sm.get_matching_blocks()[0].size return p1 + p2[size:] </code></pre> <p>Execution</p> <pre><code>&gt;&gt;&gt; join_overlapping_path(p1, p2) '/root/d1/d2/d1/d2/file.txt' &gt;&gt;&gt; join_overlapping_path(p2, p1) '/root/d1/d2/d1/d2/file.txt' </code></pre>
python|python-3.x|string|path
3
1,904,083
61,435,502
Bad escape error when using a regular expression to remove punctuation in Python
<p>I am trying to remove punctuations from the text stored in the variable <code>clean_string</code>. Therefore, I attempted to use the following regular expression within the <code>sub</code> method: </p> <pre><code>remove_punc = re.sub(r'[^\P{P}-]+',"", clean_string) </code></pre> <p>Nevertheless, I am getting the following traceback error:</p> <pre><code>error Traceback (most recent call last) &lt;ipython-input-43-2954d0a309ca&gt; in &lt;module&gt; 7 paper_body_without_stopwords = [token for token in body_tokens if not token in stopwords.words('english')] #remove the stop words in the body and return a list 8 clean_string = ' '.join(paper_body_without_stopwords) #convert the list into string ----&gt; 9 remove_punc = re.sub('[^\P{P}-]+',"", clean_string) 10 final_cleaned_String = re.sub(r"\bThe\b", r"", remove_punc) 11 clean_text.append(final_cleaned_String) #add the string to the array c:\users\hp\appdata\local\programs\python\python36\lib\re.py in sub(pattern, repl, string, count, flags) 189 a callable, it's passed the match object and must return 190 a replacement string to be used.""" --&gt; 191 return _compile(pattern, flags).sub(repl, string, count) 192 193 def subn(pattern, repl, string, count=0, flags=0): c:\users\hp\appdata\local\programs\python\python36\lib\re.py in _compile(pattern, flags) 299 if not sre_compile.isstring(pattern): 300 raise TypeError("first argument must be string or compiled pattern") --&gt; 301 p = sre_compile.compile(pattern, flags) 302 if not (flags &amp; DEBUG): 303 if len(_cache) &gt;= _MAXCACHE: c:\users\hp\appdata\local\programs\python\python36\lib\sre_compile.py in compile(p, flags) 560 if isstring(p): 561 pattern = p --&gt; 562 p = sre_parse.parse(p, flags) 563 else: 564 pattern = None c:\users\hp\appdata\local\programs\python\python36\lib\sre_parse.py in parse(str, flags, pattern) 853 854 try: --&gt; 855 p = _parse_sub(source, pattern, flags &amp; SRE_FLAG_VERBOSE, 0) 856 except Verbose: 857 # the VERBOSE flag was switched on inside the pattern. to be c:\users\hp\appdata\local\programs\python\python36\lib\sre_parse.py in _parse_sub(source, state, verbose, nested) 414 while True: 415 itemsappend(_parse(source, state, verbose, nested + 1, --&gt; 416 not nested and not items)) 417 if not sourcematch("|"): 418 break c:\users\hp\appdata\local\programs\python\python36\lib\sre_parse.py in _parse(source, state, verbose, nested, first) 525 break 526 elif this[0] == "\\": --&gt; 527 code1 = _class_escape(source, this) 528 else: 529 code1 = LITERAL, _ord(this) c:\users\hp\appdata\local\programs\python\python36\lib\sre_parse.py in _class_escape(source, escape) 334 if len(escape) == 2: 335 if c in ASCIILETTERS: --&gt; 336 raise source.error('bad escape %s' % escape, len(escape)) 337 return LITERAL, ord(escape[1]) 338 except ValueError: error: bad escape \P at position 2 </code></pre>
<p>The error is on '<code>\P{P}</code> because <code>Python 3.6</code> does not support Unicode properties. You can try the following to remove all punctuation, except <code>-</code>:</p> <pre><code>import re all_puntuation = """!"#$%&amp;'()*+,./:;&lt;=&gt;?@[\]^_`{|}~""" dirty_string = "$&lt;-&gt;311-abc(){}..//...-" clean_string = re.sub(rf"[{all_puntuation}]", '', dirty_string) # -311-abc- </code></pre> <p><a href="https://trinket.io/python3/e6a7a2a12e" rel="nofollow noreferrer">Demo</a></p>
python|regex|python-3.x
3
1,904,084
43,370,872
How to plot graph between two timedelta variable in pandas?
<p>i have the following dataset :</p> <pre><code>Duration1 Duration2 05:13:45 01:09:58 18:53:38 01:53:18 NaT 01:03:38 07:19:38 01:23:26 </code></pre> <p>I want to plot a graph between the duration1 and duration2 ?</p> <pre><code>df['duration1'] =[" 05:13:45 "," 18:53:38 "," NaT ","07:19:38"] df['duration2'] = [" 01:09:58","01:53:18","01:03:38","01:23:26"] </code></pre> <p>The datatype of the duration 1 and duration 2 are timedelta64[ns]</p> <p>Bonus: Is it possible to get a function based on the trend of the graph plotted?</p>
<p>use <code>dt.total_seconds</code></p> <pre><code>df.stack().dt.total_seconds().unstack().plot.scatter( 'Duration1', 'Duration2') </code></pre> <p><a href="https://i.stack.imgur.com/FepcS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FepcS.png" alt="enter image description here"></a></p> <p>Easiest way to get the trendline is to use <code>seaborn.regplot</code></p> <pre><code>import seaborn as sns d = df.stack().dt.total_seconds().unstack() sns.regplot(d.Duration1, d.Duration2, ci=None) </code></pre> <p><a href="https://i.stack.imgur.com/keWPo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/keWPo.png" alt="enter image description here"></a></p> <hr> <p><strong><em>code from start to finish</em></strong><br> <em>you should be able to copy/paste this</em> </p> <pre><code>from io import StringIO import pandas as pd import seaborn as sns txt = """Duration1 Duration2 -1 days +05:13:45 0 days 01:09:58 -6 days +18:53:38 0 days 01:53:18 NaT 0 days 01:03:38 10 days +07:19:38 0 days 01:23:26 """ df = pd.read_csv(StringIO(txt), sep='\s{2,}', engine='python').apply(pd.to_timedelta) d = df.stack().dt.total_seconds().unstack() sns.regplot(d.Duration1, d.Duration2, ci=None) </code></pre>
python|pandas|datetime|matplotlib
2
1,904,085
36,896,672
Pascal's Triangle - type error
<p>So my code for some reason is giving me the error:</p> <pre class="lang-none prettyprint-override"><code>TypeError: Can't convert 'int' object to str implicitly </code></pre> <p>It has to do with the line:</p> <pre><code>answer = answer + combination(row, column) + "\t" </code></pre> <p>Here is my code:</p> <pre><code>def combination(n, k): if k == 0 or k == n: return 1 return combination(n - 1, k - 1) + combination(n - 1, k) def pascals_triangle(rows): for row in range(rows): answer = "" for column in range(row + 1): answer = answer + combination(row, column) + "\t" print(answer) pascals_triangle(10) </code></pre>
<blockquote> <p>TypeError: Can't convert 'int' object to str implicitly</p> </blockquote> <p>In this line:</p> <pre><code>answer = answer + combination(row, column) + "\t" ^ ^ |__ str |__ int </code></pre> <p><code>combination()</code> returns an <code>int</code>, and in Python you cannot do "str + int" implicitly, so convert it to <code>str</code> explicitly:</p> <pre><code>answer = answer + str(combination(row, column)) + "\t" </code></pre> <p>You may also avoid string concatenation for with something along:</p> <pre><code>answer = '{ans} {comb} \t'.format(ans=answer, comb=combination(row, column)) </code></pre>
python|python-3.x|pascals-triangle
2
1,904,086
37,016,636
Python scipy Curve fit for quadratic function stopping early
<p>So my plotted line of best fit for a curve is cutting off at the second point and I for the life of me can't figure out why.</p> <pre><code>from matplotlib import pyplot as plt import numpy as np from scipy.optimize import curve_fit accuracy = 250 def quadratic_function(E,a,b,c): B = (a*(E**2.0)) + (b*E) + c return B Implantation_E = np.array([5.0,10.0,15.0,20.0,25.0]) plt.figure() plt.title("A plot showing how the Magnetic Field varies with Implantation Energy") plt.ylabel("Magnetic Field Strength (T)") plt.xlabel("Implantation Energy (J)") plt.plot(Implantation_E,D_array[0],'bo') parameters, var = curve_fit(quadratic_function,Implantation_E,D_array[0], absolute_sigma = True, p0 = (1.0,1.0,1.0)) newTime = np.linspace(0,10,accuracy) newAsymmetry = quadratic_function(newTime, *parameters) plt.plot(newTime, newAsymmetry) plt.show() </code></pre> <p>(Note D_array[0] : [ 0.00523265 0.00860683 0.0109838 0.01241191 0.01284149] )</p> <p><img src="https://i.stack.imgur.com/mWuCt.png" alt="Image of plotted graph"></p>
<p>Your original data range in their argument from 5 to 25. But your fit only goes to 10. Change the <code>newTime</code> definition to reach 25 and you are fine.</p> <pre><code>from matplotlib import pyplot as plt import numpy as np from scipy.optimize import curve_fit %matplotlib inline accuracy = 250 def quadratic_function(E,a,b,c): B = (a*(E**2.0)) + (b*E) + c return B dd= np.array([ 0.00523265, 0.00860683 ,0.0109838, 0.01241191 ,0.01284149]) Implantation_E = np.array([5.0,10.0,15.0,20.0,25.0]) plt.plot(Implantation_E,dd,'b-o',lw=15,ms=10,alpha=0.3) parameters, var = curve_fit(quadratic_function,Implantation_E,dd,absolute_sigma = True, p0 = (1.0,1.0,1.0)) newTime = np.linspace(0,10,accuracy) newAsymmetry = quadratic_function(newTime, *parameters) plt.plot(newTime, newAsymmetry,'r.',ms=1) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/hImkb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hImkb.png" alt="enter image description here"></a></p> <pre><code>... newTime = np.linspace(3,25,accuracy) ... </code></pre> <p><a href="https://i.stack.imgur.com/NUO3C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NUO3C.png" alt="enter image description here"></a></p>
python|numpy|matplotlib
0
1,904,087
36,854,277
How can I read four specific lines of a file without reading the whole file in python?
<p>I need to read 4 specific lines of a file in python. I don't want to read all the file and then get four out of it ( for the sake of menory). Does anyone know how to do that? Thanks!</p> <p>P. S. I used the following code but apparently it reads all the file and then take 4 out of it. </p> <pre><code>a=open("file", "r") b=a.readlines() [c:d] </code></pre>
<p>you have to read at least to the lines you are interested in ... you can use islice to grab a slice</p> <pre><code>interesting_lines = list(itertools.islice(a,c,d)) </code></pre> <p>but it still reads up to those lines</p>
python
2
1,904,088
20,306,608
Save a numpy array to csv with a string header
<p>I have a large-ish numpy array containing floats, which I save as a csv file with np.savetxt("myFile.csv", myArray, delimiter=",")</p> <p>Now, as the array has many columns and it can become hard to remember what is what, I want to add a string header to the array before exporting it. Since numpy doesn't accept strings in float arrays, is there a trick to accomplish this?</p> <p>[Solution] Thanks to Cyborg's advice, I managed to make this work installing Pandas.</p> <pre><code>import pandas as pd df = pd.DataFrame(A) # A is a numpy 2d array df.to_excel("A.xls", header=C,index=False) # C is a list of string corresponding to the title of each column of A </code></pre>
<p>The <code>header</code> argument (the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html">docs</a>):</p> <pre><code>numpy.savetxt(fname, X, delimiter=' ', header='') </code></pre> <p>But you may prefer <a href="http://pandas.pydata.org/">Pandas</a> if you are actually dealing with a table.</p>
arrays|numpy|header|pandas|export-to-csv
16
1,904,089
20,083,039
static files copied, css not being used
<p>It's a bit weird how paths look, but it's my first Django app, I'm learning :)</p> <p>setting.py</p> <pre><code>STATIC_ROOT = os.path.join(SITE_ROOT, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( ('assets', 'C:\Users\Szymon\Desktop\UploaderUpdate\Uploader\uploader\static'), ) </code></pre> <p>urls.py</p> <pre><code>urlpatterns += staticfiles_urlpatterns() </code></pre> <p>main.html (template)</p> <pre><code>{% load static %} &lt;link rel="stylesheet" href="{% static 'assets/css/style.css' %}"&gt; </code></pre> <p>Then in my cmd I do: <code>python manage.py collectstatic</code> And it says copies files. Now, I have my (I created it) static folder at:</p> <pre><code>C:\Users\Szymon\Desktop\UploaderUpdate\Uploader\uploader </code></pre> <p>Unfortunately main app is in folder <code>main</code> so it created folder <code>static</code> at :</p> <pre><code>C:\Users\Szymon\Desktop\UploaderUpdate\Uploader\uploader\uploader\static </code></pre> <p>It contains <code>assets</code> and <code>admin</code>. But my CSS is not being used, despite my import in the template. Am I linking it wrong?</p>
<p>Perhaps try</p> <pre><code>STATICFILES_DIRS = (os.path.join(SITE_ROOT,'static'))? </code></pre> <p>I don't know why the absolute path doesn't seem to work. However python manage.py collectstatic should have put all of your static files in the static directory defined by STATIC_ROOT, which uses SITE_ROOT (or BASE_DIR from <a href="https://docs.djangoproject.com/en/1.6/howto/static-files/" rel="nofollow">https://docs.djangoproject.com/en/1.6/howto/static-files/</a>. (I would avoid local absolute paths if you can, for one thing that gives you more work when you go into production.) Also does your SITE_ROOT look like this?</p> <pre><code>SITE_ROOT = os.path.dirname(os.path.abspath(__file__)) </code></pre> <p>I'm 99% sure this gives the absolute path of the directory your settings.py file is in, so if you use this, your static folder should be in the same directory as your settings file.</p>
python|css|django|static|django-staticfiles
0
1,904,090
51,541,754
How to change the thickness of the edge (contour) of an Image?
<p>I am trying to extract the edge of an image (its contour) and change its thickness. I want to give it like the stroke effect of Photoshop layer style. Photoshop stroke effect example: <a href="http://projectwoman.com/2012/11/smart-objects-and-strokes-in-photoshop.html" rel="nofollow noreferrer">http://projectwoman.com/2012/11/smart-objects-and-strokes-in-photoshop.html</a></p> <p>I was able to extract the edge from an image. Using <code>canny edge</code> or the <code>pillow</code> function.</p> <p>1.using canny edge detection</p> <pre><code>img = cv2.imread(img_path,0) edges = cv2.Canny(img,300,700) </code></pre> <p>2.using pillow filler</p> <pre><code>image = Image.open(img_path).convert('RGB') image = image.filter(ImageFilter.FIND_EDGES()) </code></pre> <p>but, I could not adjust the contour thickness.</p>
<p>Here a solution:</p> <pre><code>import cv2 import matplotlib import numpy as np import matplotlib.pyplot as plt image = cv2.imread('mickey.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB)[...,0] def show_img(im, figsize=None, ax=None, alpha=None): if not ax: fig,ax = plt.subplots(figsize=figsize) ax.imshow(im, alpha=alpha) ax.set_axis_off() return ax def getBordered(image, width): bg = np.zeros(image.shape) _, contours, _ = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) biggest = 0 bigcontour = None for contour in contours: area = cv2.contourArea(contour) if area &gt; biggest: biggest = area bigcontour = contour return cv2.drawContours(bg, [bigcontour], 0, (255, 255, 255), width).astype(bool) im2 = getBordered(image, 10) show_img(im2, figsize=(10,10)) </code></pre> <p><a href="https://i.stack.imgur.com/TLx01.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TLx01.png" alt="enter image description here"></a></p> <p>You can change thickness by changing param width in <code>getBordered</code>.</p>
python|image|opencv|edge-detection
2
1,904,091
51,509,125
How to serve different web apps using one domain name in Apache?
<p>I'm currently trying to deploy my Django 2.0 App on an Apache Web Server. However I'm experiencing difficulties in configuring it because my Virtual Host configuration overrides other Virtual Hosts which is used by other projects (Ruby and PHP WebApps). We only have one domain name at the moment so I cannot use other domain names to host my app.</p> <p>Is it possible to serve different kind of apps with one domain name using Apache Virtual Hosts?</p>
<p>Since you can only have 1 VirtualHost (one domain, one port, one IP), you cannot create additionnal VH. You need to "split" the paths to the different applications some other way.</p> <p>Let assume www.example.com:</p> <pre><code>ServerRoot "/some/path/apache" [...] OTHER LoadModule directives [...] LoadModule alias_module modules/mod_alias.so Listen *:80 &lt;VirtualHost *:80&gt; ServerName www.example.com ServerAlias example.com # Logs LogLevel warn CustomLog "logs/www.example.com_access-log" combined ErrorLog "logs/www.example.com_error-log" # Index file. Add as many as required for your applications &lt;IfModule dir_module&gt; DirectoryIndex index.html &lt;/IfModule&gt; # Where the documents are DocumentRoot "/some/path/apache/htdocs" &lt;Directory /&gt; Options FollowSymLinks AllowOverride None Order deny,allow Deny from all &lt;/Directory&gt; &lt;Directory "/some/path/apache/htdocs"&gt; Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>This VirtualHost is a basic configuration for the www.example.com domain. Now you want to have Ruby, PHP WebApps and Django 2.0 App under that single domain. You have 3 choices:</p> <ol> <li>Get 1 domain per application, not applicable here, that is your question.</li> <li>Make a sub-directory in htdocs, and a path in the URI for each application.</li> <li>Put each application in some directory, not under <code>DocumentRoot</code> and use <code>Alias</code>.</li> <li>Use sub-domains.</li> </ol> <hr> <ol> <li>Not applicable.</li> </ol> <hr> <ol start="2"> <li>Sub-directory and path</li> </ol> <p>Create <code>/some/path/apache/htdocs/Ruby</code>, put your Ruby app. here.<br> Will be accessed via <code>http://www.example.com/Ruby</code></p> <p>Create <code>/some/path/apache/htdocs/PHPWebApps</code>, put your PHP app. here.<br> Will be accessed via <code>http://www.example.com/PHPWebApps</code></p> <p>Create <code>/some/path/apache/htdocs/Django</code>, put your Django app. here.<br> Will be accessed via <code>http://www.example.com/Django</code></p> <p>The URI value must match the directory value.</p> <hr> <ol start="3"> <li>In some directory, use <code>Alias</code></li> </ol> <p>If you do not need, or want the URI to match the directory name (like in 2.), use Alias.</p> <p>Create <code>/SOME_DIR_FOR_Ruby</code>, put your Ruby app. here.<br> Add <code>Alias "/Ruby" "/SOME-DIR-FOR-Ruby"</code><br> Will be accessed via <code>http://www.example.com/Ruby</code></p> <p>Create <code>/SOME_DIR_FOR_PHPWebApps</code>, put your PHP app. here.<br> Add <code>Alias "/PHPWebApps" "/SOME_DIR_FOR_PHPWebApps"</code><br> Will be accessed via <code>http://www.example.com/PHPWebApps</code></p> <p>Create <code>/SOME_DIR_FOR_Django</code>, put your Django app. here.<br> Add <code>Alias "/Django" "/SOME_DIR_FOR_Django"</code><br> Will be accessed via <code>http://www.example.com/Django</code></p> <hr> <ol start="4"> <li>Use sub-domains</li> </ol> <p>This is where you could use multiple VirtualHosts. But you have to be able to create sub-domains. This is done either via a DNS configuration, or through your hosting provider.</p> <p>You could setup <a href="http://ruby.example.com" rel="nofollow noreferrer">http://ruby.example.com</a>, <a href="http://php.example.com" rel="nofollow noreferrer">http://php.example.com</a>, <a href="http://django.example.com" rel="nofollow noreferrer">http://django.example.com</a>. Each of these will have 1 VirtualHost, but will all be mapped to the same IP in the DNS.</p> <p>Then setup 3 VH:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName ruby.example.com # Logs LogLevel warn CustomLog "logs/ruby.example.com_access-log" combined ErrorLog "logs/ruby.example.com_error-log" # Index file. Add as many as required for your applications &lt;IfModule dir_module&gt; DirectoryIndex index.html &lt;/IfModule&gt; # Where the documents are DocumentRoot "/some/path/apache/htdocs/Ruby" &lt;Directory /&gt; Options FollowSymLinks AllowOverride None Order deny,allow Deny from all &lt;/Directory&gt; &lt;Directory "/some/path/apache/htdocs/Ruby"&gt; Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; &lt;VirtualHost *:80&gt; ServerName php.example.com # Logs LogLevel warn CustomLog "logs/php.example.com_access-log" combined ErrorLog "logs/php.example.com_error-log" # Index file. Add as many as required for your applications &lt;IfModule dir_module&gt; DirectoryIndex index.html &lt;/IfModule&gt; # Where the documents are DocumentRoot "/some/path/apache/htdocs/php" &lt;Directory /&gt; Options FollowSymLinks AllowOverride None Order deny,allow Deny from all &lt;/Directory&gt; &lt;Directory "/some/path/apache/htdocs/php"&gt; Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; &lt;VirtualHost *:80&gt; ServerName django.example.com # Logs LogLevel warn CustomLog "logs/django.example.com_access-log" combined ErrorLog "logs/django.example.com_error-log" # Index file. Add as many as required for your applications &lt;IfModule dir_module&gt; DirectoryIndex index.html &lt;/IfModule&gt; # Where the documents are DocumentRoot "/some/path/apache/htdocs/django" &lt;Directory /&gt; Options FollowSymLinks AllowOverride None Order deny,allow Deny from all &lt;/Directory&gt; &lt;Directory "/some/path/apache/htdocs/django"&gt; Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>On Apache 2.2, you have to add <code>NameVirtualHost *:80</code>, in Apache 2.4, nothing, it is always "on".</p> <p>All these values can be changed as you like, this is just an example to explain the concept.</p>
ruby|django|python-3.x|apache|virtualhost
1
1,904,092
51,352,515
Tkinter Listbox - How to disable arrow key selection?
<p>I have a Python 3.7 tkinter GUI, and within the GUI I have implemented up-down arrow key controls for the main part of the application. Next to it I have a list box that also controls the application but in a different way, and by default AFTER a listbox selection has been made the listbox selection will scroll with up and down arrows. So, after I've used the list box in the app, the arrow key triggers an up arrow event in both the main part of the application and in the list box. This triggers my application to respond in the change in list box selection by loading new data into the main app. This is obviously unacceptable.</p> <p>How can I disable the arrow key controls feature of tkinter's ListBox?</p> <p>I've tried configuring the listbox to not take focus, but this doesn't seem to disable the feature.</p> <p>Edit:</p> <p>I solved this by binding the list box's FocusIn event to a function that immediately focus's something else. This is far from ideal, as the code now focus's in then changes focus for no reason. If there is a way to disable focus on a widget completely or disable the list box key bindings that would be a preferred solution.</p> <pre><code>from tkinter import * class App: def __init__(self): self.root = Tk() self.dummy_widget = Label() self.lb = ListBox(master=self.root) self.lb.bind("&lt;FocusIn&gt;", lambda event: self.dummy_widget.focus()) # Additional setup and packing widgets... if __name__ == '__main__': mainloop() </code></pre> <p>This seems very "hacky", although it does the job perfectly.</p>
<blockquote> <p>How can I disable the arrow key controls feature of tkinter's ListBox?</p> </blockquote> <p>Create your own bindings for the events you want to override, in the widget in which you want them overridden. Do anything you want in that function (including nothing), and then return the string <code>break</code>, which is the documented way to prevent events from being processed any further.</p> <p>For a more extensive description of how bindings work, see <a href="https://stackoverflow.com/questions/11541262/basic-query-regarding-bindtags-in-tkinter/11542200#11542200">this answer</a> to the question <a href="https://stackoverflow.com/questions/11541262/basic-query-regarding-bindtags-in-tkinter">Basic query regarding bindtags in tkinter</a>. It describes how a character is inserted into an entry widget, but the mechanism is identical for all events and widgets in tkinter.</p>
python|python-3.x|tkinter
1
1,904,093
73,806,066
reading csv files with specific name in python
<p>I have some csv files with name pattern below</p> <p>IU_2022-09-01T09_43_56_<strong>0100</strong>-0018-0000-0002</p> <p>Bold part of the name is important and i want to create different data frames if that changes but i am not able to read csv files by specifying something in the middle of the name. i want to read only those csv files which has 0100 in their names. i used glob method</p> <pre><code>ls_data = list() </code></pre> <p>for idx, f in glob.glob('[0100]*.csv'):</p> <p>df_temp = pd.read_csv(f, delimiter=';')</p> <p>df_temp[&quot;layer_number&quot;] = idx</p> <p>ls_data.append(df_temp)</p> <p>print (idx)</p> <p>df_L = pd.concat(ls_data, axis=0)</p> <p>`</p> <p>but i am getting empty data</p>
<p>Use <a href="https://docs.python.org/3/library/pathlib.html" rel="nofollow noreferrer"><strong><code>pathlib</code></strong></a> :</p> <pre><code>from pathlib import Path import pandas as pd ls_data = [] csv_directory = r'/path/to/csvfiles/' for idx, filename in enumerate(Path(csv_directory).glob('*_0100-*.csv')): df_temp = pd.read_csv(filename, delimiter=';') df_temp.insert(0, 'layer_number', idx) ls_data.append(df_temp) df = pd.concat(ls_data, axis=0) </code></pre>
python|pandas
0
1,904,094
17,553,802
Manipulating a string to create even chunks of three
<p>I am new to Python, and this is probably a very simple question, but I am having trouble figuring it out. I have some raw input that I need to convert. The input is a body of text such as <code>'ABCDEFGHIJKLMNO'</code> but in order for me to continue, I need to convert this into a string such as <code>'ABC DEF GHI JKL MNO'</code>.</p>
<pre><code>&gt;&gt;&gt; s = 'ABCDEFGHIJKLMNO' &gt;&gt;&gt; ' '.join([s[i:i+3] for i in xrange(0, len(s), 3)]) 'ABC DEF GHI JKL MNO' </code></pre>
python|string|input
6
1,904,095
59,891,939
How to compile a python script to an executable?
<p>I know a way to do this is using pyinstaller, however, after some <a href="https://reverseengineering.stackexchange.com/questions/160/how-do-you-reverse-engineer-an-exe-compiled-with-pyinstaller">research</a>, I found out that a pyinstaller exe can be reverse engineered to get the original python script.</p> <p>Do you know a way to compile a python script into an executable which can be shared with anyone ,even if they <strong>don't have</strong> the dependencies I used, or python, installed, and <strong>can not</strong> be reverse engineered?</p>
<p>I found two other threads talking about this, maybe you would like them:</p> <blockquote> <p><a href="https://stackoverflow.com/questions/20297725/how-to-make-an-encrypted-executable-file">How to make an encrypted executable file</a></p> <p><a href="https://www.quora.com/How-can-I-protect-my-Python-code-but-still-make-it-available-to-run" rel="nofollow noreferrer">https://www.quora.com/How-can-I-protect-my-Python-code-but-still-make-it-available-to-run</a></p> </blockquote>
python|compilation|exe
0
1,904,096
71,090,873
How to webscrape with Python keeping meta-information in the text?
<p>I am trying to webscrape this <a href="https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html" rel="nofollow noreferrer">website</a>. To do so, I run the following code:</p> <pre><code>from bs4 import BeautifulSoup import requests url = &quot;https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html&quot; soup = BeautifulSoup(requests.get(url).content) data = [] for link in soup.select('div.title &gt; a'): soup = BeautifulSoup(requests.get(f&quot;https://www.ecb.europa.eu{link['href']}&quot;).content) data.append({ 'text':' '.join([p.text for p in soup.select('main .section p:not([class])')]) }) print(data) </code></pre> <p>This works fine. What is the issue? The problem is that the webscraped text comes without information on paragraphs split and on bold character. This is a problem since I would then need to make some calls on the basis of that.</p> <p>Can anyone suggest how to maintain meta-information in the text?</p> <p>Thanks a lot!</p>
<p>A solution is to determine in the website code source what are the markers for paragraphs split and bold characters.</p> <p>Then, the &quot;soup&quot; variable, you can localize what interests you using the markers as a string to be searched in &quot;soup&quot;.</p> <p>Looking briefly at the source code of your website, I think the answer relies in following markers (I needed to add ' otherwise the markers are hidden by stackoverflow):</p> <blockquote> <p>&quot;&lt;'/a&gt;&lt;'/div&gt;&lt;'div class=&quot;subtitle&quot;&gt;&quot;</p> </blockquote>
python|web-scraping
1
1,904,097
57,355,649
Is this a valid way to get switch case like functionality in python?
<p>I am doing something like this and it works but I am not sure if it is the right way to do it. When there is an exception in one of the case methods the trace stops at the line containing <code>}["case1"]("name")</code>. But the reason for the error is correct like if I was expecting a dict and passed a list I will get a list is unhashable exception but on <code>}["case1"]("name")</code> not in the method where that is happening it will stop the traceback here. So if this goes a few levels deep debugging it can become... tricky.</p> <pre><code>def test(what, data): def case1(data): # do something with data result = "Hello " + data return result def case2(data): # do something with data result = "bye " + foo return result res = { "case1": case1, "case2": case2 }[what](data) print(res) test("case1", "Foo") </code></pre>
<p>Separate the dict definition and the call, and you'll be fine:</p> <pre><code>def test(what, data): def case1(data): # do something with data result = "Hello " + data return result def case2(data): # do something with data result = "bye " + foo return result res = { "case1": case1, "case2": case2 } print(res[what](data)) test("case1", "Foo") </code></pre>
python-3.x|switch-statement
1
1,904,098
51,858,833
how to set key arg for sorted() when using strftime to form file path
<p>I am on Windows and trying to find the most recent file in a certain folder. Here is the folder name, <code>C:\ResultsUpload\Nmap</code>. I will have files in this folder resembling the following format <code>C:\ResultsUpload\Nmap\scan-&lt;some hostname&gt;-%Y%m%d%H%M.xml</code>. </p> <p>Here are two examples, <code>scan-localhost-201808150818.xml</code> and <code>scan-scanme.nmap.org-201808150746.xml</code></p> <p>I have the following code, </p> <pre><code>logdir = r'C:\ResultsUpload\Nmap' logfiles = sorted([f for f in os.listdir(logdir) if f.startswith('scan')]) print logfiles print "Most recent file = %s" % (logfiles[-1],) </code></pre> <p>Printing logfiles shows as <code>['scan-localhost-201808150818.xml', 'scan-scanme.nmap.org-201808150746.xml']</code> </p> <p>Even though the file with localhost as the hostname was more recent, the scanme.nmap.org file is in the [-1] position. I believe this is due to alphabetical sorting. So my sorting is wrong here and I believe I need the sorting key parameter like so </p> <p><code>logfiles = sorted([f for f in os.listdir(logdir) if f.startswith('scan')], key= &lt;somethin&gt;)</code></p> <p>I'm just not sure how to say that the key is the strftime format or how to adjust the startswith() arg to account for different host names. Would anyone be able to assist? </p>
<p>You can give the <code>key</code> parameter a <code>lambda</code> which will extract the <code>timestamp</code> from the entry.</p> <p>By default, the sorting is in natural sorting. You can do a reverse sorting by giving <code>reverse=True</code></p> <pre><code>&gt;&gt;&gt; l= ["scan-localhost-201808150818.xml","scan-scanme.nmap.org-201808150746.xml"] &gt;&gt;&gt; &gt;&gt;&gt; sorted(l, key = lambda x: x.rsplit('-')[-1].split(".")[0] , reverse = True) ['scan-localhost-201808150818.xml', 'scan-scanme.nmap.org-201808150746.xml'] &gt;&gt;&gt; </code></pre>
python|sorting|strftime
2
1,904,099
52,798,964
I need to count Images with a specific value for "src" in a web page and populate a input field and submit page using script automatically
<p>Assume any web page with a Form and having a set of images. I need to populate the input text value on page load and submit.</p> <pre><code>var imgs = document.getElementsByTagName('img'); var countImagesFilled = 0; var curImg; for(var i = 0; i &lt; imgs .length; i++) { curImg = imgs[i]; if(curImg.getAttribute('src')=='abc.png'){++countImagesFilled;} } var inputValue = document.getElementsByName('valuee'); inputValue[0].value=countImagesFilled; document.forms[0].submit(); </code></pre>
<p>Checkout this <a href="https://codepen.io/RaysOfTheSun/pen/zmEoYw?editors=1111" rel="nofollow noreferrer">working example</a> :)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = ()=&gt;{ // get our form let imageForm = document.getElementById('image-form'); // something to inform us that the form has been submitted imageForm.addEventListener('submit', function(){ console.log(`form data: ${$(this).serialize()}`); }); // get all the img elements let images = document.querySelectorAll('img'); // get the input field where we'll be putting the total image count let field = document.getElementById('image-count'); // the number of images that match our criteria let imageCount = 0; // count the number of img elements that have 'test.png' as their source for(let i = 0; i &lt; images.length; i++){ if(images[i].getAttribute('src') === 'test.png'){ imageCount++; } } // set the image count (imageCount) as the value of the text field field.value = imageCount; // submit the form imageForm.dispatchEvent(new Event('submit')); };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;form id="image-form" name="imageCount"&gt; &lt;img src="test.png" class="img-1"&gt; &lt;img src="test.png" class="img-1"&gt; &lt;img src="test.png" class="img-1"&gt; &lt;img src="test.png" class="img-1"&gt; &lt;img src="test.png" class="img-1"&gt; &lt;img src="test.png" class="img-1"&gt; &lt;img src="test.png" class="img-1"&gt; &lt;img src="exclude.png" class="img-2"&gt; &lt;img src="exclude.png" class="img-2"&gt; &lt;img src="exclude.png" class="img-2"&gt; &lt;img src="exclude.png" class="img-2"&gt; &lt;img src="exclude.png" class="img-2"&gt; &lt;input type="text" id="image-count" name="imageWithSourceCount"&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>One more thing, given the following HTML:</p> <pre><code>&lt;img src="images/test.png" class="img-1"&gt; </code></pre> <p>if you read the <strong>src</strong> property of the image object (<code>img.src</code>), you will get the resolved path which will be something like <code>yourwebsite.com/images/test.png</code>. But, if you retrieve it using <strong>getAttribute</strong> (<code>img.getAttribute('src')</code>), you will get the actual value of the <code>src</code> attribute which may also be a relative path (i.e. <code>images/test.png</code>)</p>
javascript|python|web-scraping|vbscript|scripting
2