Unnamed: 0
int64 0
1.91M
| id
int64 337
73.8M
| title
stringlengths 10
150
| question
stringlengths 21
64.2k
| answer
stringlengths 19
59.4k
| tags
stringlengths 5
112
| score
int64 -10
17.3k
|
---|---|---|---|---|---|---|
1,907,300 | 45,974,223 |
Static files not working in Iframe in production mode django
|
<p>In production mode my django project1 working fine.</p>
<p>settings.py</p>
<pre><code>DEBUG = False
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR,'mysite' ,'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'mysite', "static"),
'/var/www/static/',
]
</code></pre>
<p>I ran this project in localhost:8000 </p>
<p>And my different project(project2) which is running into localhost:8001 </p>
<p>I want to show project1's home page in project2 using iframe or embed
but project1's static files not working here.</p>
|
<p>try with:</p>
<pre><code>STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
'/var/www/static/',
)
</code></pre>
<p>and set debug to true, if you set debug to false then run <code>manage.py --insecure</code>. The reason: If you set debug to true then you server will take care the staticfiles and not the Django server</p>
|
python|django|django-cms|django-staticfiles
| 0 |
1,907,301 | 45,969,711 |
Sphinx Doc - How do I render an animated GIF when building for HTML but a PNG when building for latexpdf?
|
<p>As title states, I'm using sphinx-doc and I really want to conditionally render static PNGs when the build output is latexpdf and animated GIFs when built for the web.</p>
<p>Ideally, it would be nice to be able to do this in the rst file itself somehow... semantically a:</p>
<p>if builder == html:
.. image: blah blah
elif builder == latexpdf:
.. image: blah blah</p>
|
<p>From the <a href="http://www.sphinx-doc.org/en/stable/rest.html#images" rel="noreferrer">Sphinx documentation for images</a>:</p>
<blockquote>
<p>Sphinx extends the standard docutils behavior by allowing an asterisk for the extension:</p>
<pre><code>.. image:: gnu.*
</code></pre>
<p>Sphinx then searches for all images matching the provided pattern and determines their type. Each builder then chooses the best image out of these candidates. For instance, if the file name <code>gnu.*</code> was given and two files <code>gnu.pdf</code> and <code>gnu.png</code> existed in the source tree, the LaTeX builder would choose the former, while the HTML builder would prefer the latter. Supported image types and choosing priority are defined at <a href="http://www.sphinx-doc.org/en/stable/builders.html#builders" rel="noreferrer">Available builders</a>.</p>
</blockquote>
<p>To customize the "best image" order for a given builder, edit your <code>conf.py</code> to override the <code>StandaloneHTMLBuilder</code> class with the <code>supported_image_types</code> order you prefer.</p>
<pre><code>from sphinx.builders.html import StandaloneHTMLBuilder
StandaloneHTMLBuilder.supported_image_types = [
'image/svg+xml',
'image/gif',
'image/png',
'image/jpeg'
]
</code></pre>
|
python-sphinx|restructuredtext
| 7 |
1,907,302 | 54,798,571 |
ImportError: Install keras_contrib in order to use instance normalization
|
<p>ImportError: Install keras_contrib in order to use instance normalization. This is the error message:</p>
<p><img src="https://i.stack.imgur.com/TRmEF.png" alt="enter image description here" /></p>
<p>I went to the website that suggested and I get this:</p>
<p><img src="https://i.stack.imgur.com/V8fTa.png" alt="enter image description here" /></p>
<p>Then I ran the code again and got the same error like in image 1</p>
|
<p>from keras_contrib.layers.normalization.instancenormalization import InstanceNormalization</p>
|
python
| 0 |
1,907,303 | 12,910,253 |
Inheriting doc strings in Python + preview in IDE
|
<p>I am currently spending some time writing a wrapper for matplotlib for easier creation of plots for publications etc. </p>
<p>Currently I am using Spyder as IDE and I really like the Object Inspector feature which provides live documentation for the objects you are working with. </p>
<p>Anyways, part of my API only forwards calls to a matplotlib function and it would therefore be very handy to inherit the documentation from those. </p>
<p>Writing <code>myfunction.__doc__ = matplotlibfunction.__doc__</code> seems to work if I print <code>__doc__</code> to the console, but the Object Inspector in Spyder does not show the documentation, do anyone have a good suggestion as to why, and what I could do to get the intended behavior?</p>
|
<p>Greg, are you trying to view <code>myfuncion</code> docstring from the Editor? The thing is Spyder relies on the <a href="http://rope.sourceforge.net/" rel="nofollow">rope</a> library to do docstring inspection on the Editor, which unfortunately has several shortcomings we'll try to fix on the 2.2 version.</p>
|
python|spyder
| 3 |
1,907,304 | 12,994,217 |
Python 3.x IndexError while using nested For loops
|
<p>So I've been trying to code a tabletop game that I made a long time ago - I'm working on the graphic section now, and I'm trying to draw the 9x7 tile map using nested For loops:</p>
<p>I'm using the numpy library for my 2d array</p>
<pre><code>gameboard = array( [[8, 8, 8, 7, 7, 7, 8, 8, 8],
[8, 3, 6, 7, 7, 7, 6, 3, 8],
[0, 1, 1, 6, 6, 6, 1, 1, 0],
[0, 5, 4, 0, 0, 0, 4, 5, 0],
[0, 3, 2, 0, 0, 0, 2, 3, 0],
[8, 8, 1, 0, 0, 0, 1, 8, 8],
[8, 8, 8, 6, 6, 6, 8, 8, 8]] )
def mapdraw():
for x in [0, 1, 2, 3, 4, 5, 6, 7, 8]:
for y in [0, 1, 2, 3, 4, 5, 6]:
if gameboard[(x, y)] == 1:
#insert tile 1 at location
elif gameboard[(x, y)] == 2:
#insert tile 2 at location
elif gameboard[(x, y)] == 3:
#insert tile 3 at location
#this continues for all 8 tiles
#graphics update
</code></pre>
<p>When I run this program, i get an error on the line "if gameboard[(x,y)] == 1:"
"IndexError: index (7) out of range (0<=index<7) in dimension 0"</p>
<p>I've looked for hours to find what this error even means, and have tried many different ways to fix it: any help would be appreciated.</p>
|
<p>You have to index the array using <code>[y,x]</code> because the first coordinate is the row index (which, for you, is the <code>y</code> index).</p>
<p>As an aside, <em>please</em> iterate over a <code>range</code> instead of an explicit list!</p>
<pre><code>for x in range(9):
for y in range(7):
if gameboard[y, x] == 1:
#insert tile 1 at location
...
</code></pre>
|
arrays|for-loop|numpy|python-3.x|2d
| 2 |
1,907,305 | 12,844,919 |
Sum of all numbers
|
<p>I need to write a function that calculates the sum of all numbers n.</p>
<pre><code>Row 1: 1
Row 2: 2 3
Row 3: 4 5 6
Row 4: 7 8 9 10
Row 5: 11 12 13 14 15
Row 6: 16 17 18 19 20 21
</code></pre>
<p>It helps to imagine the above rows as a 'number triangle.' The function should take a number, n, which denotes how many numbers as well as which row to use. Row 5's sum is 65. How would I get my function to do this computation for any n-value?</p>
<p>For clarity's sake, this is not homework. It was on a recent midterm and needless to say, I was stumped.</p>
|
<p>The leftmost number in column 5 is <code>11 = (4+3+2+1)+1</code> which is <code>sum(range(5))+1</code>. This is generally true for any <code>n</code>.</p>
<p>So: </p>
<pre><code>def triangle_sum(n):
start = sum(range(n))+1
return sum(range(start,start+n))
</code></pre>
<hr>
<p>As noted by a bunch of people, you can express <code>sum(range(n))</code> analytically as <code>n*(n-1)//2</code> so this could be done even slightly more elegantly by:</p>
<pre><code>def triangle_sum(n):
start = n*(n-1)//2+1
return sum(range(start,start+n))
</code></pre>
|
python
| 14 |
1,907,306 | 21,640,319 |
Dijkstra's Algorithm printing too much
|
<p>So I have this code here, which take a graph and then prints the shortest distance between two points chosen. The input for it is python filename.py start end map.txt
It works great with graphs I've given it such as this one:</p>
<pre><code>{'a': {'b': 5, 'c': 8},
'b': {'a': 5, 'd': 6},
'c': {'a': 8, 'd': 2},
'd': {'b': 6, 'c': 2, 'e': 12, 'f': 2},
'e': {'d': 12, 'g': 3},
'f': {'d': 2, 'g': 7},
'g': {'e': 3, 'f':7}}
</code></pre>
<p>The only problem is that when it prints output in the Command, it prints it like this:<br>
Distance from start to end is (distance , [start,end])
I can't figure out how tot make it just print the distance without any of the parentheses or the start and end point. Any help is appreciated.<br>
"""
Winter 2014
Authors: Cole Charbonneau & Peter Pham
Credit: <a href="https://stackoverflow.com/questions/21628503/python-importing-a-graph?noredirect=1">Python: Importing a graph</a>
Stackoverflow for helping us figure out how to import a graph via sys.argv</p>
<pre><code> Finds the shortest path between two points in a dictionary graph.
Uses a single-source shortest distance approach, nearly identical to
Dijkstra's Algortihm.
Takes input in the format: python filename.py start end grap.txt
"""
import sys
def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
"""Finds the shortest path between a start and end point from a graph"""
if start==end:
path=[] ##If the starting point is the end point, then we're done
while end != None:
path.append(end)
end=predecessors.get(end,None)
return distances[start], path[::-1]
##Check if it's the first time through it, and set current distance to 0
if not visited: distances[start]=0
##Runs through each adjacent point, and keeps track of the preceeding ones
for neighbor in graph[start]:
if neighbor not in visited:
neighbordist = distances.get(neighbor,sys.maxsize)
tentativedist = distances[start] + graph[start][neighbor]
if tentativedist < neighbordist:
distances[neighbor] = tentativedist
predecessors[neighbor]=start
##Now that all of the adjacent points are visited, we can mark the current point as visited
visited.append(start)
##This finds the next closest unvisited point to start on
unvisiteds = dict((k, distances.get(k,sys.maxsize)) for k in graph if k not in visited)
closestvertex = min(unvisiteds, key=unvisiteds.get)
##Recurses that closest point making it the current one
return shortestpath(graph,closestvertex,end,visited,distances,predecessors)
if __name__ == "__main__":
start = sys.argv[1]
end = sys.argv[2]
graph = eval(open(sys.argv[3],'r').read())
if len(sys.argv) != 4:
print('Input syntax: python filename.py start end map.py')
else:
print('Distance from ',start,' to ',end,' is ',shortestpath(graph,start,end))
"""
Result:
(20, ['a', 'y', 'w', 'b'])
"""
</code></pre>
|
<p>The function is returning a <a href="http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">tuple</a>, so you need to either access the first element in the tuple</p>
<pre><code>length = shortestpath(graph,start,end)[0]
</code></pre>
<p>or unpack it:</p>
<pre><code>length, path = shortestpath(graph,start,end)
</code></pre>
|
python|printing|dijkstra|sys
| 0 |
1,907,307 | 21,532,916 |
Error in linked lists function in python
|
<p>I have to Convert a number into linked list such that each digit is in a node and pointing to node having next digit.The function should return head of the linked list. e.g input 120 should create a list of Nodes 1 -> 2 -> 0 and return the reference.If it is a negative number say -120 it should return -1->-2->0.I tried to do it in this way:</p>
<pre><code>def number_to_list(number):
head,tail = None,None
for x in str(number):
if x<0:
x = -int(x)
node = Node(int(x))
else:
node = Node(int(x))
if head:
tail.next = node
else:
head = node
tail = node
return head
pass
</code></pre>
<p>It is working fine for positive numbers but if I pass -120.It is showing an error:</p>
<pre><code>ValueError: invalid literal for int() with base 10: '-'.
</code></pre>
<p>How can I fix it.</p>
|
<p>The problem is you are iterating over a string</p>
<pre><code>for x in string(number):
</code></pre>
<p>Makes x a character, which iterates over the string number. Now when you have a positive number, each digit in the number can be converted to an int. But when you pass a negative number, x takes the value of '-' which cannot be converted to an integer. There you get the error. By what I see, I think you are storing the absolute values of the digits of the numbers in the list. This can be done by checking if the character is '-', where you can just give a <code>pass</code> to do nothing in this iteration.</p>
<pre><code>if x=='-':
continue
</code></pre>
|
python
| 1 |
1,907,308 | 24,545,302 |
django form wizard: global name 'request' is not defined in done() method
|
<p>I am using django form wizard, which requires a done method as such.</p>
<pre><code>def done(self, form_list, **kwargs):
#Making an instance of Location
location = Location(
manager = User.objects.get(username=request.user.username)
#more stuff
)
</code></pre>
<p>Except I am getting the following error:</p>
<pre><code>global name 'request' is not defined on line (the line with manager assignment)
</code></pre>
<p>Not really sure what I could do to solve this problem. Should I just insert request into the done method? would that even make sense? How do other people handle this?</p>
|
<p>You can refer the <code>request</code> as <code>self.request</code> in class based views and form wizard.
Update your line to </p>
<pre><code>location = Location( #-------v
manager = User.objects.get(username=self.request.user.username)
#more stuff
)
</code></pre>
|
python|django|django-forms|django-formwizard|formwizard
| 4 |
1,907,309 | 40,819,487 |
Crontab issue, even when I have the file in the directory is says "No such file or directory"
|
<p>Even when I have the file in the directory is says "No such file or directory" How do I fix this?</p>
<p>I'm using <code>crontab -e</code> to add tho crontab.</p>
<p>Crontab;</p>
<pre><code>MAILTO=""
*/1 * * * * /home/TwitterFollowBot/bot.py 2>/tmp/twitterBot.log
</code></pre>
<p>Bot.py</p>
<pre><code>#!/usr/bin/env python
from TwitterFollowBot import TwitterBot
my_bot = TwitterBot()
from TwitterFollowBot import TwitterBot
my_bot = TwitterBot("config.txt")
from TwitterFollowBot import TwitterBot
my_bot = TwitterBot()
my_bot.sync_follows()
from TwitterFollowBot import TwitterBot
my_bot = TwitterBot()
my_bot.auto_rt("@ShoutGamers", count=2200)
</code></pre>
<p>Path;</p>
<pre><code>/home/TwitterFollowBot/bot.py
</code></pre>
<p>Crontab log;</p>
<pre><code>Traceback (most recent call last):
File "/home/TwitterFollowBot/bot.py", line 5, in <module>
my_bot = TwitterBot()
File "/home/TwitterFollowBot/TwitterFollowBot/__init__.py", line 42, in __init__
self.bot_setup(config_file)
File "/home/TwitterFollowBot/TwitterFollowBot/__init__.py", line 78, in bot_setup
with open(config_file, "r") as in_file:
IOError: [Errno 2] No such file or directory: 'config.txt'
</code></pre>
|
<p>Crontab doesn't run your code in the directory its in, as it just runs the command you've put in from whatever location its configured to (probably your home directory).</p>
<p>You can solve that by getting the path of your file via <code>sys.argv</code>:</p>
<pre><code>#!/usr/bin/env python
import sys
import os.path
from TwitterFollowBot import TwitterBot
path = sys.argv[0].rsplit("/", 1)[0]
TwitterBot() # I don't know if this does something, but as the assigned value is never used...
TwitterBot(os.path.join(path, "config.txt")) # Same here. I put the path in front of "config.txt"
TwitterBot().sync_follows()
TwitterBot().auto_rt("@ShoutGamers", count=2200)
</code></pre>
|
python|crontab
| 0 |
1,907,310 | 38,426,390 |
Python __get__ differences between static instance and member
|
<p>I'm having trouble understanding what is going on to make a difference in static object and member objects (those created in constructor).</p>
<p>The following will run the overridden <strong>get</strong>():</p>
<pre><code>class A(object):
class B(object):
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print('B Retrieving', self.name)
return self.val
b = B(10, 'var "b"')
</code></pre>
<p>But, if I pull b in to the constructor it does not:</p>
<pre><code>class A(object):
class B(object):
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print('B Retrieving', self.name)
return self.val
def __init__(self)):
self.b = A.B(10, 'var "b"')
</code></pre>
<p>I really want to make this work in the latter and maybe this isn't the right way to do it. </p>
<p>Can someone please explain what is going on here in a call to <code>print(a.b)</code> where <code>a = A()</code>?</p>
<p>Also, is there a way to have <code>print(a.b)</code> call a member function from b?</p>
|
<p>By implementing <code>__get__</code>, you turned your class <code>B</code> into a <a href="https://stackoverflow.com/questions/3798835/understanding-get-and-set-and-python-descriptors">descriptor class</a>. Descriptors are objects that take care of attribute access by performing custom logic on an instance.</p>
<p>In order to make descriptors work, you need to declare them as members on the type. Only then will Python call <code>__get__</code> and <code>__set__</code> methods of the object properly.</p>
<p>The reason why doing <code>self.b = SomeDescriptor()</code> does not work is because by assinging something to <code>self.b</code>, you are directly changing the object’s underlying <code>__dict__</code>:</p>
<pre><code>>>> class A(object): pass
>>> x = A()
>>> x.b = B(10, '')
>>> x.__dict__
{'b': <__main__.B object at 0x000000437141F208>}
</code></pre>
<p>As you can see <code>x.b</code> has the value of that <code>B</code> object. That is the descriptor object. And when you just try to access <code>x.b</code>, you just get that descriptor object back. The <code>__get__</code> is never called.</p>
<p>When you set the descriptor on the type however, a member <code>b</code> does not exist in the object’s <code>__dict__</code>, so Python will look further up in the inheritance chain and will find the descriptor object for <code>b</code> at which point it will also execute the descriptor:</p>
<pre><code>>>> class A(object): pass
>>> A.b = B(10, '')
>>> x = A()
>>> x.__dict__
{}
>>> x.b
B Retrieving
10
</code></pre>
|
python
| 2 |
1,907,311 | 30,951,421 |
running scripts without using python keyword
|
<p>I would like apologise since this is not exactly a programming releated question but rather something I would like to know :</p>
<p>I installed a python library with files say: lib.py, lib2.py .. lib-n.py. All these scripts take command line arguments when being called. So it looks like</p>
<p><code>username@machinename:~$ lib.py -s <args> -t <args> ..</code></p>
<p>Now like you can see above, I can run these scripts form any directory and without using the 'python' keyword before calling them. I would like to do this with the python scripts that I write as well. ie; I should be able to call them from any directory instead of 'cd'ing to their location.</p>
<p>P.S: Using a Linux machine running Ubuntu 12.04 and python 2.7.3</p>
|
<p>Add this to top of your script -</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>And then make your python script executable using <code>chmod</code> -</p>
<pre><code>chmod u+x <python script>
</code></pre>
<p>Also, if you do not want to give complete path to python script, you can add the directory the script exists in to <code>PATH</code> environment variable.</p>
|
python|unix
| 3 |
1,907,312 | 39,996,583 |
Is it possible to consume from every queue with pika?
|
<p>I'm trying to set up a program that will consume from every queue in RabbitMQ and depending on certain messages it will run certain scripts. Unfortunately while adding consumers if it runs into a single error (i.e. timeout or queue not found) the entire channel is dead. Additionally queues come and go so it has to refresh the queues list quite often. Is this even possible?
Here is my code so far.</p>
<pre><code>import pika
import requests
import sys
try:
host = sys.argv[1]
except:
host = "localhost"
def get_queues(host="localhost", port=15672, user="guest", passwd="guest", virtual_host=None):
url = 'http://%s:%s/api/queues/%s' % (host, port, virtual_host or '')
response = requests.get(url, auth=(user, passwd))
return response.json()
queues = get_queues(host)
def get_on_message(queue):
def on_message(channel, method_frame, header_frame, body):
print("message from", queue)
channel.basic_ack(delivery_tag=method_frame.delivery_tag)
return on_message
connection = pika.BlockingConnection(pika.ConnectionParameters(host))
channel = connection.channel()
for queue in queues:
print(channel.is_open)
try:
channel.basic_consume(get_on_message(queue["name"]), queue["name"])
print("queue added",queue["name"])
except Exception as e:
print("queue failed",queue["name"])
sys.exit()
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.stop_consuming()
connection.close()
</code></pre>
<p>Is there a right way to do this or is doing this not right at all?</p>
|
<p>It possible to consume from every queue in any language. It's also wrong and if this is something that is required, then the whole design/setup should be re-thought.</p>
<p>EDIT after comments:</p>
<p>Basically, you'd need to get the names of all existing queues which can be programmatically done via the <a href="http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_3_4/priv/www/api/index.html" rel="nofollow">rest api</a> (potentially even by calling rabbitmqctl and parsing the output). Once you have the names of the queues, you can simply consume from them as it is explained in <a href="http://www.rabbitmq.com/tutorials/tutorial-one-python.html" rel="nofollow">the tutorial</a>.</p>
<p>Once again, I don't think that this the right way to go, and perhaps you should consider using topic exchange - I'm guessing this since you wrote <code>queues come and go</code>.</p>
|
python|rabbitmq|pika
| 6 |
1,907,313 | 29,312,685 |
User uploading multiple images?
|
<p>I'm making web app that sell used bikes and I can't figure out how to enable user to upload multiple images. At the moment it is possible to upload only one image.Thanks in advance!</p>
<p>Here is my model.py:</p>
<pre><code>class UsedBike(models.Model):
manufacturer = models.CharField("Proizvođač",
max_length = 20, choices = manufacturers,) #proizvodjac
model = models.CharField("Model:", max_length = 20) #model
engine_size = models.IntegerField("Kubikaža:", default = 0) #kubikaza
km = models.IntegerField("Kilometraža:", default = 0) #kilometraza
year = models.IntegerField("Godina proizvodnje:", default = 0) #godina proizvodnje
bike_type = models.CharField("Vrsta motora:", max_length = 20, choices = bike_types) #tip motora
location = models.CharField("Lokacija:", max_length = 20) #lokacija
comment = models.TextField("Komentar:") #opis
views = models.IntegerField("Broj pregleda:", default = 0) #broj pregleda
likes = models.IntegerField(default = 0) #broj lajkova
slug = models.SlugField(unique = True) #slug
hp = models.IntegerField("Snaga", default = 0) #snaga
condition = models.CharField("Stanje:", max_length = 15, choices = condition_of_bike) #stanje
price = models.IntegerField("Cena:", default = 0) #cena
registered = models.CharField("Registrovan:", max_length = 15, choices = yes_no) #registrovan
img = models.ImageField("Slike:", upload_to = 'img', blank = True, null = True)
pub_date = models.DateTimeField(editable = False, default = timezone.now())
expire_date = models.DateTimeField(editable = False, default = timezone.now()+datetime.timedelta(days = 30))
author = models.ForeignKey(User)
</code></pre>
<p>forms.py:</p>
<pre><code>class BikeForm(forms.ModelForm):
helper = FormHelper()
helper.layout = Layout(
Div(
Div('manufacturer', 'model', 'engine_size', 'km', 'year', 'bike_type', 'location',
css_class = 'col-md-6'),
Div(AppendedText('hp', 'ks'), 'condition', AppendedText('price', '€'), 'registered', 'comment', Field('img', multiple = 'multiple'),
ButtonHolder(Submit('submit', 'Dodaj', css_class = 'btn btn-primary')), css_class = 'col-md-6'),
css_class = 'row-fluid'),
)
class Meta:
model = UsedBike
widgets = {
'comment': forms.Textarea(attrs={'rows': 6, 'cols': 1}),
}
exclude = ('views', 'likes', 'slug', 'author')
</code></pre>
<p>views.py:</p>
<pre><code>def add_bike(request):
if request.method == 'POST':
form = BikeForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit = False)
form.author = request.user
form.save()
if 'img' in request.FILES:
form.img = request.FILES['img']
form.save()
return index(request)
else:
print form.errors
else:
form = BikeForm()
return render(request, 'shop/add_bike.html', { 'form': form })
</code></pre>
<p>And my form in template:</p>
<pre><code><form class = 'form' enctype = 'multipart/form-data' role = 'form' id = 'bike_form' method = 'post' action = '/shop/add_bike/' >
<h2>Postavi oglas</h2>
{% csrf_token %}
{% crispy form %}
</form>
</code></pre>
|
<p>Take a look on django-photologues' source code. It has an option to upload an arbitrary number of images in a zip file <a href="https://github.com/jdriscoll/django-photologue" rel="nofollow">https://github.com/jdriscoll/django-photologue</a></p>
|
python|django|image-uploading
| 0 |
1,907,314 | 8,751,293 |
does cassandra cql support aggregation functions, like group by and order by
|
<p>For example in CQL,
SELECT * from abc_dimension ORDER BY key ASC;</p>
<p>seems to be not working.</p>
<p>Any help?</p>
|
<p>There is no support for something like group by in CQL. There is some ordering support but only for columns within a row. Columns will already have a natural ordering within a row but you can retrieve the reverse ordering (ASC vs DSC) by using the REVERSED keyword.</p>
<p>See: <a href="http://www.datastax.com/docs/1.0/references/cql/SELECT" rel="noreferrer">http://www.datastax.com/docs/1.0/references/cql/SELECT</a></p>
|
python|cassandra|cql
| 5 |
1,907,315 | 52,124,027 |
python-evdev : reading axes X and Y of a gamepad simultaneously
|
<p>With a little project in hands I thought it would be a good excuse to learn python. With the gamepad I have here (Logitech F310), the values of axis X and axis Y for the joysticks vary between 0-255, with 127 or 128 when they are "idle" at the center.</p>
<p>With this code (from <a href="http://www.lafavre.us/robotics/IoT_LogitechF310.pdf" rel="nofollow noreferrer">http://www.lafavre.us/robotics/IoT_LogitechF310.pdf</a>)</p>
<pre><code>from evdev import InputDevice, categorize, ecodes, KeyEvent
gamepad = InputDevice('/dev/input/event3')
for event in gamepad.read_loop():
if event.type == ecodes.EV_ABS:
absevent = categorize(event)
if ecodes.bytype[absevent.event.type][absevent.event.code] == 'ABS_RZ':
if absevent.event.value > 128:
print 'reverse'
print absevent.event.value
elif absevent.event.value < 127:
print 'forward'
print absevent.event.value
if ecodes.bytype[absevent.event.type][absevent.event.code] == 'ABS_Z':
if absevent.event.value > 128 :
print 'right'
print absevent.event.value
elif absevent.event.value < 127:
print 'left'
print absevent.event.value
</code></pre>
<p>I'm able to get the positions for up, down, right, left; what I've failed to accomplish so far is, how to retrieve the values of X and Y when the joystick it's in between the X axis and the Y axis, which are narrow intervals (4 to be precise).</p>
|
<p>Each axis is reported separately, so you'll need to keep current state in some variables. </p>
<pre><code>from evdev import InputDevice, categorize, ecodes, KeyEvent
gamepad = InputDevice('/dev/input/event3')
last = {
"ABS_RZ": 128,
"ABS_Z": 128
}
for event in gamepad.read_loop():
if event.type == ecodes.EV_ABS:
absevent = categorize(event)
if ecodes.bytype[absevent.event.type][absevent.event.code] == 'ABS_RZ':
last["ABS_RZ"] = absevent.event.value
if ecodes.bytype[absevent.event.type][absevent.event.code] == 'ABS_Z':
last["ABS_Z"] = absevent.event.value
if last["ABS_RZ"] > 128:
print 'reverse'
print last["ABS_RZ"]
elif last["ABS_RZ"] < 127:
print 'forward'
print last["ABS_RZ"]
if last["ABS_Z"] > 128 :
print 'right'
print last["ABS_Z"]
elif last["ABS_Z"] < 127:
print 'left'
print last["ABS_Z"]
</code></pre>
|
python|evdev
| 3 |
1,907,316 | 51,914,145 |
Pythonic way to transform list of pairs to dict
|
<p>I have a List of pairs like this:</p>
<pre><code>[
{'Name': 'first_name', 'Value': 'Joe'},
{'Name': 'last_name', 'Value': 'Smith'},
{'Name': 'gender', 'Value': 'male'}
]
</code></pre>
<p>I want to transform it into a Dict like this:</p>
<pre><code>{
'first_name': 'Joe',
'last_name': 'Smith',
'gender': 'male'
}
</code></pre>
<p>I am currently using a simple loop to accomplish this now but I know there is a more Pythonic way to do it. Thoughts?</p>
<p>-Tony</p>
|
<p>It was easier than I expected:</p>
<pre><code>{pair['Name']:pair['Value'] for pair in source_list}
</code></pre>
<p>This uses a feature of Python called a Dict comprehension.</p>
|
python|python-3.x|algorithm|data-structures
| 2 |
1,907,317 | 51,768,594 |
Tensorflow: on what does the batch_size depend?
|
<p>I new on tensorflow and I try to understand what size should be <code>batch</code>.</p>
<p>Shape of my data <code>(119396, 12955)</code>. How can I choose best <code>batch_size</code> to my data?
And what dependence <code>batch_size</code> from data shape or using algorithm?</p>
|
<p>The batch size is the number of input data values that you are introducing at once in the model. It is very important while training, and secondary when testing. For a standard Machine Learning/Deep Learning algorithm, choosing a batch size will have an impact on several aspects:</p>
<ul>
<li>The bigger the <code>batch size</code>, the more data you will feed at once in a model. Thus, RAM <strong>memory consumption</strong> will be almost <strong>linear with</strong> <code>batch size</code>, and there will always be a limit based on your system specs and the size of your model above which your model will overflow.</li>
<li>The bigger the <code>batch size</code>, the <strong>faster</strong> you will <strong>loop over your dataset</strong> N times to perform training.</li>
<li>A bigger<code>batch size</code> will <strong>slow down</strong> your model <strong>training speed</strong>, meaning that it will take longer for your model to get one single update since that update depends on more data.</li>
<li>A bigger<code>batch size</code> will have more data to average towards the next update of the model, hence training should be smoother: <strong>smoother training/test accuracy curves</strong>.</li>
</ul>
<p>Note that the <strong>size of the data</strong> is only related to the batch size in the sense that the bigger the data, the smaller the maximum <code>batch size</code> becomes (limit set by RAM). The <strong>size of the model</strong> also has a similar relation.</p>
<p>In practice, you should follow "in powers of 2 and the larger the better, provided that the batch fits into your (GPU) memory". For more in-depth details, check <a href="https://stackoverflow.com/a/46655895/9670056">https://stackoverflow.com/a/46655895/9670056</a>.</p>
|
python|tensorflow
| 6 |
1,907,318 | 19,298,147 |
Python table error
|
<p>I always get this error for this code:</p>
<pre><code>Traceback (most recent call last):
File "E:/ankosh/trial13.py", line 14, in <module>
if grades_mix[index_no]=="HM1":
IndexError: list index out of range)
</code></pre>
<p>I would really appreciate the help.</p>
<pre><code> `file_pointer=open("C:/python27/Doc/student_grades.txt", "r")
read_grades=file_pointer.readline()
my_list=[]
while 0==0:
grades_mix=read_grades.split()
name_str=grades_mix[0]
contained_list=[name_str,0,0,0,0,0.0]
index_no=1
count_num=0
sum_float=0.0
avg_float=0.0
while 0==0:
if grades_mix[index_no]=="HM1":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[1]=grade_num
elif grades_mix[index_no]=="HM2":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[2]=grade_num
elif grades_mix[index_no]=="HM3":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[3]=grade_num
elif grades_mix[index_no]=="HM4":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[4]=grade_num
index_no+=1
if count_num>0:
avg_float=sum_float/count_num
contained_list[5]=avg_float
index_num=0
while index_num<len(my_list):
if my_list[0]>name_str:
break
index_no+=1
my_list.insert(index_num, contained_list)
read_grades=file_pointer.readline()
file_pointer.close()
print format ("Name","<10")+" | "+format("HM1"," >5")+" | "+format("HM2"," >5")+" | "+format("HM3"," >5")+" | "+format("HM4"," >5")+" | "+format("avg_float"," <10")+" | "
for index_no in range(0, len(my_list)):
print format(my_list[index_num][0], "<10") + " | " + \
format(my_list[index_num][1], " >5") + " | " + \
format(my_list[index_num][2], " >5") + " | " + \
format(my_list[index_num][3], " >5") + " | " + \
format(my_list[index_num][4], " >5") + " | " + \
format(my_list[index_num][5], " >10.2f") + " | "
</code></pre>
|
<p>You have, in abbreviated form:</p>
<pre><code>while 0==0:
if grades_mix[index_no]=="HM1":
index_no+=1
</code></pre>
<p>with no break statement to ever get out of the loop (which, how about <code>while True</code>?). Sooner or later you're going to go out of range.</p>
|
python|python-2.7
| 3 |
1,907,319 | 62,419,849 |
merge two lists (even/odd elements)
|
<pre><code>len_array = 10
A = np.zeros( len_array )
B = np.zeros( len_array )
A = np.arange(1, 5, 0.5)
B = np.arange(11, 15, 0.5)
A = A.tolist()
B = B.tolist()
</code></pre>
<p>I followed another <a href="https://stackoverflow.com/questions/18041840/python-merge-two-lists-even-odd-elements">post</a> that did similar task, however it just insert elements in B into A. This method did not generate a new list C.</p>
<pre><code>for i,v in enumerate(B):
A.insert(2*i+1,v)
</code></pre>
<p>How to create a new list C that merges A and B based on their even/odd elements?</p>
<p>Thanks.</p>
|
<pre><code>In [194]: A = np.arange(1, 5, 0.5)
...: B = np.arange(11, 15, 0.5)
</code></pre>
<p>The list derived from <code>A</code> is a copy. in-place changes to <code>C</code> don't affect <code>A</code>:</p>
<pre><code>In [196]: C = A.tolist()
In [197]: for i,v in enumerate(B):
...: C.insert(2*i+1,v)
...:
In [198]: A
Out[198]: array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
In [199]: B
Out[199]: array([11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5])
In [200]: C
Out[200]:
[1.0,
11.0,
1.5,
11.5,
2.0,
12.0,
2.5,
12.5,
3.0,
13.0,
3.5,
13.5,
4.0,
14.0,
4.5,
14.5]
</code></pre>
<p>An array approach:</p>
<pre><code>In [201]: np.vstack((A,B))
Out[201]:
array([[ 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5],
[11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5]])
In [202]: np.vstack((A,B)).ravel(order='F')
Out[202]:
array([ 1. , 11. , 1.5, 11.5, 2. , 12. , 2.5, 12.5, 3. , 13. , 3.5,
13.5, 4. , 14. , 4.5, 14.5])
</code></pre>
<p>Or we could stack the arrays as columns and do the ordinary <code>C</code> order ravel.</p>
<p>===</p>
<p>Another list way - use <code>zip</code> to make list of lists, and <code>itertools.chain</code> to flatten that:</p>
<pre><code>In [203]: import itertools
In [204]: [(i,j) for i,j in zip(A,B)]
Out[204]:
[(1.0, 11.0),
(1.5, 11.5),
(2.0, 12.0),
(2.5, 12.5),
(3.0, 13.0),
(3.5, 13.5),
(4.0, 14.0),
(4.5, 14.5)]
In [205]: list(itertools.chain(*[(i,j) for i,j in zip(A,B)]))
Out[205]:
[1.0,
11.0,
1.5,
11.5,
2.0,
12.0,
2.5,
12.5,
3.0,
13.0,
3.5,
13.5,
4.0,
14.0,
4.5,
14.5]
</code></pre>
|
python|numpy
| 2 |
1,907,320 | 36,281,738 |
Django debug toolbar installation (Django 1.9)
|
<p>I'm using python 3.5.1 with django 1.9.4 in virtualenv (Windows). I'm trying to add the django-debug-toolbar but I get an error when starting the server. </p>
<p>I added 'django_debug' in my installed_apps, and also 'debug_toolbar.middleware.DebugToolbarMiddleware' in my middleware_classes.</p>
<p>Pip freeze log:</p>
<pre><code>Django==1.9.4
django-debug-toolbar==1.4
sqlparse==0.1.19
</code></pre>
<p>Runserver:</p>
<p><strong>ImportError: No module named 'django_debug'</strong></p>
|
<p>You have to add <code>debug_toolbar</code> in <code>INSTALLED_APPS</code> and <strong>not</strong> <code>django_debug</code>.</p>
<p>Also, you can remove the class that you added in <code>MIDDLEWARE_CLASSES</code>. As given in the docs:</p>
<blockquote>
<p>If <code>MIDDLEWARE_CLASSES</code> doesn’t contain the middleware, the Debug Toolbar automatically adds it the beginning of the list.</p>
</blockquote>
<p>You can have a look at the <a href="https://django-debug-toolbar.readthedocs.org/en/1.4/installation.html#quick-setup" rel="nofollow">docs</a>.</p>
|
python|django|django-debug-toolbar|django-1.9
| 2 |
1,907,321 | 36,314,588 |
How to read an html table with multiple tbodies with python pandas' read_html?
|
<p>This is my html:</p>
<pre><code>import pandas as pd
html_table = '''<table>
<thead>
<tr><th>Col1</th><th>Col2</th>
</thead>
<tbody>
<tr><td>1a</td><td>2a</td></tr>
</tbody>
<tbody>
<tr><td>1b</td><td>2b</td></tr>
</tbody>
</table>'''
</code></pre>
<p>If I run <code>df = pd.read_html(html_table)</code>, and then <code>print(df[0]</code> I get:</p>
<pre><code> Col1 Col2
0 1a 2a
</code></pre>
<p>Col 2 disappears. Why? How to prevent it?</p>
|
<p><em>The HTML you have posted is not a valid one</em>. Multiple <code>tbody</code>s is what confuses the <code>pandas</code> parser logic. If you cannot fix the input html itself, you have to pre-parse it and <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#unwrap" rel="nofollow">"unwrap"</a> all the <code>tbody</code> elements:</p>
<pre><code>import pandas as pd
from bs4 import BeautifulSoup
html_table = '''
<table>
<thead>
<tr><th>Col1</th><th>Col2</th>
</thead>
<tbody>
<tr><td>1a</td><td>2a</td></tr>
</tbody>
<tbody>
<tr><td>1b</td><td>2b</td></tr>
</tbody>
</table>'''
# fix HTML
soup = BeautifulSoup(html_table, "html.parser")
for body in soup("tbody"):
body.unwrap()
df = pd.read_html(str(soup), flavor="bs4")
print(df[0])
</code></pre>
<p>Prints:</p>
<pre><code> Col1 Col2
0 1a 2a
1 1b 2b
</code></pre>
|
python|html|pandas|lxml
| 4 |
1,907,322 | 36,472,805 |
Model an undirected graph in Python
|
<p>I tried to draw a "network graph" with networkX but was <a href="https://stackoverflow.com/questions/36431153/networkx-in-python-connect-only-values-not-keys">told</a>, that this library is not intended for the purpose I want to use it for.</p>
<p>So summarizing the failed question linked above, I start with the data I want to plot and proceed with the actual question:</p>
<pre><code>graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
</code></pre>
<p>Considering this data as a defaultdict(list), the most left part is the key, and the list of the right side is a list of values to that key. What I want to achieve, is drawing a graph, similar to a network graph <a href="https://stackoverflow.com/questions/24376200/python-networks-change-color-of-nodes-when-using-draw-network-nodes/24378318#24378318">here</a>: The more edges, the bigger the nodes, label the nodes, etc.</p>
<p>However, the difference is that I want to connect the keys, with the corresponding values (1 with 2, 1 with 3, 1 with 4) but <strong>not</strong> the keys with each other (<strong>not</strong> 1 with 2 with 3 with 5 with 4 with 7).</p>
<p>Image the data being Servers and clients. The keys are the servers, and the values are the clients. The servers (keys) are not connected to each other directly, they only share (sometimes) the same clients. As of the example above, server 3 and server 5 are both connected to the clients 6, 66 and 77. This is also the reason, why the clients (values) should not be connected with each other.</p>
<p>I was hopefully able to make my question clear^^</p>
<p>Thanks!</p>
|
<p>The problem is you're trying to use the same IDs for your servers and clients. NetworkX has no way to know if <code>2</code> refers to a client (that should be connected) or a server (that should not). To do what you're describing here, you just need to create a unique id for the servers. For example:</p>
<pre><code>import networkx
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3': ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}
g = networkx.Graph()
for k, vs in graph.items():
server_id = 'server_%s' % k
for v in vs:
g.add_edge(server_id,v)
networkx.draw_spring(g)
</code></pre>
<p>This produces the following output:</p>
<p><a href="https://i.stack.imgur.com/c1CtU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c1CtU.png" alt="NetworkX plot"></a></p>
<p>To change the size of node by the number of edges, you need to calculate the size and pass it to <code>draw_spring</code>. To get the number of edges for a particular node you can call <code>g.edges(node)</code> e.g.</p>
<pre><code>node_sizes = [150*len(g.edges(n)) for n in g.nodes()]
networkx.draw_spring(g, node_size=node_sizes)
</code></pre>
<p>Which should give you the following:</p>
<p><a href="https://i.stack.imgur.com/IUNMt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IUNMt.png" alt="enter image description here"></a></p>
|
python|matplotlib|graph|networkx
| 3 |
1,907,323 | 19,666,227 |
Exception in python unknown errors
|
<pre><code> except ValueError:
print "the input is Invaild(dd.mm.year)"
except as e:
print "Unknown error"
print e
</code></pre>
<p>This is the code I wrote, if an error different then valueerror will happen will it print it in e?
thanks</p>
|
<p>You'll need to catch the <code>BaseException</code> or <code>object</code> here to be able to assign to <code>e</code>:</p>
<pre><code>except ValueError:
print "the input is Invaild(dd.mm.year)"
except BaseException as e:
print "Unknown error"
print e
</code></pre>
<p>or, better still, <code>Exception</code>:</p>
<pre><code>except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e
</code></pre>
<p>The blanket <code>except:</code> will catch the same exceptions as <code>BaseException</code>, catching just <code>Exception</code> will <em>ignore</em> <code>KeyboardInterrupt</code>, <code>SystemExit</code>, and <code>GeneratorExit</code>. Not catching these there is <em>generally</em> a good idea.</p>
<p>For details, see the <a href="http://docs.python.org/2/library/exceptions.html" rel="noreferrer">exceptions documentation</a>.</p>
|
python
| 16 |
1,907,324 | 19,345,256 |
counting values and adding reference in a new dataframe column
|
<p>I have a dataframe that contains multiple appearances of a certain value in a certain column. I want to set those values unique by adding some kind of a reference in a new column. for example, suppose i have a dataframe with an ID column:</p>
<pre><code> ID
7 2035200584
8 2035200584
9 2035200584
31 2038128459
32 2038128459
33 2038128459
42 2053561908
43 2053561908
44 2053561908
</code></pre>
<p>and I want to create a new column, say "newID", which will look something like this:</p>
<pre><code> ID
7 2035200584_1
8 2035200584_2
9 2035200584_3
31 2038128459_1
32 2038128459_2
33 2038128459_3
42 2053561908_1
43 2053561908_2
44 2053561908_3
</code></pre>
<p>Iv'e tried to use the groupby mechanism, but with no success. using the simple apply mechanism is ok, but seems a little cumbersome (I'll need to keep a dictionary containing a counter of appearances for each ID)</p>
<p>Is there a simple and efficient way to do that that I'm missing?</p>
|
<p>Here's a slight variation of DSM's solution:</p>
<pre><code>import pandas as pd
import io
content = io.BytesIO('''index ID
7 2035200584
8 2035200584
9 2035200584
31 2038128459
32 2038128459
33 2038128459
42 2053561908
43 2053561908
44 2053561908''')
df = pd.read_table(content, sep='\s+', header=0)
df['ID'] = df.groupby('ID')['ID'].transform(
lambda x: map('{:.0f}_{:.0f}'.format, x, x.rank('first')))
print(df)
</code></pre>
<p>yields</p>
<pre><code> index ID
0 7 2035200584_1
1 8 2035200584_2
2 9 2035200584_3
3 31 2038128459_1
4 32 2038128459_2
5 33 2038128459_3
6 42 2053561908_1
7 43 2053561908_2
8 44 2053561908_3
</code></pre>
|
python|pandas
| 3 |
1,907,325 | 13,298,592 |
Why does Popen.poll() return a return code of None even though the sub-process has completed?
|
<p>I have some Python code that runs on Windows that spawns a subprocess and waits for it to complete. The subprocess isn't well behaved so the script makes a non-blocking spawn call and watches the process on the side. If some timeout threshold is met it kills of the process, assuming it has gone of the rails.</p>
<p>In some instances, which are non-reproducible, the spawned subprocess will just disappear and the watcher routine won't pick up on this fact. It'll keep watching until the timeout threshold is passed, try to kill the subprocess and get an error, and then exit.</p>
<p><strong>What might be causing the fact that the subprocess has gone away to be undetectable to the watcher process? Why isn't the return code trapped and returned by the call to <code>Popen.poll()</code>?</strong></p>
<p>The code I use to spawn and watch the process follows:</p>
<pre><code>import subprocess
import time
def nonblocking_subprocess_call(cmdline):
print 'Calling: %s' % (' '.join(cmdline))
p = subprocess.Popen(cmdline, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return p
def monitor_subprocess(handle, timeout=1200):
start_time = time.time()
return_code = 0
while True:
time.sleep(60)
return_code = handle.poll()
if return_code == None:
# The process is still running.
if time.time() - start_time > timeout:
print 'Timeout (%d seconds) exceeded -- killing process %i' % (timeout, handle.pid)
return_code = handle.terminate()
# give the kill command a few seconds to work
time.sleep(5)
if not return_code:
print 'Error: Failed to kill subprocess %i -- return code was: %s' % (handle.pid, str(return_code))
# Raise an error to indicate that the process was hung up
# and we had to kill it.
raise RuntimeError
else:
print 'Process exited with return code: %i' % (return_code)
break
return return_code
</code></pre>
<p>What I'm seeing is that, in cases where the process has disappeared, the call to <code>return_code = handle.poll()</code> on line 15 is returning <code>None</code> instead of a return code. I know the process has gone away completely -- I can see that it is no longer there in Task Manager. And I know the process disappeared long before the timeout value was reached.</p>
|
<p>poll method on subprocess objects does not seem to work too good.
I used to have same issues while i was spawning some threads to do some job.
I suggest that you use the multiprocessing module.</p>
|
python|windows|subprocess
| 1 |
1,907,326 | 58,163,796 |
Plotting data by year over year using plotly
|
<p>I have a data look like this:-</p>
<pre><code>Month Year Value
Jan 2015 2.8
Jan 2015 2.0
Mar 2016 0.9
Feb 2015 3.1
Mar 2016 4.2
Feb 2015 2.1
Mar 2016 2.3
Feb 2015 1.1
Apr 2016 1.3
Apr 2016 0.5
</code></pre>
<p>Now I want to plot line chart, but by using this code, I am getting this output. below <a href="https://i.stack.imgur.com/LB6o5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LB6o5.png" alt="enter image description here"></a></p>
<p>Code I have used:- </p>
<pre><code>df = rslt_bb.sort_values(by='Year')
trace = go.Scatter(
x = df["Year"],
y = df["Value"],
mode='markers+lines'
)
layout = go.Layout(
#title='Distribution by year',
xaxis=dict(title='Year'),
yaxis=dict(title='Value'),
showlegend=True
)
fig = dict(data=[trace], layout=layout)
offline.iplot(fig)
</code></pre>
<p>I want the plotting should be like not aggregated all common year in the same line, I want spreaded. All year, single data should be visible separately, like this way below, <a href="https://i.stack.imgur.com/PC3GF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PC3GF.png" alt="enter image description here"></a></p>
|
<p>You need to crate a <code>datetime</code> object for plotting a <code>Time Series</code>. So instead of</p>
<pre><code>x = df["Year"]
</code></pre>
<p>use</p>
<pre><code># import pandas as pd
x = pd.to_datetime(df.Year*100+df.Month, format='%Y%m')
</code></pre>
|
python|pandas|plotly
| 1 |
1,907,327 | 43,579,626 |
Pandas Plot With Positive Values One Color And Negative Values Another
|
<p>I have a pandas dataframe where I am plotting two columns out the 12, one as the x-axis and one as the y-axis. The x-axis is simply a time series and the y-axis are values are random integers between -5000 and 5000 roughly. </p>
<p>Is there any way to make a scatter plot using only these 2 columns where the positive values of y are a certain color and the negative colors are another color?</p>
<p>I have tried so many variations but can't get anything to go. I tried diverging color maps, colormeshs, using seaborn colormaps and booleans masks for neg/positive numbers. I am at my wits end.</p>
|
<p>The idea to use a colormap to colorize the points of a scatter is of course justified. If you're using the <code>plt.scatter</code> plot, you can supply the values according to which the colormap chooses the color in the <code>c</code> argument. </p>
<p>Here you only want two values, so <code>c= np.sign(df.y)</code> would be an appropriate choice. </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame({'x': np.arange(25), 'y': np.random.normal(0,2500,25)})
fig, ax = plt.subplots()
ax.scatter(df.x, df.y, c=np.sign(df.y), cmap="bwr")
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/akoQF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/akoQF.png" alt="scatter plot colored according to postive and negative vlaues"></a></p>
|
python|pandas|matplotlib|plot
| 6 |
1,907,328 | 43,737,968 |
Missing value didnt disappear
|
<p>I tried to replace the missing value with 0, but it didn't work. Here is my code : </p>
<pre><code>df_all_data[[ 'Temps_normal_trajet_agent', 'Temps_astreinte_trajet_agent',
'Heures_suptrajet_agent','Duree_normale_intervention_agent',
'Duree_intervention_astreinte_agent' , 'Duree_intervention_Heures_supagent' ,
'FDROUTE_DATE' ]].fillna(0)
</code></pre>
<p>And here is the result I got:
<a href="https://i.stack.imgur.com/W0xRW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W0xRW.png" alt="enter image description here"></a></p>
|
<p>Remember to reassign to the original variable. <code>fillna</code> by default is not an inplace operation. You can also use, <code>inplace=True</code> as an argument to fillna. For example, .fillna(0, inplace=True) then you don't reassign.</p>
<pre><code>df_all_data[[ 'Temps_normal_trajet_agent', 'Temps_astreinte_trajet_agent',
'Heures_suptrajet_agent','Duree_normale_intervention_agent', 'Duree_intervention_astreinte_agent' , 'Duree_intervention_Heures_supagent' , 'FDROUTE_DATE' ]] = df_all_data[[ 'Temps_normal_trajet_agent', 'Temps_astreinte_trajet_agent',
'Heures_suptrajet_agent','Duree_normale_intervention_agent', 'Duree_intervention_astreinte_agent' , 'Duree_intervention_Heures_supagent' , 'FDROUTE_DATE' ]].fillna(0)
</code></pre>
|
python|pandas|dataframe|missing-data
| 3 |
1,907,329 | 43,676,152 |
Pandas convert column to datetime
|
<p>I have this df:</p>
<pre><code> A
0 2017-04-17 00:00:00
1 2017-04-18 00:00:00
2 2017-04-19 00:00:00
3 2017-04-20 00:00:00
4 2017-04-21 00:00:00
</code></pre>
<p>I am trying to get rid of the H, M, S, so that I am left with:</p>
<pre><code> A
0 2017-04-17
1 2017-04-18
2 2017-04-19
3 2017-04-20
4 2017-04-21
</code></pre>
<p>the dtype of column A is object. I have tried:</p>
<pre><code>df['A'] = df['A']datetime.strftime('%Y-%m-%d')
</code></pre>
<p>with:</p>
<pre><code>import datetime as datetime
</code></pre>
<p>I get:</p>
<pre><code>AttributeError: 'Series' object has no attribute 'strftime'
</code></pre>
|
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="noreferrer"><code>dt.strftime</code></a> - output are <code>strings</code>:</p>
<pre><code>#if necessary
#df['A'] = pd.to_datetime(df['A'])
print (type(df.loc[0, 'A']))
<class 'pandas.tslib.Timestamp'>
df['A'] = df['A'].dt.strftime('%Y-%m-%d')
print (df)
A
0 2017-04-17
1 2017-04-18
2 2017-04-19
3 2017-04-20
4 2017-04-21
print (type(df.loc[0, 'A']))
<class 'str'>
</code></pre>
<p>and for dates use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="noreferrer"><code>date</code></a>:</p>
<pre><code>df['A'] = df['A'].dt.date
print (df)
A
0 2017-04-17
1 2017-04-18
2 2017-04-19
3 2017-04-20
4 2017-04-21
print (type(df.loc[0, 'A']))
<class 'datetime.date'>
</code></pre>
|
python|pandas
| 5 |
1,907,330 | 43,837,721 |
Is it thread safe to modify a static variable?
|
<p>Since C++11, static variable initialization is guaranteed to be thread safe. But how about modifying a static variable in multiple threads? like below</p>
<pre><code>static int initialized = 0;
Initialize()
{
if (initialized)
return;
initialized = 1; // Is this thread safe?
}
</code></pre>
<p>The reason I ask this question is that I am reading the source code for
<code>Py_Initialize()</code>, I am trying to embed Python in a multithreaded C++ application, I am wondering if it is safe to call <code>Py_Initialize()</code> multiple times in several threads? The implementation of <code>Py_Initialize()</code> boils down to
function <code>_Py_InitializeEx_Private</code>, which is like below</p>
<pre><code>// pylifecycle.c
static int initialized = 0;
_Py_InitializeEx_Private(int install_sigs, int install_importlib)
{
if (initialized)
return;
initialized = 1;
// a bunch of other stuff
}
</code></pre>
<p>And is the conclusion for C the same as C++?</p>
<p><strong>EDIT</strong>
So all the answers are good, I chose the one which clears my head most.</p>
|
<p>No, static in this context is only about the storage duration (see <a href="http://en.cppreference.com/w/c/language/static_storage_duration" rel="noreferrer">http://en.cppreference.com/w/c/language/static_storage_duration</a>).
The variable has no extra thread safety at all over some other variable.</p>
<p>Try using std::call_once for this, see <a href="http://en.cppreference.com/w/cpp/thread/call_once" rel="noreferrer">http://en.cppreference.com/w/cpp/thread/call_once</a></p>
|
python|c++|c|multithreading|c++11
| 7 |
1,907,331 | 53,375,102 |
Serialize array data from C code, deserialize in Python
|
<p>I need to store dense array data (3D arrays) from C code and then to read them into NumPy arrays (in another application). The data is around 100 kbytes of float values, C array as a pointer to the data. I am looking for a solution that does not require any external dependencies and can be implemented with the least effort.</p>
<p>What would be a good solution for that?</p>
<p>Thanks.</p>
|
<p>I've done some serialization for arm devices and network and I'would be happy to share my experience since you prefer binary serialization.
I am using unions to serialize.Lets assume that you have a struct that holds some element, data and pointers and this holds data for a family member :</p>
<pre><code>struct fam_member
{
char name [ MAX_NAME_LEN + 1 ];
int height;
age_bracket_t age_bracket;
fam_member_t* mother;
fam_member_t* father;
}fam_member_t;
</code></pre>
<p>Age bracket is an enum:</p>
<pre><code>typedef enum age_bracket
{
under_18 = 0 , from_18_to_25 = 1 , from_26_to_40 = 2 , over_40 = 3
}age_bracket_t;
</code></pre>
<p>The main problem and the most common mistake is struct padding and not taking this to serious.<a href="https://fresh2refresh.com/c-programming/c-structure-padding/" rel="nofollow noreferrer">Here</a> is a good start if someone is not familiar with the issue.
My simple solution is stream data down byte to byte (or bit to bit), do what you need to do with the serialized data (i.e. send them over a socket) and deserialize in the end.
I define a Union like this: </p>
<pre><code>typedef union serialized_struct
{
fam_member_t family_member;
unsigned char data[ (MAX_NAME_LEN + 1 ) + (sizeof(int)*3) ];
}serialized_struct_t;
</code></pre>
<p><a href="https://www.tutorialspoint.com/cprogramming/c_unions.htm" rel="nofollow noreferrer">(A few think about union here)</a>
The purpose of union is to save memory by using the same memory region for storing different objects at different times.In this example this will help us and actually serialize the family object struct for free.</p>
<p>Here is a function that serializes an array of family members (if you can do an area, single will be a piece of cake.That's why I choose an array here).</p>
<pre><code>int serialize_array(fam_member_t* people , char* message , int elements)
{
if((people == NULL ) || (message == NULL) || (elements < 1))
{
return -1;
}
int size = sizeof(fam_member_t);
int i;
for(i=0 ; i < elements ; i++)
{
serialized_struct_t x;
memcpy((x.family_member.name) , people[i].name , MAX_NAME_LEN);
x.family_member.age_bracket = people[i].age_bracket;
x.family_member.height = people[i].age_bracket
x.family_member.mother = people[i].mother;
x.family_member.father = people[i].father;
memcpy ( (message + (size * i)) , x.data , size );
}
return 0;
}
</code></pre>
<p>Here we initiate every data of every member inside the struct which lies in the union.Message holds serialized data.This is the deserialized function which will do the reverse</p>
<pre><code>int desirialize_array(fam_member_t* people , char* message , int elements)
{
if((people == NULL ) || (message == NULL) || (elements < 1))
{
return -1;
}
int size = sizeof(fam_member_t);
serialized_struct_t y;
int i;
for (i =0 ; i < elements ; i ++ )
{
memcpy ( y.data , (message + (size * i)) , size );
memcpy ( people[i].name , y.family_member.name , MAX_NAME_LEN);
people[i].age_bracket = y.family_member.age_bracket;
people[i].height = y.family_member.height;
people[i].mother = y.family_member.mother;
people[i].father = y.family_member.father;
}
return 0;
}
</code></pre>
<p>This is serialize and deserialize in c example.For your case where you need to deserialize this in python I think it will be easy if you figured out which will be the mean of serialization.JSON that @Alexander Tolkachev said for example could be a solution.
I hope this simplified example helps you.</p>
|
python|c|numpy|serialization
| 1 |
1,907,332 | 54,581,514 |
Save array output to csv in Python
|
<p>I am trying to scrape data from a website. I am making a loop to extract the data, and store in a variable, but a can't save it in csv file. Being new to Python and BeautifulSoup I'm not getting very far. Here's the code: </p>
<pre><code>import requests
from bs4 import BeautifulSoup
import csv
r = "https://sofia.businessrun.bg/en/results-2018/"
content = requests.get(r)
soup = BeautifulSoup(content.text, 'html.parser')
for i in range (1,5):
team_name= soup.find_all(class_="column-3")
team_time= soup.find_all(class_="column-5")
for i in range (1,5):
print (team_name[i].text)
print (team_time[i].text)
with open("new_file.csv","w+") as my_csv:
csvWriter = csv.writer(my_csv,delimiter=',')
csvWriter.writerows(team_name)
</code></pre>
<p>Any help would be greatly appreciated!</p>
|
<p>I found another way of doing your <strong>scraping</strong> and saving it in a csv by using pandas. The code is here below:</p>
<pre><code>import requests
# I changed this
import pandas as pd
from bs4 import BeautifulSoup
import csv
r = "https://sofia.businessrun.bg/en/results-2018/"
content = requests.get(r)
soup = BeautifulSoup(content.text, 'html.parser')
for i in range (1,5):
team_name= soup.find_all(class_="column-3")
team_time= soup.find_all(class_="column-5")
tn_list = []
tt_list = []
# I changed this to have string in place of tags
tn_list = [str(x) for x in team_name]
tt_list = [str(x) for x in team_time]
for i in range (1,5):
print(team_name[i].text)
print(team_time[i].text)
# I put the result in a dataframe
df = pd.DataFrame({"teamname" : tn_list, "teamtime" : tt_list})
# I use regex to clean your data (get rid of the html tags)
df.teamname = df.teamname.str.replace("<[^>]*>", "")
df.teamtime = df.teamtime.str.replace("<[^>]*>", "")
# The first row is actually the column name
df.columns = df.iloc[0]
df = df.iloc[1:]
# I send it to a csv
df.to_csv(r"path\to\new_file.csv")
</code></pre>
<p>this should normally work</p>
|
python|arrays|file|csv|save
| 1 |
1,907,333 | 47,739,191 |
PyQt5 pyuic Import error: DLL load failed
|
<p>
I have downloaded <code>python 3.6.2</code> from python.org and <code>pyqt 5.9.2</code> using pip to install but I am having a problem when converting code from <code>.ui</code> to <code>.py</code>
<pre><code>C:\Users\pc\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\pyqt5-tools>pyuic5 -x satesto.ui -o satesto.py
Traceback (most recent call last):
File "c:\users\pc\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\users\pc\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\pyqt5-tools\pyuic5.exe\__main__.py", line 5, in <module>
File "c:\users\pc\appdata\local\programs\python\python36-32\lib\site-packages\PyQt5\uic\pyuic.py", line 26, in <module>
from PyQt5 import QtCore
ImportError: DLL load failed: The specified procedure could not be found.
</code></pre>
<p>
It says that dll load is failed when typing from PyQt5 <code>import QtCore</code> but when I type it in basic python it works without a problem. Do anyone know what could be the problem or how can it be solved?</p>
|
<p>You can follow these steps(Windows 8 or 10 User) to accomplish the converting from .ui to .py</p>
<ol>
<li><p>Open the folder Python36\Scripts</p>
</li>
<li><p>Click shift key anywhere in the window and then select PowerShell</p>
</li>
<li><p>Write <code>pyuic5 -x</code> the place where you have saved ui data -o name.py</p>
<p>example: <code>pyuic5 -x C:\User\Documents\MyPython\MyGui.ui -o MyGui.py</code></p>
</li>
<li><p>You will find MyGui.py in Scripts of the Python36</p>
</li>
</ol>
|
python|pyqt|pyuic
| 2 |
1,907,334 | 47,733,611 |
isinstance: How to manage set classes better
|
<p>While writing some debugging python, I seem to have created a bit of ugly code that I would like to clean up.</p>
<p>Here is the function in its entirety:</p>
<pre><code>def debug(message, variable=None):
if variable and DEBUG:
print("\n" + str(type(variable)))
try:
if isinstance(variable, (list, dict, 'OrderedDict')):
variable = json.dumps(
variable,
indent=4,
sort_keys=True
)
except TypeError:
if isinstance(variable, (list, dict)):
variable = json.dumps(
variable,
indent=4,
sort_keys=True
)
if DEBUG:
if variable:
print(message + str(variable) + "\n")
else:
print("\n" + message)
</code></pre>
<p>I specifically despise my try-except statement, because not only am I repeating code, but if I run into another dictionary class (like CaseInsensitiveDict from requests' headers) that I would like to print nicely during debugging output I would have to nest try-except statements. </p>
<p>Is there a way that I could check if <code>type(variable)</code> is like <code>*dict*</code> or <code>*list*</code> then add it when creating the tuple for use in isinstance?</p>
|
<p>You want to look at the <a href="https://docs.python.org/3/library/functools.html#functools.singledispatch" rel="nofollow noreferrer"><code>@functools.singledispatch()</code> construct</a>; this lets you delegate to specific functions to handle your debugging, keyed on types:</p>
<pre><code>from functools import singledispatch
def debug(message, variable=None):
if not DEBUG:
return
variable = debug_display(variable)
print('{}{}\n'.format(message, variable))
@singledispatch
def debug_display(variable):
return str(variable)
@debug_display.register(type(None))
def _none_to_empty_string(_ignored):
return ''
@debug_display.register(dict)
@debug_display.register(list)
@debug_display.register(OrderedDict)
def _as_json(variable):
return json.dumps(
variable,
indent=4,
sort_keys=True
)
@debug_display.register(SomeOtherType)
def _handle_specific_type(variable):
# handle custom types any way you need to with separate registrations
return "{} -> {}".format(variable.spam, variable.ham)
</code></pre>
<p><code>singledispatch</code> knows how to delegate for subclasses that don't have specific handlers; so <code>OrderedDict</code> is handled by the <code>_as_json</code> handler because it is a subclass of <code>dict</code>.</p>
|
python|isinstance
| 2 |
1,907,335 | 37,318,637 |
Python how to sort list with float values
|
<p>How to sort the python list that contains the float values,</p>
<pre><code>list1 = [1, 1.10, 1.11, 1.1, 1.2]
</code></pre>
<p>or</p>
<pre><code>list1 = ['1', '1.10', '1.11', '1.1', '1.2']
</code></pre>
<p>The expected results is</p>
<pre><code>list_val = ['1', **'1.1', '1.2'**, '1.10', '1.11']
</code></pre>
<p>but the returned result in using sort() method returns</p>
<pre><code>[1, 1.1000000000000001, 1.1000000000000001, 1.1100000000000001, 1.2]
</code></pre>
<p>or</p>
<pre><code>['1', '1.1', '1.10', '1.11', '1.2'].
</code></pre>
<p>But, here <code>1.2</code> should come in between <code>1.1</code> and <code>1.10</code>.</p>
|
<p>You can use:</p>
<pre><code>list1 = sorted(list1)
</code></pre>
<p>If it is in the second format (as a string) you can use the key parameter to convert it into floats by using:</p>
<pre><code>list1 = sorted(list1, key=float)
</code></pre>
<p>The key parameter expects a function that will transform the values before sorting using the transformed values, but keeping the original values</p>
|
python|list|sorting
| 15 |
1,907,336 | 34,069,474 |
Iterating over a DataFrame in ReportLab
|
<p>I want to iterate over the DataFrame (df) to produce a PDF for each hospital ('A' and 'B'). I tried many ways, but have not been successful unless I make the name a random number with np.random.rand(1), but that still had issues. Update:
I want the name of the .pdf to be the hospital name per iteration. If I try to add the hospital name, it results in an error:</p>
<p>When I set:</p>
<pre><code>pdf_file_name = str(np.random.rand(1))+'.pdf'
</code></pre>
<p>The result is:</p>
<pre><code>OSError: [Errno 22] Invalid argument: '0 A\nName: Hospital, dtype: object.pdf'
</code></pre>
<p>So I need go figure out how to:
1. Pass the hospital name in to the file name and
2. Iterate over hospital names to produce one PDF per hospital.</p>
<pre><code>from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.pagesizes import portrait
from reportlab.platypus import Image
import pandas as pd
import numpy as np
df = pd.DataFrame({'Hospital':['A','B']})
#This is here to just produce one report that "works" while working on the code.
df = df[(df.Hospital == 'A')]
hospital = df['Hospital']
def import_data(df):
import numpy as np
hospital = df['Hospital']
pdf_file_name = str(np.random.rand(1))+'.pdf'
generate_report(hospital, pdf_file_name)
def generate_report(hospital, pdf_file_name):
c = canvas.Canvas(pdf_file_name, pagesize=portrait(letter))
c.setFont('Helvetica', 48, leading=None)
c.drawCentredString(415, 500, 'Report')
c.setFont('Helvetica', 24, leading=None)
c.drawCentredString(415, 450, 'This Report is For:')
c.setFont('Helvetica-Bold', 34, leading=None)
c.drawCentredString(415, 395, str(hospital))
c.showPage()
c.save()
import_data(df)
</code></pre>
<p>Thanks in advance!</p>
|
<p>IIUC, you could do something like</p>
<pre><code>def import_data(df):
for hospital, hosp_df in df.groupby("Hospital"):
pdf_file_name = hospital + '.pdf'
generate_report(hospital, pdf_file_name)
df = pd.DataFrame({'Hospital':['A','B'], 'Other': [1,2]})
import_data(df)
</code></pre>
<p>This produces two files for me, one called <code>A.pdf</code> and the second called <code>B.pdf</code>, each of which say "Report / This Report is For: / A" (or B).</p>
<p>At the moment we're not doing anything with <code>hosp_df</code>, which looks like</p>
<pre><code>A
Hospital Other
0 A 1
</code></pre>
<p>and</p>
<pre><code>B
Hospital Other
1 B 2
</code></pre>
<p>but you can pass <code>hosp_df</code> into <code>generate_report</code> as well and do anything you want with that hospital-specific data.</p>
|
python|python-3.x|pandas|reportlab
| 1 |
1,907,337 | 66,001,273 |
How can a child class access its parent attributes without the "parent.attrib" syntax in Django?
|
<p>I'm totally confused
in Django I can create a child class which is PostAdmin(admin.ModelAdmin) with "admin.ModelAdmin" as its parent and assign a tuple to the "list_display"(tip: list_display is an attribute of admin.ModelAdmin class) inside the PostAdmin without writing "admin.ModelAdmin.list_display"...while in python to address a parent class's attribute one needs to use the "parent.attrib" syntax
and the fact is when I try admin.ModelAdmin.list_display it gives me errors!</p>
<p>here is the code in my "admin.py":</p>
<pre><code>from django.contrib import admin
# Register your models here.
from blog.models import post
class PostAdmin(admin.ModelAdmin):
admin.ModelAdmin.list_display= ('title','publish', 'status')
admin.site.register(post,PostAdmin)
</code></pre>
<p>what am I missing?
I've searched a lot about python inheritance and couldn't understand the way the inheritance works in here...to be exact, <strong>How the child class (PostAdmin) assigns the "('title','publish', 'status')" to its parent(ModelAdmin)?
how does it get there?</strong></p>
<p>here are some parts of admin.ModelAdmin codes(which is made by Django and located in options.py) that I found by going to ModelAdmin's definition</p>
<p>the first time <strong>list_display</strong> is used in options.py (where ModelAdmin is defined)</p>
<pre><code>class BaseModelAdmin(metaclass=forms.MediaDefiningClass):
#...
def get_sortable_by(self, request):
"""Hook for specifying which fields can be sorted in the changelist."""
return self.sortable_by if self.sortable_by is not None else self.get_list_display(request)
"""Encapsulate all admin options and functionality for a given model."""
#....
</code></pre>
<p>second encounter with <strong>list_display</strong></p>
<pre><code>class ModelAdmin(BaseModelAdmin):
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
#.....etc
</code></pre>
<p>third encounter with <strong>list_display</strong></p>
<pre><code>def get_changelist_instance(self, request):
"""
Return a `ChangeList` instance based on `request`. May raise
`IncorrectLookupParameters`.
"""
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
# Add the action checkboxes if any actions are available.
if self.get_actions(request):
list_display = ['action_checkbox', *list_display]
sortable_by = self.get_sortable_by(request)
ChangeList = self.get_changelist(request)
return ChangeList(
request,
self.model,
list_display,
list_display_links,
self.get_list_filter(request),
self.date_hierarchy,
self.get_search_fields(request),
self.get_list_select_related(request),
self.list_per_page,
self.list_max_show_all,
self.list_editable,
self,
sortable_by,
)
</code></pre>
<p>fourth encounter</p>
<pre><code> def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
return self.list_display
def get_list_display_links(self, request, list_display):
"""
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
"""
if self.list_display_links or self.list_display_links is None or not list_display:
return self.list_display_links
else:
# Use only the first item in list_display as link
return list(list_display)[:1]
</code></pre>
|
<p>You are doing it the wrong way.</p>
<pre class="lang-py prettyprint-override"><code>from django.contrib import admin
# Register your models here.
from blog.models import post
class PostAdmin(admin.ModelAdmin):
list_display= ('title','publish', 'status') ### Set the attribute on this class, not on the base class.
admin.site.register(post, PostAdmin)
</code></pre>
|
python|django|inheritance|django-models|scope
| 0 |
1,907,338 | 16,106,346 |
Python Converting Characters from Unicode to HTML
|
<p>Hey guys I am trying to convert this in python 2.7.3:</p>
<pre><code>the+c\xf8\xf8n
</code></pre>
<p>to the html string:</p>
<pre><code>the+c%C3%B8%C3%B8n
</code></pre>
<p>It was original the <code>c\xf8\xf8n</code> but I did use a replace to use a + instead of the space.</p>
<p>I'm not entirely sure what convention the latter is I would use string replace but the convention changes by the different characters.. </p>
<p>Thoughts? Thanks guys</p>
|
<p>You are <em>URL</em> encoding, not HTML. Use <code>urllib.quote</code>:</p>
<pre><code>from urllib import quote
</code></pre>
<p>but make sure you encode to <code>UTF-8</code> first:</p>
<pre><code>quote(inputstring.encode('utf8'))
</code></pre>
<p>This will quote the <code>+</code> explicitly; if you meant that to be a space character, you need to mark that as safe:</p>
<pre><code>quote(inputstring.encode('utf8'), '+')
</code></pre>
<p>The latter form gives:</p>
<pre><code>>>> quote(inputstring.encode('utf8'), '+')
'the+c%C3%B8%C3%B8n'
</code></pre>
|
python|python-2.7
| 1 |
1,907,339 | 31,773,975 |
Instagram-API with python
|
<p>I recently started using the instagram-API in python. I built successfully some programs, and then I searched a way to create an Instagram account through the api - but I couldn't find.
Is there a way to create an instargram account from the api (python), and then send the login details (user,pass) and the token, secret token to the user?
Thanks, and have a nice day. </p>
|
<p>Check out the <a href="https://instagram.com/developer/" rel="nofollow">documentation</a> and you'll quickly discern that their API isn't designed to allow for third-party, programmatic user account creation. </p>
<p>The only way to create an account with Instagram is by downloading their iOS or Android app and following the account creation process that way. </p>
<p>From an end user perspective, what would be the use case for granting a third party application all the sensitive personal data required to create an Instagram account? Because an end user can only upload media to their account via the app, why wouldn't someone just want to sign up when they download the app? </p>
|
python|api|instagram|instagram-api
| 1 |
1,907,340 | 52,537,311 |
How to use a conditional decorator in python?
|
<p>In trying to understand a conditional decorator in python I came upon <a href="https://stackoverflow.com/questions/10724854/how-to-do-a-conditional-decorator-in-python-2-6/10724898#10724898">this example</a>. The accepted answer for that question explains how to <em>define</em> a conditional decorator, but not how to <em>use</em> it. </p>
<p>The example code is as follows:</p>
<pre><code>class conditional_decorator(object):
def __init__(self, dec, condition):
self.decorator = dec
self.condition = condition
def __call__(self, func):
if not self.condition:
# Return the function unchanged, not decorated.
return func
return self.decorator(func)
@conditional_decorator(timeit, doing_performance_analysis)
def foo():
time.sleep(2)
</code></pre>
<p>But how to use it? I tried the following calls of <code>foo</code> like this:</p>
<pre><code>doing_performance_analysis=False
foo()
doing_performance_analysis=True
foo()
</code></pre>
<p>but I got the following errors:</p>
<pre><code>Traceback (most recent call last):
File "tester.py", line 18, in <module>
@conditional_decorator(timeit, doing_performance_analysis)
NameError: name 'doing_performance_analysis' is not defined
</code></pre>
<p>So how does it work correctly?</p>
|
<p>If you use the python 3 wrapt module you can set an enabled flag to switch your decorator on or off. For debug reasons i try to paste a specific parameter given to a function to the clipboard (using pandas). This is done by the following decorator.</p>
<pre><code>CLIPTRACE = True
def traceClipboard(fieldname):
""" give fieldname of the functions formal parameter
to get value dumped to clipboard
also use wrapt parameter to disable if cliptrace is not set
"""
@wrapt.decorator(enabled=CLIPTRACE)
def wrapper(wrapped, instance, args, kwargs):
args_list = inspect.getfullargspec(wrapped)[0]
if "self" in args_list:
args_list.pop(0)
if fieldname in args_list:
pyperclip.copy(args[args_list.index(fieldname)])
if fieldname in kwargs.keys():
pyperclip.copy(kwargs.get(fieldname))
return wrapped(*args, **kwargs)
return wrapper
</code></pre>
<p>then use it for decorating a function of my session class:</p>
<pre><code> @traceClipboard("url")
def _get(self, url, odata=None):
"""single _get request..."""
</code></pre>
<p>as long as CLIPTRACE is True the value of the parameter "url" is copied to clipboard, in productive environment CLIPTRACE is False and no clipboard copy is performed.</p>
|
python
| 0 |
1,907,341 | 40,693,727 |
Getting usable data in a dictionary from the string output of SOX in Python
|
<p>The opensource software SOX is a command line interface tool which does things with audio files. It has a stat function which returns data related to an audio file. This data comes back as a string - a string which is not terribly easy to use.</p>
<p>Examples of the strings returned by SOX are below.</p>
<p>\nInput File : 'E:\path\to\file\filename.wav'\nChannels : 1\nSample Rate : 176400\nPrecision : 16-bit\nDuration : 00:00:30.00 = 5292001 samples ~ 2250 CDDA sectors\nFile Size : 10.6M\nBit Rate : 2.82M\nSample Encoding: 16-bit Signed Integer PCM\n"</p>
<p>and...</p>
<p>Samples read: 5292001\nLength (seconds): 30.000006\nScaled by: 2147483647.0\nMaximum amplitude: 0.705475\nMinimum amplitude: -0.705475\nMidline amplitude: 0.000000\nMean norm: 0.449045\nMean amplitude: 0.000153\nRMS amplitude: 0.498788\nMaximum delta: 1.410950\nMinimum delta: 0.000000\nMean delta: 0.571030\nRMS delta: 0.704606\nRough frequency: 39659\nVolume adjustment: 1.417\n\nTry: -t raw -e mu-law -b 8 '</p>
<p>The number of characters a value may have can change from one file to another and some files will actually miss certain values altogether. </p>
<p>How can I get a simple dictionary of values from these strings?</p>
|
<p>You could <code>split</code> on <code>'\n'</code> and then feed pairs to the <code>dict</code> constructor by splitting on <code>':'</code>:</p>
<p>Given your second sample string:</p>
<pre><code>>>> s = """Samples read: 5292001\nLength (seconds): 30.000006\nScaled by: 2147483647.0\nMaximum amplitude: 0.705475\nMinimum amplitude: -0.705475\nMidline amplitude: 0.000000\nMean norm: 0.449045\nMean amplitude: 0.000153\nRMS amplitude: 0.498788\nMaximum delta: 1.410950\nMinimum delta: 0.000000\nMean delta: 0.571030\nRMS delta: 0.704606\nRough frequency: 39659\nVolume adjustment: 1.417\n\nTry: -t raw -e mu-law -b 8 '"""
</code></pre>
<p>A dictionary can be created by:</p>
<pre><code>>>> dict(r.strip().split(':', 1) for r in s.split('\n') if r)
</code></pre>
<p>where <code>if r</code> takes care to filter out empty lines and the <code>1</code> in split takes care to perform <em>only one split</em> (so strings like <code>Duration</code> that have many <code>":"</code> won't get split up multiple times).</p>
<p>This yields:</p>
<pre><code>{'Length (seconds)': ' 30.000006',
'Maximum amplitude': ' 0.705475',
'Maximum delta': ' 1.410950',
'Mean amplitude': ' 0.000153',
'Mean delta': ' 0.571030',
'Mean norm': ' 0.449045',
'Midline amplitude': ' 0.000000',
'Minimum amplitude': ' -0.705475',
'Minimum delta': ' 0.000000',
'RMS amplitude': ' 0.498788',
'RMS delta': ' 0.704606',
'Rough frequency': ' 39659',
'Samples read': ' 5292001',
'Scaled by': ' 2147483647.0',
'Try': " -t raw -e mu-law -b 8 '",
'Volume adjustment': ' 1.417'}
</code></pre>
<p>Similarly, with the first sample string:</p>
<pre><code>>>> s = """\nInput File : 'E:\\path\\to\\file\\filename.wav'\nChannels : 1\nSample Rate : 176400\nPrecision : 16-bit\nDuration : 00:00:30.00 = 5292001 samples ~ 2250 CDDA sectors\nFile Size : 10.6M\nBit Rate : 2.82M\nSample Encoding: 16-bit Signed Integer PCM\n"""
>>> dict(r.strip().split(':', 1) for r in s.strip().split('\n') if r)
{'Bit Rate ': ' 2.82M',
'Channels ': ' 1',
'Duration ': ' 00:00:30.00 = 5292001 samples ~ 2250 CDDA sectors',
'File Size ': ' 10.6M',
'Input File ': " 'E:\\path\\to\\file\\filename.wav'",
'Precision ': ' 16-bit',
'Sample Encoding': ' 16-bit Signed Integer PCM',
'Sample Rate ': ' 176400'}
</code></pre>
|
python|regex|string|python-3.x|dictionary
| 1 |
1,907,342 | 40,714,700 |
frequency table as a data frame in pandas
|
<p>I'm looking for a more efficient way to do this as I am new to python. I want a data frame of the cyl value and the counts - ideally without having to go and do the rename column. I'm coming from R.</p>
<p>What is happening is 'cyl' is the index if i don't use the to-frame.reset-index piece of code and when I do use the reset-index code it becomes a column called 'index' - which is really the cyl values, while the the 2nd column 'cyl' is really the frequency counts..</p>
<pre><code>import pandas as pd
new_df = pd.value_counts(mtcars.cyl).to_frame().reset_index()
new_df.columns = ['cyl', 'frequency']
</code></pre>
|
<p>I think you can omit <code>to_frame()</code>:</p>
<pre><code>new_df = pd.value_counts(mtcars.cyl).reset_index()
new_df.columns = ['cyl', 'frequency']
</code></pre>
<p>Sample:</p>
<pre><code>mtcars = pd.DataFrame({'cyl':[1, 2, 2, 4, 4]})
print (mtcars)
cyl
0 1
1 2
2 2
3 4
4 4
new_df = pd.value_counts(mtcars.cyl).reset_index()
new_df.columns = ['cyl', 'frequency']
print (new_df)
cyl frequency
0 4 2
1 2 2
2 1 1
</code></pre>
|
python|pandas|frequency
| 1 |
1,907,343 | 40,447,068 |
Run a script which is in a django app under management folder in command folder
|
<p>I have a django project and inside I have an app. Inside this app I created a management folder, inside this one I create a commands folder, and inside the last one I put my script with the <strong>init</strong>.py file too. My question is how I can run the script, because if I'm in the django project folder (where is manage.py file) and I execute the line:</p>
<pre><code>python manage.py myscript.py
</code></pre>
<p>the terminal is displaying this:</p>
<pre><code>Unknown command: 'myscript.py'
</code></pre>
|
<p>It should be <code>python manage.py myscript</code>, and if everything else is correct it will work.</p>
<p>Note that management command is not just a python script. It must implement <code>class Command</code> inside. (<a href="https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/" rel="nofollow noreferrer">Tutorial</a>)</p>
|
python|django
| 0 |
1,907,344 | 9,974,753 |
Free memory for multiprocessing pickled methods
|
<p>I'm using the first answer to this question</p>
<p><a href="https://stackoverflow.com/questions/1798450/overcoming-pythons-limitations-regarding-instance-methods">Overcoming Python's limitations regarding instance methods</a></p>
<p>to be able to use multiprocess module on methods of one of my own classes.</p>
<p>As an example let's say that I have the following:</p>
<pre><code>from multiprocessing import Pool
def myParallelFunc(my_list, a, b, inst):
# do something
return True
def myFunc:
# instantiate custom class
my_instance = MyObject()
pool = Pool()
pool.map(functools.partial(myParallelFunc, a=5, b=7, inst=my_instance), my_list)
# SOLUTION!!!
pool.close()
</code></pre>
<p>Now I have another program that calls myFunc let's say 100 times.
Every time I call myFunc some memory is occupied and never freed.
Is there a way to explicitly free it?</p>
|
<p>You are creating a new Pool at every call to myFunc. It is not deleted automatically when myFunc exits, because the child processes and related threads remain.</p>
<p>Create a Pool, keep it around for those 100 calls, then .close it</p>
|
python|methods|multiprocessing|pickle
| 1 |
1,907,345 | 1,491,957 |
Testing for an empty iterator in a Python for... loop
|
<p>The code below is based on <a href="http://code.activestate.com/recipes/413614/" rel="nofollow noreferrer">this recipe</a>. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways:</p>
<ol>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is skipped, rather than being selected on the next iteration.</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are less than two items left in the iterator, <strong>my_func()</strong> returns None.</li>
</ol>
<p>How can I ensure that:</p>
<ul>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is <em>not</em> skipped?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there is one item left in the iterator, <strong>my_func()</strong> prints it and calls <strong>get_yes_no_answer()</strong>?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are no items left in the iterator, the <strong>except StopIteration</strong> clause is triggered?</li>
</ul>
<p>Here's the code:</p>
<pre><code>def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
print "No choices. Exiting..."
sys.exit()
else:
# Show choices to the user. For each one, ask user for a yes/no response. If
# choice accepted, return a result. Otherwise show user next choice. If no
# choices accepted by user, quit.
for choice in choice_iterator:
print choice.group()
# get_yes_no_answer() returns True or False depending on user response.
if get_yes_no_answer():
return choice
else:
# Check if iterator is empty. If so, quit; if not, do something else.
try:
next_choice = choice_iterator.next()
except StopIteration:
print "No matches. Exiting..."
sys.exit()
else:
choice_iterator = itertools.chain([next_choice], choice_iterator)
</code></pre>
|
<p>why are you doing it this way at all? why not just:</p>
<pre><code>def get_choice(pattern, inpt):
choices = pattern.finditer(inpt, re.M)
if not choices:
sys.exit('No choices')
for choice in choices:
print(choice.group(0))
if get_yes_no_answer():
return choice
sys.exit('No matches')
</code></pre>
<p>I don't know what your is the length of your input but I doubt it's worth the trouble.</p>
|
python|exception|iterator|conditional
| 4 |
1,907,346 | 1,687,344 |
How do you generate random unique identifiers in a multi process and multi thread environment?
|
<p>Every solution I come up with is not thread save.</p>
<pre><code>def uuid(cls,db):
u = hexlify(os.urandom(8)).decode('ascii')
db.execute('SELECT sid FROM sessions WHERE sid=?',(u,))
if db.fetch(): u=cls.uuid(db)
else: db.execute('INSERT INTO sessions (sid) VALUES (?)',(u,))
return u
</code></pre>
|
<pre><code>import os, threading, Queue
def idmaker(aqueue):
while True:
u = hexlify(os.urandom(8)).decode('ascii')
aqueue.put(u)
idqueue = Queue.Queue(2)
t = threading.Thread(target=idmaker, args=(idqueue,))
t.daemon = True
t.start()
def idgetter():
return idqueue.get()
</code></pre>
<p>Queue is often the best way to synchronize threads in Python -- that's frequent enough that when designing a multi-thread system your first thought should be "how could I best do this with Queues". The underlying idea is to dedicate a thread to entirely "own" a shared resource or subsystem, and have all other "worker" threads access the resource only by gets and/or puts on Queues used by that dedicated thread (Queue is intrinsically threadsafe).</p>
<p>Here, we make an <code>idqueue</code> with a length of only 2 (we don't want the id generation to go wild, making a lot of ids beforehand, which wastes memory and exhausts the entropy pool -- not sure if <code>2</code> is optimal, but the sweet spot is definitely going to be a pretty small integer;-), so the id generator thread will block when trying to add the third one, and wait until some space opens in the queue. <code>idgetter</code> (which could also be simply defined by a top-level assignment, <code>idgetter = idqueue.get</code>) will normally find an id already there and waiting (and make space for the next one!) -- if not, it intrinsically blocks and waits, waking up as soon as the id generator has placed a new id in the queue.</p>
|
python|sql|mod-wsgi
| 5 |
1,907,347 | 63,038,582 |
Scraping paginated data loaded with Javascript
|
<p>I am trying to use selenium and beautifulsoup to scrape videos off a website. The videos are loaded when the 'videos' tab is clicked (via JS I guess). When the videos are loaded, there is also the pagination where videos on each page is loaded on click (via JS I guess).</p>
<p>Here is how it looks</p>
<p><a href="https://i.stack.imgur.com/bT8MS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bT8MS.png" alt="enter image description here" /></a></p>
<p>When I inspect element, here is what I get</p>
<p><a href="https://i.stack.imgur.com/mRIfv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mRIfv.png" alt="enter image description here" /></a></p>
<p>My issue is I can't seem to get all videos across all pages, I can only get the first page. Here is my code,</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as soup
import random
import time
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.add_argument('--headless')
seconds = 5 + (random.random() * 5)
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.implicitly_wait(30)
driver.get("https://")
time.sleep(seconds)
time.sleep(seconds)
for i in range(1):
element = driver.find_element_by_id("tab-videos")
driver.execute_script("arguments[0].click();", element)
time.sleep(seconds)
time.sleep(seconds)
html = driver.page_source
page_soup = soup(html, "html.parser")
containers = page_soup.findAll("div", {"id": "tabVideos"})
for videos in containers:
main_videos = videos.find_all("div", {"class":"thumb-block tbm-init-ok"})
print(main_videos)
driver.quit()
</code></pre>
<p>Please what am I missing here?</p>
|
<p>The content is loaded from URL <code>'https://www.x***s.com/amateur-channels/ajibola_elizabeth/videos/best/{page}'</code> where page goes from <code>0</code>.</p>
<p>This script will print all video URLs:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url = 'https://www.x***s.com/amateur-channels/ajibola_elizabeth/videos/best/{page}'
page = 0
while True:
soup = BeautifulSoup(requests.get(url.format(page=page)).content, 'html.parser')
for video in soup.select('div[id^="video_"] .title a'):
u = video['href'].rsplit('/', maxsplit=2)
print('https://www.x***s.com/video' + u[-2] + '/' + u[-1])
next_page = soup.select_one('a.next-page')
if not next_page:
break
page += 1
</code></pre>
|
python|python-3.x|selenium|selenium-webdriver|beautifulsoup
| 3 |
1,907,348 | 28,209,241 |
What is the purpose of a struct template without definition?
|
<p>Below is a snippet from Boost.Python's <a href="http://www.boost.org/doc/libs/1_57_0/boost/python/handle.hpp" rel="nofollow">source code</a>:</p>
<pre><code>template <class T> struct null_ok; // how's it working?
template <class T>
inline null_ok<T>* allow_null(T* p)
{
return (null_ok<T>*)p;
}
</code></pre>
<p>It's wired that there's no definition for forward declared struct <code>null_ok</code>, and <code>null_ok</code> has nothing to do with the template argument <code>T</code>.</p>
<p>In <a href="https://wiki.python.org/moin/boost.python/handle" rel="nofollow">Python wiki</a>, some hints given that:</p>
<blockquote>
<p><strong>handle<> y(null_ok(x))</strong> allows y to become NULL</p>
<p><strong>handle<> y(x)</strong>, where x is not the result of null_ok, never results in a NULL y. An exception will be thrown if x is NULL</p>
</blockquote>
<p>I can't figure out how the declaration (without definition) of a struct template, <code>null_ok</code>, could achieve the purpose as stated above?</p>
|
<p>The point is to encode "it's ok for this pointer to be null" along with the original type in the type of the pointer itself.</p>
<p>Then, the function templates accepting the pointer can be overloaded to recognize <code>null_ok<T>*</code> pointers, and not error out on null pointers (while converting it back to a <code>T*</code>).</p>
<p>You do not need a definition for <code>null_ok</code>, since you can have pointers to incomplete types, and it prevents people from accidentally writing something like <code>null_ok<int> a;</code>.</p>
|
c++|templates|metaprogramming|boost-python
| 5 |
1,907,349 | 44,062,371 |
How to use itertools product with a huge data
|
<p>I would like to make a list of 81-tuple by using three elements, namely 1,2,3 in python.</p>
<p>I tried to find a solution, and then I found these useful links:</p>
<p><a href="https://stackoverflow.com/questions/23833780/how-to-use-itertools-to-compute-all-combinations-with-repeating-elements">How to use itertools to compute all combinations with repeating elements?</a></p>
<p>and</p>
<p><a href="https://stackoverflow.com/questions/10234599/which-itertools-generator-doesnt-skip-any-combinations">Which itertools generator doesn't skip any combinations?</a></p>
<p>According to the above links, I should do the following</p>
<pre><code>import itertools
list = []
for p in itertools.product(range(1, 3 + 1), repeat=81):
list.append(p)
print(list)
</code></pre>
<p>But, my computer hangs. I think there is too much data in the list.</p>
<p>I want to know whether there is a command that prints only first 100-elements in list or the 101th to 200th in the list.</p>
|
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.islice" rel="nofollow noreferrer"><code>itertools.islice</code></a>:</p>
<pre><code>p = itertools.product(range(1, 3 + 1), repeat=81)
s = itertools.islice(p, 101, 200)
print(list(s))
</code></pre>
<p>This will, however, iterate through all the elements until it reaches the starting index of the slice. So for ranges towards the end of an iterator with a gazillion elements (yours has <code>3**81 = 443426488243037769948249630619149892803</code> or in other words: too many to process let alone store), this will run into similar problems.</p>
<p>For those later ranges, you would have to calculate the n-th element by hand and generate successors from there... See <a href="https://stackoverflow.com/questions/9944915/how-to-select-specific-item-from-cartesian-product-without-calculating-every-oth">How to select specific item from cartesian product without calculating every other item</a> for some inspiration.</p>
|
python|list|product|itertools
| 3 |
1,907,350 | 32,689,118 |
Python and Pandas: UnicodeDecodeError: 'ascii' codec can't decode byte
|
<p>After using Pandas to read a json object into a <code>Pandas.DataFrame</code>, we only want to <code>print</code> the first year in each pandas row. Eg: if we have <code>2013-2014(2015)</code>, we want to print <code>2013</code></p>
<p><strong>Full code <a href="https://gist.github.com/anonymous/9e7b4932e9adf8e6f1fa" rel="nofollow">(here)</a></strong></p>
<pre><code>x = '{"0":"1985\\u2013present","1":"1985\\u2013present",......}'
a = pd.read_json(x, typ='series')
for i, row in a.iteritems():
print row.split('-')[0].split('—')[0].split('(')[0]
</code></pre>
<p>the following error occurs:</p>
<pre><code>---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-1333-d8ef23860c53> in <module>()
1 for i, row in a.iteritems():
----> 2 print row.split('-')[0].split('—')[0].split('(')[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
</code></pre>
<p>Why is this happening? How can we fix the problem?</p>
|
<p>Your json data strings are unicode string, which you can see for example by just printing one of the values:</p>
<pre><code>In: a[0]
Out: u'1985\u2013present'
</code></pre>
<p>Now you try to split the string at the unicode <code>\u2031</code> (EN DASH), but the string you give to <code>split</code> is no unicode string (therefore the error <code>'ascii' codec can't decode byte 0xe2</code> - the EN DASH is no ASCII character). </p>
<p>To make your example working, you could use:</p>
<pre><code>for i, row in a.iteritems():
print row.split('-')[0].split(u'—')[0].split('(')[0]
</code></pre>
<p>Notice the <code>u</code> in front of the uncode dash. You could also write <code>u'\u2013'</code> to split the string.</p>
<p>For details on unicode in Python, see <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">https://docs.python.org/2/howto/unicode.html</a></p>
|
python|json|pandas|encoding|python-2.x
| 1 |
1,907,351 | 34,577,606 |
regex python variable
|
<p>I know there is a lot of questions in here about "regex python variable" but none seems to work for me. I have been looking for two hours but I did not find any answer to this question in specific.</p>
<p>Here is my problem: I would like to search for words of <code>[ERROR]</code> and <code>[WARNING]</code>. As you may know the <code>/var/log/mysql/error.log</code> has a standard file, which basically goes like this <code>year-month-day hour:minute</code>. </p>
<p>Example:</p>
<pre><code>2016-01-03 13:19:40 1242 [Warning] Buffered warning: Changed limits: table_open_cache: 431 (requested 2000)
2016-01-03 13:19:40 1242 [Warning] Using unique option prefix myisam-recover instead of myisam-recover-options is deprecated and will be removed in a future release. Please use the full name instead.
2016-01-03 13:19:40 1242 [Note] Plugin 'FEDERATED' is disabled.
</code></pre>
<p>I have this script in which tries to do the job:</p>
<pre><code>#!/usr/bin/python
import re
import time
import datetime
from datetime import datetime
i = datetime.now()
dia = i.day
mes_abreviado = i.strftime('%b')
hora = i.strftime('%H')
minuto = i.strftime('%M')
ano = i.strftime('%Y')
mes_ano_num = i.strftime('%m')
dia_00 = i.strftime('%d')
#Data/Hora especifica "syslog"
date = '%s %d %s:%s'% (mes_abreviado, dia, hora, minuto)
#Data/Hora especifica do ficheiro "error.log"
mysql_time = '%s-%s-%s %s:%s'% (ano, mes_ano_num, dia_00, hora, minuto)
print mysql_time
words = '\b\[ERROR\]\b|\b\[WARNING\]\b'
print words
file = open("/var/log/mysql/error.log", "rb")
for line in file:
if re.findall(r'{0}'.format(words), line):
# if re.findall(r'{0}'.format(mysql_time), line):
# print "aqui"
print line
file.close()
</code></pre>
<p>I have to get the current year, month, day, hour and minute to search for it in <code>re.findall</code> function. The problem is: I need to place them in a variable and use them in the regex but it doesn't seem to work. </p>
<p>Here's the output:</p>
<pre><code>2016-01-03 14:21
\[ERROR\\[WARNING\]
</code></pre>
<p>As you can see <code>words</code> is not printing <code>\b</code> and it's messing up with the regex.
I have tried using <code>words = re.compile(words)</code>, <code>words = re.compile(r'\b\[ERROR\]\b|\b\[WARNING\]\b')</code> and <code>re.findall(r'{0}'.format(words)</code>. From what it looks like the regex is perfectly fine.</p>
<p>There's a lot of comments in the code which is problems I will solve latter on. If there is something missing let me know so I can edit this answer. Thank you in advance.</p>
|
<p>I don't know why you are using the \b in your regexp - it doesn't make sense when the word you are looking for is already delimited by [ and ]. According to the docs \b matches a zero-length string at the edges of a-zA-Z_, so your pattern could match 'a[WARNING]b'. Also I couldn't get [WARNING] in the regexp to match [Warning] in the logfile (like the sample data you provided) without ensuring case-insensitivity in the regex by adding (?i) to it.</p>
<p>Change the regex to: <code>words = r'(?i)\[ERROR\]|\[WARNING\]'</code> and it should start working.</p>
<p>Once you have the Error/Warning matching working, you can add the date string matching into your regexp quite easily.</p>
|
python|regex
| 1 |
1,907,352 | 12,166,368 |
django request.session.get("name", False) - What does this code mean?
|
<p>I am using the following code : </p>
<pre><code>if request.session.get("name",False):
</code></pre>
<p>Can anyone please tell me what the above code does? What I assume is, if there is "name" in session it returns True, otherwise, it returns False. I'm confused with my code so I posted this question here. </p>
<p>Thanks.</p>
|
<p>If <code>session</code> has a key in it with the value <code>"name"</code> it returns <em>the value associated with that key</em> (which might well be <code>False</code>), otherwise (if there is no key named "name") it returns <code>False</code>. </p>
<p>The <code>session</code> is a dictionary-like type so the best place to get documenation on the <a href="http://docs.python.org/library/stdtypes.html#dict.get"><code>get</code> method</a> is in the Python docs for the standard library. The short of the matter is that <code>get</code> is shorthand for the following:</p>
<pre><code>if "name" in request.session:
result = request.session["name"]
else:
result = False
if result:
# Do something
</code></pre>
|
python|django
| 18 |
1,907,353 | 41,747,870 |
Set an optimization using LMFIT and Parameters class with condition to be checked
|
<p>How to use ExpressionModel in LMFIT to fit a conditional model that can be represented as:</p>
<pre><code>from lmfit.models import ExpressionModel
# read(xdata and ydata) here
if xdata < some_parameter_value:
model = ExpressionModel('expression1')
else:
model = ExpressionModel('expression2')
</code></pre>
<p>How to write this conditional model as one model (global_model) and pass it to the fit method</p>
<pre><code>results = global_model.fit(y, x = x, parameters_dictionary)
</code></pre>
<p>some_parameter_value: is a member of parameters_dictionary which is created using Parameters class</p>
|
<p>lmfit Models are defined independent of the data and cannot be used for "part of the data".</p>
<p>Perhaps you can rewrite the expression for the model as:</p>
<pre><code> expr1 if x < x0 else expr2
</code></pre>
<p>Otherwise, I think you'll have to write a custom Model that tests the condition and does a different calculation based on that condition.</p>
|
python|curve-fitting|lmfit
| 0 |
1,907,354 | 47,088,992 |
How to convert from IPv6 to IPv4, and from there to an integer format
|
<p>How do I convert an IPv6 address to an IPv4 address, and likewise how do I then parse the IPv4 address into a set of integers?</p>
<p>I have :</p>
<blockquote>
<p>a = ' ff06::c3'</p>
</blockquote>
<p>I would like:</p>
<blockquote>
<p>4278583296.0.0.195 </p>
</blockquote>
<p>And from there I would like to get:</p>
<blockquote>
<p>a1 = 4278583296<br>
a2 = 0<br>
a3 = 0<br>
a4 = 195 </p>
</blockquote>
|
<p>I'm not sure why you'd ever want such a thing, since it doesn't correspond in any way to how IP addresses actually work, but you can use Python3.3's <code>ipaddress</code> module to easily parse your string. If you aren't on Python3.3, you'll have to write your own parser for IPv6 addresses that will expand them to their exploded form (<code>"0123:4567:89ab:cdef:fedc:ba98:7654:3210"</code>)</p>
<pre><code>import ipaddress
myIP = ipaddress.ip_address('ff06::c3')
</code></pre>
<p>then convert to string with <code>IPv6Address.exploded</code> and grab each hextet using <code>str.split(":")</code></p>
<pre><code>hextets = myIP.exploded.split(":")
</code></pre>
<p>then map each pair of hextets into one 32-bit group and parse to int with <code>int(grp, base=16)</code></p>
<pre><code>import itertools
# from itertools recipes
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
new_groups = [int(a+b, base=16) for (a, b) in grouper(hextets, 2)]
# N.B. that a+b here is string concatenation, not addition
</code></pre>
<p>Then you can use <code>str.join</code> and <code>map</code> to put it all together into one dotted "IPv4" address</p>
<pre><code>ipv4ish = '.'.join(map(str, new_groups))
</code></pre>
<p>and tuple unpacking to get each separate argument</p>
<pre><code>a1, a2, a3, a4 = new_groups
</code></pre>
|
python|python-2.7|ipv6|ipv4
| 1 |
1,907,355 | 47,361,250 |
Pandas add column with formula using value of other column
|
<p>I have a existing df. I want to extend it with a column RSI.
RSI is calculated using a function rsi_func(close) which returns a number. I've tried the official <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer">pandas doc</a> see coding 2) and 3) and <a href="https://stackoverflow.com/questions/39564372/create-new-column-in-pandas-based-on-value-of-another-column">Stackoverflow answer</a>, see coding 7) and many other examples, I can't get it to work.
I've tried, without the numbering of course:</p>
<pre><code> 1) df['RSI'] = rsi_func(df['close'])
2) df.assign(RSI=lambda x: rsi_func(close))
3a) rsi = rsi_func(df['close'])
3b) print(rsi)
3c) df.assign(RSI=rsi)
4) df.assign(RSI=rsi_func(df['close']))
5) df.assign(RSI=lambda x: rsi_func(close))
6) df['RSI'] = df.apply(lambda x: rsi_func(x['close']))
7) df['RSI'] = df['close'].apply(rsi_func)
</code></pre>
<p>When I try 3a+b+c then a python list with RSI values is printed. But 3c doesn't append RSI to df. How can I create RSI with the return of rsi_func(close) and append it to df?</p>
|
<p>You can use map with the lambda expression</p>
<pre><code>df['RSI'] = df['close'].map(lambda x: rsi_func(x))
</code></pre>
<p>Test using basic dataframe:</p>
<pre><code>def rsi_func(close):
return close /10
df['RSI'] = df['close'].map(lambda x: rsi_func(x))
df
Out[11]:
close RSI
0 20.02 2.002
1 20.04 2.004
2 20.05 2.005
</code></pre>
|
pandas
| 2 |
1,907,356 | 11,530,580 |
Python - how to reference one object to another
|
<p>more basic questions i'm struggling with...</p>
<p>Give the basic code below... how does the person object get the address "attached" to it. </p>
<pre><code>class Person(object):
def __init__(self, fn, ln):
self.uid = Id_Class.new_id("Person")
self.f_name = fn
self.l_name = ln
class Address(object):
def __init__(self, st, sub):
self.uid = Id_Class.new_id("Address")
self.street = st
self.suburb = sub
s = Person('John', 'Doe')
hm = Address('Queen St.', 'Sydney')
</code></pre>
|
<p>Try:</p>
<pre><code>class Person(object):
def __init__(self, fn, ln, address):
self.uid = Id_Class.new_id("Person")
self.f_name = fn
self.l_name = ln
self.address = address
class Address(object):
def __init__(self, st, sub):
self.uid = Id_Class.new_id("Address")
self.street = st
self.suburb = sub
hm = Address('Queen St.', 'Sydney')
s = Person('John', 'Doe', hm)
</code></pre>
|
python|class
| 9 |
1,907,357 | 33,524,704 |
Changing taiga-back default port (8000)
|
<p>I want to change the default port of taiga-back api which is 8000. I have another daemon listening to that port that is already in production and I can't change its port.</p>
|
<p>I found the solution. It is done by specifying the port when when executing runserver</p>
<pre><code>python manage.py runserver 0.0.0.0:8001
</code></pre>
|
python|api
| 3 |
1,907,358 | 33,949,968 |
Tensorflow multi-class ML model issues
|
<p>I have been trying to get tensor flow working on a multi-class kaggle problem. Basically the data consists of 6 features which I have converted to all numeric observations. The goal is to use these 6 features to predict a trip type, where there are 38 different trip types. I have been trying to use tensorflow to predict these trip type classes. The following code is what I have thus far, including what I had used to format the csv file. The code will run, but the output starts off ok for run 1, and then is very poor with the same output for the remainder of the runs. The following is the example of the output when it is running:</p>
<pre><code>Run 0,0.268728911877
Run 1,0.0108088823035
Run 2,0.0108088823035
Run 3,0.0108088823035
Run 4,0.0108088823035
Run 5,0.0108088823035
Run 6,0.0108088823035
Run 7,0.0108088823035
Run 8,0.0108088823035
Run 9,0.0108088823035
Run 10,0.0108088823035
Run 11,0.0108088823035
Run 12,0.0108088823035
Run 13,0.0108088823035
Run 14,0.0108088823035
</code></pre>
<p>And the code:</p>
<pre><code>import tensorflow as tf
import numpy as np
from numpy import genfromtxt
import sklearn
import pandas as pd
from sklearn.cross_validation import train_test_split
import sklearn
# function buildWalMartData takes in a csv file, converts to numpy array, splits into training
# and testing, then saves the file to specified target directory
def buildWalmartData():
df = pd.read_csv('/Users/analyticsmachine/Desktop/Kaggle/WallMart_Kaggle/Data/full_train_complete.csv')
df = df.drop('Unnamed: 0', 1) # 1 specifies axis to remove
df_data = np.array(df.drop('TripType', 1).values) # convert to numpy array
df_label = np.array(df['TripType'].values) # convert to numpy array
X_train, X_test, y_train, y_test = train_test_split(df_data, df_label, test_size=0.25, random_state=50)
f = open('/Users/analyticsmachine/Desktop/Kaggle/WallMart_Kaggle/Data/wm-training.csv', 'w')
for i,j in enumerate(X_train):
k = np.append(np.array(y_train[i]), j)
f.write(','.join([str(s) for s in k]) + '\n')
f.close()
f = open('/Users/analyticsmachine/Desktop/Kaggle/WallMart_Kaggle/Data/wm-testing.csv', 'w')
for i,j in enumerate(X_test):
k=np.append(np.array(y_test[i]), j)
f.write(','.join([str(s) for s in k]) + '\n')
f.close()
buildWalmartData()
# function convertOnehot takes in data and converts to tensorflow oneHot
# The corresponding labels in Wallmat TripType are numbers between 1 and 38, describing
# which trip is taken. We have already converted the labels to a one-hot vector, which is a
# vector that is 0 in most dimensions, and 1 in a single dimension. In this case, the nth triptype
# will be represented as a vector which is 1 in the nth dimensions.
def convertOneHot(data):
y = np.array([int(i[0]) for i in data])
y_onehot = [0]*len(y)
for i,j in enumerate(y):
y_onehot[i]=[0]*(y.max()+1)
y_onehot[i][j] = 1
return (y, y_onehot)
# import training data
data = genfromtxt('/Users/analyticsmachine/Desktop/Kaggle/WallMart_Kaggle/Data/wm-training.csv', delimiter=',')
# import testing data
test_data = genfromtxt('/Users/analyticsmachine/Desktop/Kaggle/WallMart_Kaggle/Data/wm-testing.csv', delimiter=',')
x_train = np.array([i[1::] for i in data])
# example output for x_train:
#array([[ 7.06940000e+04, 5.00000000e+00, 7.91005185e+09,
# 1.00000000e+00, 8.00000000e+00, 2.15000000e+02],
# [ 1.54653000e+05, 4.00000000e+00, 5.20001225e+09,
# 1.00000000e+00, 5.00000000e+00, 4.60700000e+03],
# [ 1.86178000e+05, 3.00000000e+00, 4.32136106e+09,
# -1.00000000e+00, 5.00000000e+01, 1.90000000e+03],
y_train, y_train_onehot = convertOneHot(data)
x_test = np.array([ i[1::] for i in test_data])
y_test, y_test_onehot = convertOneHot(test_data)
# exmaple y_test output
#array([ 5, 32, 24, ..., 31, 28, 5])
# and example y_test_onehot:
#[0,...
# 0,
# 0,
# 0,
# 0,
# 0,
# 0,
# 1,
# 0,
# 0,
# 0,
# 0,
# 0]
# A is the number of features, 6 in the wallmart data
# B=38, which is the number of trip types
A = data.shape[1]-1
B = len(y_train_onehot[0])
tf_in = tf.placeholder('float', [None, A]) # features
tf_weight = tf.Variable(tf.zeros([A,B]))
tf_bias = tf.Variable(tf.zeros([B]))
tf_softmax = tf.nn.softmax(tf.matmul(tf_in, tf_weight) + tf_bias)
# training via backpropogation
tf_softmax_correct = tf.placeholder('float', [None, B])
tf_cross_entropy = - tf.reduce_sum(tf_softmax_correct*tf.log(tf_softmax))
# training using tf.train.GradientDescentOptimizer
tf_train_step = tf.train.GradientDescentOptimizer(0.01).minimize(tf_cross_entropy)
# add accuracy nodes
tf_correct_prediction = tf.equal(tf.argmax(tf_softmax,1), tf.argmax(tf_softmax_correct, 1))
tf_accuracy = tf.reduce_mean(tf.cast(tf_correct_prediction, 'float'))
# initialize and run
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
# running the training
for i in range(20):
sess.run(tf_train_step, feed_dict={tf_in: x_train, tf_softmax_correct: y_train_onehot})
# print accuracy
result = sess.run(tf_accuracy, feed_dict={tf_in: x_test, tf_softmax_correct: y_test_onehot})
print "run {},{}".format(i,result)
</code></pre>
<p>Any thoughts regarding what might be going wrong here as to why the runs would degenerate like this would be greatly appreciated. Thanks!</p>
|
<p>If you just want something up and running quickly for Kaggle competition, I would suggest you trying out <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/learn/" rel="nofollow noreferrer">examples</a> in <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/learn/python/learn" rel="nofollow noreferrer">TFLearn</a> first. There's embedding_ops for one-hot, examples for early stopping, custom decay, and more importantly, the multi-class classification/regression you are encountering. Once you are more familiar with TensorFlow it would be fairly easy for you to insert TensorFlow code to build a custom model you want (there are also examples for this). </p>
|
python|python-2.7|numpy|tensorflow|kaggle
| 1 |
1,907,359 | 29,817,831 |
Reading a compressed/deflated (csv) file line by line
|
<p>I'm using the following generator to iterate through a given csv file row by row in a memory efficient way:</p>
<pre><code>def csvreader(file):
with open(file, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',',quotechar='"')
for row in reader:
yield row`
</code></pre>
<p>This works perfectly and I am able to handle very large files incredibly well. A CSV file of several gigabytes seems to be no problem at all for a small virtual machine instance with limited RAM.</p>
<p>However, when files grow too large, disk space becomes a problem. CSV files generally seem to get very high compression rates, which allows me to store the files at a fraction of their uncompressed size, but before I can use the above code to handle the file, I have to decompress/inflate the file and then run it through my script.</p>
<p>My question: Is there any way to build an efficient generator that does the above (given a file, yield CSV rows as an array), but does so by inflating parts of the file, up till a newline is reached, and then running that through the csv reader, without ever having to deflate/decompress the file as a whole? </p>
<p>Thanks very much for your consideration!</p>
|
<p>If you <code>from gzip import open</code>, you do not need to change your code at all!</p>
|
python|python-2.7|gzip
| 1 |
1,907,360 | 61,263,206 |
ImportError: cannot import name 'convert_from_path'
|
<p><a href="https://i.stack.imgur.com/xP0U9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xP0U9.png" alt="This is my code and error"></a></p>
<p>I am trying to convert pdf to image. So I'm doing it using the pdf2image library. But somehow I get this error</p>
<blockquote>
<p>ImportError: cannot import name 'convert_from_path' </p>
</blockquote>
<p>keeps showing up. When I try to run the same code in command prompt it seems to work. But in Sublime editor this error keeps showing up.</p>
|
<p>From your error message, you seem to have a file named <em>pdf2image.py</em> in the same directory as your main script.</p>
<pre><code>File "/home/raheeb/Downloads/Telegram Desktop/New python/pdf_conversion.py" ...
from pdf2image.exceptions import convert_from_path
File "/home/raheeb/Downloads/Telegram Desktop/New python/pdf2image.py" ...
from pdf2image import convert_from_path ^^
||
||
</code></pre>
<p>You need to rename that, because your main script is importing from <em>that</em> pdf2image.py instead of the <em>actual</em> <a href="https://pypi.org/project/pdf2image/" rel="nofollow noreferrer">pdf2image</a> module which I assume is what you have installed and should be the one you actually need.</p>
<p>As to why it imports that instead of the true module, you need to read the <a href="https://docs.python.org/3/tutorial/modules.html#the-module-search-path" rel="nofollow noreferrer">Module Search Path</a> from the Python docs. Basically, it first searches for modules in the same directory as your script, before it searches from the installation environment.</p>
|
python|importerror
| 2 |
1,907,361 | 61,574,853 |
Tkinter Listbox and Scrollbar not displaying
|
<p>I am having this issue where the scroll bar is not displaying on the listbox. I do not know what the issue is as. </p>
<p>I believe the issue is originating from the Scrollbar variables as the Listbox appears to be displaying and functioning properly.</p>
<p>The output is displaying the listbox with no scrollbar on the right (as set)</p>
<p>Here is the Listbox with the for loop however, it is displaying the wrong dimensions
<a href="https://i.stack.imgur.com/nvF3W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nvF3W.png" alt="enter image description here"></a></p>
<p>Here is the code:</p>
<pre><code>#imports
from tkinter import *
from tkinter import messagebox as ms
from tkinter import ttk
import sqlite3
from PIL import Image,ImageTk
import datetime
global time
time = datetime.datetime.now()
class main:
def __init__(self,master):
self.master = master
def search_user_sql(self):
self.search_user_sqlf = Frame(self.master, height=300, width =200)
scrollbar = Scrollbar(self.search_user_sqlf)
scrollbar.pack(side = RIGHT,fill = BOTH)
myList = Listbox(self.search_user_sqlf, yscrollcommand= scrollbar.set)
myList.pack( side = LEFT, fill = BOTH, expand = 2)
scrollbar.config( command = myList.yview )
self.search_user_sql()
root = Tk()
root.title("Gym Membership System")
main(root)
root.mainloop()
</code></pre>
|
<p>You need to pack the frame to display it. To pack() the frame with the correct size settings, try:</p>
<pre><code>search_user_sqlf = Frame(master, height=300, width=200)
search_user_sqlf.pack(expand=True, fill='both')
search_user_sqlf.pack_propagate(0)
</code></pre>
<p>Here is how to attach a scrollbar to list set in a frame in Tkinter:</p>
<pre><code>from tkinter import *
master = Tk()
search_user_sqlf = Frame( master, width=400, height=400)
search_user_sqlf.pack(expand=True, fill='both')
search_user_sqlf.pack_propagate(0)
scrollbar = Scrollbar(search_user_sqlf)
scrollbar.pack(side=RIGHT, fill=Y)
myList = Listbox(search_user_sqlf, yscrollcommand=scrollbar.set)
for line in range(100):
myList.insert(END, "This is line number " + str(line))
myList.pack( side = LEFT, fill = BOTH , expand = 2)
scrollbar.config( command = myList.yview )
mainloop()
</code></pre>
|
python|tkinter
| 2 |
1,907,362 | 43,320,030 |
Sort text in second column based on values in first column
|
<p>in python i would like to separate the text in different rows based on the values of the first number. So:</p>
<pre><code>Harry went to School 100
Mary sold goods 50
Sick man
</code></pre>
<p>using the provided information below: </p>
<pre><code>number text
1 Harry
1 Went
1 to
1 School
1 100
2 Mary
2 sold
2 goods
2 50
3 Sick
3 Man
for i in xrange(0, len(df['number'])-1):
if df['number'][i+1] == df['number'][i]:
# append text (e.g Harry went to school 100)
else:
# new row (Mary sold goods 50)
</code></pre>
|
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>,</p>
<pre><code>for name,group in df.groupby(df['number']):
print ' '.join([i for i in group['text']])
</code></pre>
<p><strong>Result</strong></p>
<pre><code>Harry Went to School 100
Mary sold goods 50
Sick Man
</code></pre>
|
python|pandas
| 3 |
1,907,363 | 43,394,450 |
pandas merge(how="inner") result is bigger than both dataframes
|
<p>I'm trying to find overlapping rows in two pandas DataFrames with the same columns, but different number of rows:</p>
<pre><code>df1.shape
(187399, 784)
df2.shape
(9790, 784)
</code></pre>
<p>After the <code>pd.merge()</code> operation</p>
<pre><code>common_cols = df1.columns.tolist()
df3 = pd.merge(df1, df2, on=common_cols, how="inner")
</code></pre>
<p>I get the result that is bigger than both df1 and df2</p>
<pre><code>df3.shape
(283979, 784)
</code></pre>
<p>How is it possible and what am I doing wrong?
I have two dfs, both with 784 columns named <code>[0,1,2,3...783]</code> and different number of rows in each df. I just want to find the intersection of identical rows in these dfs. Meaning that if a row is present in <code>df1</code> and <code>df2</code>, it has to go to <code>df3</code>
In a previous step I removed the duplicates from each df with <code>pd.drop_duplicates()</code></p>
<p>Link to the jupyter notebook with code after the header "Problem 5"
<a href="http://Link%20[link](https://github.com/kuatroka/udacity_deep_learning/blob/master/1_notmnist-Copy1.ipynb)" rel="noreferrer">https://github.com/kuatroka/udacity_deep_learning/blob/master/1_notmnist-Copy1.ipynb</a></p>
|
<p>Consider the two dataframes <code>df1</code> and <code>df2</code></p>
<pre><code>df1 = pd.DataFrame(dict(A=[1, 1, 1], B=[9, 8, 7]))
df2 = pd.DataFrame(dict(A=[1, 1, 1], C=[6, 5, 4]))
print(df1)
print()
print(df2)
A B
0 1 9
1 1 8
2 1 7
A C
0 1 6
1 1 5
2 1 4
</code></pre>
<p>If we <code>merge</code> on column <code>'A'</code>, it will return a dataframe for every combination of rows where both column <code>'A'</code>s are equal to one.</p>
<pre><code>df1.merge(df2)
A B C
0 1 9 6
1 1 9 5
2 1 9 4
3 1 8 6
4 1 8 5
5 1 8 4
6 1 7 6
7 1 7 5
8 1 7 4
</code></pre>
<p><strong><em>Answer</em></strong><br>
You have duplicate rows in both dataframes for the same keys you are merging on.</p>
<p>To solve that problem, you can (though you need to decide if this is appropriate for you)</p>
<pre><code>df1.drop_duplicates(common_cols).merge(df2.drop_duplicates(common_cols))
</code></pre>
|
python|pandas|numpy|merge|duplicates
| 9 |
1,907,364 | 48,638,000 |
getting 400 Bad Request error frequently when trying to use flask-socket with uwsgi and nginx
|
<p>I have a flask app running with Flask-SocketIO on port 5000. </p>
<p>I am using uwsgi to run this app on the production server.</p>
<p>This is my uwsgi .ini file for the app:</p>
<pre><code>[uwsgi]
module = server.webserver:app
callable = app
master = true
processes = 5
http-socket = 0.0.0.0:5000
die-on-term = true
plugin = python35
#chdir = /var/xyz/webapp
wsgi-file = /var/xyz/webapp/server/webserver.py
virtualenv = /opt/venv3
#home = /opt/venv3/bin
gevent = 1000
enable-threads = true
</code></pre>
<p>And I am using nginx as reverse proxy to this app & my nginx server block is :</p>
<pre><code> server {
#listen 80 default_server;
#listen [::]:80 default_server;
client_body_timeout 15s;
client_header_timeout 15s;
server_name x.y.z;
root /var/xyz/webapp;
index index.html index.htm index.nginx-debian.html;
location /{
proxy_pass http://127.0.0.1:5000;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /socket.io {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://localhost:5000/socket.io;
}
}
</code></pre>
<p>Now every time the client tries to connect to the socket the request gets 400 Bad Request Error frequently. But if I comment these lines from my uwsgi .ini file:</p>
<pre><code>#master = true
#processes = 5
</code></pre>
<p>the socket gets connected and runs normally.</p>
|
<p>I know this is a little bit late however I believe it has to do with the processes = 5 portion. Per the dev at this <a href="https://github.com/miguelgrinberg/Flask-SocketIO/issues/631#issuecomment-362927945" rel="nofollow noreferrer">link</a> Nginx should be setup to do load balancing multiple processes across socket servers. This is more to help anyone else that stumbles across this. Flask-SocketIO imo is incredibly difficult to configure properly. Load balancing multiple servers is easy enough in Nginx though. It is as simple as binding the flask app to a new port (5001, 5002 etc) and adding the nodes with the uWSGI apps as nodes to Nginx.</p>
<p>More details can be found at this <a href="https://flask-socketio.readthedocs.io/en/latest/deployment.html#uwsgi-web-server" rel="nofollow noreferrer">link</a> as they explain it better</p>
|
python-3.x|nginx|flask|uwsgi|flask-socketio
| 2 |
1,907,365 | 48,571,918 |
Pandas Bining and Group By
|
<p>I have a feeling this is very simple but I am having a major issue with this.</p>
<p>Say I have the following dataframe in pandas.</p>
<pre><code> price ordersize
0 0.139664 6.051679
1 0.139665 2.358634
2 0.139665 2.618828
3 0.139665 27.240000
4 0.139665 0.040661
5 0.140060 3.000000
6 0.140100 1.463016
7 0.140128 0.020000
8 0.140418 85.000000
9 0.140427 7.000000
</code></pre>
<p>This is an orderbook for BCHBTC</p>
<p>As you can see starting at index 1 to index 5 we see a number of orders at the same price.</p>
<p>I need to take this input and get it to bin the data so it outputs another dataframe like this.</p>
<pre><code> price ordersize
0 0.139664 6.051679
1 0.139665 32.258123
2 0.140060 3.000000
3 0.140100 1.463016
4 0.140128 0.020000
5 0.140418 85.000000
6 0.140427 7.000000
</code></pre>
<p>I have tried using groupby and other things but It is not giving me the correct output, or gives it in a very weird formating that is hard to work with.</p>
<p>If I could get some help with this that would be much appreciated.</p>
|
<p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> and <code>sum</code>:</p>
<pre><code>df2 = df.groupby("price").sum()
</code></pre>
<p>This gets you the new <code>ordersize</code>, with the <code>price</code> as index. If you want the index back as a column, you can use <a href="https://stackoverflow.com/a/20461206/4042267"><code>reset_index</code></a>:</p>
<pre><code>df2.reset_index(level=0, inplace=True)
</code></pre>
|
python|pandas
| 0 |
1,907,366 | 48,864,631 |
What are the differences between a cpdef and a cdef wrapped in a def?
|
<p>In the Cython docs there is an <a href="http://docs.cython.org/en/latest/src/userguide/early_binding_for_speed.html" rel="noreferrer">example</a> where they give two ways of writing a C/Python hybrid method. An explicit one with a cdef for fast C access and a wrapper def for access from Python:</p>
<pre><code>cdef class Rectangle:
cdef int x0, y0
cdef int x1, y1
def __init__(self, int x0, int y0, int x1, int y1):
self.x0 = x0; self.y0 = y0; self.x1 = x1; self.y1 = y1
cdef int _area(self):
cdef int area
area = (self.x1 - self.x0) * (self.y1 - self.y0)
if area < 0:
area = -area
return area
def area(self):
return self._area()
</code></pre>
<p>And one using cpdef:</p>
<pre><code>cdef class Rectangle:
cdef int x0, y0
cdef int x1, y1
def __init__(self, int x0, int y0, int x1, int y1):
self.x0 = x0; self.y0 = y0; self.x1 = x1; self.y1 = y1
cpdef int area(self):
cdef int area
area = (self.x1 - self.x0) * (self.y1 - self.y0)
if area < 0:
area = -area
return area
</code></pre>
<p>I was wondering what the differences are in practical terms.</p>
<p>For example, is either method faster/slower when called from C/Python?</p>
<p>Also, when subclassing/overriding does cpdef offer anything that the other method lacks?</p>
|
<p>chrisb's answer gives you all you need to know, but if you are game for gory details...</p>
<p>But first, the takeaways from the lengthy analysis bellow in a nutshell:</p>
<ul>
<li><p>For free functions, there is not much difference between <code>cpdef</code> and rolling it out with <code>cdef</code>+<code>def</code> performance-wise. The resulting c-code is almost identical.</p></li>
<li><p>For bound methods, <code>cpdef</code>-approach can be slightly faster in the presence of inheritance-hierarchies, but nothing to get too excited about.</p></li>
<li><p>Using <code>cpdef</code>-syntax has its advantages, as the resulting code is clearer (at least to me) and shorter.</p></li>
</ul>
<hr>
<p><strong>Free functions:</strong></p>
<p>When we define something silly like:</p>
<pre><code> cpdef do_nothing_cp():
pass
</code></pre>
<p>the following happens:</p>
<ol>
<li>a fast c-function is created (in this case it has a cryptic name <code>__pyx_f_3foo_do_nothing_cp</code> because my extension is called <code>foo</code>, but you actually have only to look for the <code>f</code> prefix).</li>
<li>a python-function is also created (called <code>__pyx_pf_3foo_2do_nothing_cp</code> - prefix <code>pf</code>), it does not duplicate the code and call the fast function somewhere on the way.</li>
<li>a python-wrapper is created, called <code>__pyx_pw_3foo_3do_nothing_cp</code> (prefix <code>pw</code>)</li>
<li><code>do_nothing_cp</code> method definition is issued, this is what the python-wrapper is needed for, and this is the place where is stored which function should be called when <code>foo.do_nothing_cp</code> is invoked.</li>
</ol>
<p>You can see it in the produced c-code here:</p>
<pre><code> static PyMethodDef __pyx_methods[] = {
{"do_nothing_cp", (PyCFunction)__pyx_pw_3foo_3do_nothing_cp, METH_NOARGS, 0},
{0, 0, 0, 0}
};
</code></pre>
<p>For a <code>cdef</code> function, only the first step happens, for a <code>def</code>-function only steps 2-4.</p>
<p>Now when we load module <code>foo</code> and invoke <code>foo.do_nothing_cp()</code> the following happens:</p>
<ol>
<li>The function pointer bound to name <code>do_nothing_cp</code> is found, in our case the python-wrapper <code>pw</code>-function.</li>
<li><code>pw</code>-function is called via function-pointer, and calls the <code>pf</code>-function (as C-functionality)</li>
<li><code>pf</code>-function calls the fast <code>f</code>-function.</li>
</ol>
<p>What happens if we call <code>do_nothing_cp</code> inside the cython-module?</p>
<pre><code>def call_do_nothing_cp():
do_nothing_cp()
</code></pre>
<p>Clearly, cython doesn't need the python machinery to locate the function in this case - it can directly use the fast <code>f</code>-function via a c-function call, bypassing <code>pw</code> and <code>pf</code> functions.</p>
<p>What happens if we wrap <code>cdef</code> function in a <code>def</code>-function?</p>
<pre><code>cdef _do_nothing():
pass
def do_nothing():
_do_nothing()
</code></pre>
<p>Cython does the following:</p>
<ol>
<li>a fast <code>_do_nothing</code>-function is created, corresponding to the <code>f</code>- function above.</li>
<li>a <code>pf</code>-function for <code>do_nothing</code> is created, which calls <code>_do_nothing</code> somewhere on the way.</li>
<li>a python-wrapper, i.e. <code>pw</code> function is created which wraps the <code>pf</code>-function</li>
<li>the functionality is bound to <code>foo.do_nothing</code> via function-pointer to the python-wrapper <code>pw</code>-function.</li>
</ol>
<p>As you can see - not much difference to the <code>cpdef</code>-approach.</p>
<p>The <code>cdef</code>-functions are just simple c-function, but <code>def</code> and <code>cpdef</code> function are python-function of the first class - you could do something like this:</p>
<pre><code>foo.do_nothing=foo.do_nothing_cp
</code></pre>
<p>As to performance, we cannot expect much difference here:</p>
<pre><code>>>> import foo
>>> %timeit foo.do_nothing_cp
51.6 ns ± 0.437 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %timeit foo.do_nothing
51.8 ns ± 0.369 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
</code></pre>
<p>If we look at the resulting machine code (<code>objdump -d foo.so</code>), we can see that the C-compiler has inlined all calls for the cpdef-version <code>do_nothing_cp</code>:</p>
<pre><code> 0000000000001340 <__pyx_pw_3foo_3do_nothing_cp>:
1340: 48 8b 05 91 1c 20 00 mov 0x201c91(%rip),%rax
1347: 48 83 00 01 addq $0x1,(%rax)
134b: c3 retq
134c: 0f 1f 40 00 nopl 0x0(%rax)
</code></pre>
<p>but not for the rolled out <code>do_nothing</code> (I must confess, I'm a little bit surprised and don't understand the reasons yet):</p>
<pre><code>0000000000001380 <__pyx_pw_3foo_1do_nothing>:
1380: 53 push %rbx
1381: 48 8b 1d 50 1c 20 00 mov 0x201c50(%rip),%rbx # 202fd8 <_DYNAMIC+0x208>
1388: 48 8b 13 mov (%rbx),%rdx
138b: 48 85 d2 test %rdx,%rdx
138e: 75 0d jne 139d <__pyx_pw_3foo_1do_nothing+0x1d>
1390: 48 8b 43 08 mov 0x8(%rbx),%rax
1394: 48 89 df mov %rbx,%rdi
1397: ff 50 30 callq *0x30(%rax)
139a: 48 8b 13 mov (%rbx),%rdx
139d: 48 83 c2 01 add $0x1,%rdx
13a1: 48 89 d8 mov %rbx,%rax
13a4: 48 89 13 mov %rdx,(%rbx)
13a7: 5b pop %rbx
13a8: c3 retq
13a9: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
</code></pre>
<p>This could explain, why <code>cpdef</code> version is slightly faster, but anyway the difference is nothing compared to the overhead of a python-function-call.</p>
<hr>
<p><strong>Class-methods:</strong></p>
<p>The situation is a little bit more complicated for class methods, because of the possible polymorphism. Let's start out with:</p>
<pre><code>cdef class A:
cpdef do_nothing_cp(self):
pass
</code></pre>
<p>At first sight, there is not that much difference to the case above:</p>
<ol>
<li>A fast, c-only, <code>f</code>-prefix-version of the function is emitted</li>
<li>A python (prefix <code>pf</code>) version is emitted, which calls the <code>f</code>-function</li>
<li>A python wrapper (prefix <code>pw</code>) wraps the <code>pf</code>-version and is used for registration.</li>
<li><code>do_nothing_cp</code> is registered as a method of class <code>A</code> via <code>tp_methods</code>-pointer of the <code>PyTypeObject</code>.</li>
</ol>
<p>As can be seen in the produced c-file:</p>
<pre><code>static PyMethodDef __pyx_methods_3foo_A[] = {
{"do_nothing", (PyCFunction)__pyx_pw_3foo_1A_1do_nothing_cp, METH_NOARGS, 0},
...
{0, 0, 0, 0}
};
....
static PyTypeObject __pyx_type_3foo_A = {
...
__pyx_methods_3foo_A, /*tp_methods*/
...
};
</code></pre>
<p>Clearly, the bound version has to have the implicit parameter <code>self</code> as an additional argument - but there is more to it: The <code>f</code>-function performs a function-dispatch if called not from the corresponding <code>pf</code> function, this dispatch looks as follows (I keep only the important parts):</p>
<pre><code>static PyObject *__pyx_f_3foo_1A_do_nothing_cp(CYTHON_UNUSED struct __pyx_obj_3foo_A *__pyx_v_self, int __pyx_skip_dispatch) {
if (unlikely(__pyx_skip_dispatch)) ;//__pyx_skip_dispatch=1 if called from pf-version
/* Check if overridden in Python */
else if (look-up if function is overriden in __dict__ of the object)
use the overriden function
}
do the work.
</code></pre>
<p>Why is it needed? Consider the following extension <code>foo</code>:</p>
<pre><code>cdef class A:
cpdef do_nothing_cp(self):
pass
cdef class B(A):
cpdef call_do_nothing(self):
self.do_nothing()
</code></pre>
<p>What happens when we call <code>B().call_do_nothing()</code>?</p>
<ol>
<li>`B-pw-call_do_nothing' is located and called.</li>
<li>it calls <code>B-pf-call_do_nothing</code>,</li>
<li>which calls <code>B-f-call_do_nothing</code>, </li>
<li>which calls <code>A-f-do_nothing_cp</code>, bypassing <code>pw</code> and <code>pf</code>-versions.</li>
</ol>
<p>What happens when we add the following class <code>C</code>, which overrides the <code>do_nothing_cp</code>-function?</p>
<pre><code>import foo
def class C(foo.B):
def do_nothing_cp(self):
print("I do something!")
</code></pre>
<p>Now calling <code>C().call_do_nothing()</code> leads to:</p>
<ol>
<li><code>call_do_nothing' of the</code>C<code>-class being located and called which means,</code>pw-call_do_nothing' of the <code>B</code>-class being located and called,</li>
<li>which calls <code>B-pf-call_do_nothing</code>,</li>
<li>which calls <code>B-f-call_do_nothing</code>, </li>
<li>which calls <code>A-f-do_nothing</code> (as we already know!), bypassing <code>pw</code> and <code>pf</code>-versions.</li>
</ol>
<p>And now in the 4. step, we need to dispatch the call in <code>A-f-do_nothing()</code> in order to get the right <code>C.do_nothing()</code> call! Luckily we have this dispatch in the function at hand!</p>
<p>To make it more complicated: what if the class <code>C</code> were also a <code>cdef</code>-class? The dispatch via <code>__dict__</code> would not work, because cdef-classes don't have <code>__dict__</code>?</p>
<p>For the cdef-classes, the polymorphism is implemented similar to C++'s "virtual tables", so in <code>B.call_do_nothing()</code> the <code>f-do_nothing</code>-function is not called directly but via a pointer, which depends on the class of the object (one can see those "virtual tables" being set up in <code>__pyx_pymod_exec_XXX</code>, e.g. <code>__pyx_vtable_3foo_B.__pyx_base</code>). Thus the <code>__dict__</code>-dispatch in <code>A-f-do_nothing()</code>-function is not needed in case of pure cdef-hierarchy.</p>
<hr>
<p>As to performance, comparing <code>cpdef</code> with <code>cdef</code>+<code>def</code> I get:</p>
<pre><code> cpdef def+cdef
A.do_nothing 107ns 108ns
B.call_nothing 109ns 116ns
</code></pre>
<p>so the difference isn't that large with, if someone, <code>cpdef</code> being slightly faster.</p>
|
python|cython
| 16 |
1,907,367 | 19,924,474 |
Create list of strings with fixed prefix based on size of a list
|
<p>I want to create a list of strings with a fixed prefix where the suffix is based on the size of a list, by using python 3.3.2.</p>
<p>For example I have a list <code>elements</code> with <code>len(elements)</code> equal to 3. The output should be a list <code>output = ['prefix_1','prefix_2','prefix_3']</code></p>
<p>I can do this by using a loop:</p>
<pre><code>elements = ['elem1','elem2','elem3']
output = []
for i in range(len(elements)):
output.append('prefix_'+str((i+1)))
</code></pre>
<p>This works but seems a bit... unpythonic to me. Is there a more pythonic way to do this? For example with a list comprehension?</p>
|
<p>Using <a href="http://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>, <a href="http://docs.python.org/3/library/stdtypes#str.format" rel="nofollow"><code>str.format</code></a>:</p>
<pre><code>>>> elements = ['elem1','elem2','elem3']
>>> output = ['prefix_{}'.format(i) for i, elem in enumerate(elements, 1)]
>>> output
['prefix_1', 'prefix_2', 'prefix_3']
</code></pre>
|
python|string|python-3.x|list-comprehension
| 4 |
1,907,368 | 67,046,256 |
Remove flash glare from image using opencv
|
<p>I'm working on extracting the the electricity meter number from a photos of a watt-hour meter using OpenCV python. I have the photos cropped/detected using Yolov4 like this:
<a href="https://i.stack.imgur.com/NRVCd.jpg" rel="nofollow noreferrer">The original Image</a></p>
<p>Then I do some operations on it including, making it gray, blur, thresholding, and then closing. Photos without glare are working fine. But the image like the one above is not.</p>
<p>`#gray scaling
gray_img = cv.cvtColor(img, cv.COLOR_RGB2GRAY)</p>
<p>blur_img = cv.GaussianBlur(gray_img, (5,5), 0)</p>
<p>rect_kern = cv.getStructuringElement(cv.MORPH_RECT, (5,5))</p>
<p>ret, thresh = cv.threshold(blur_img, 0, 255, cv.THRESH_OTSU | cv.THRESH_BINARY_INV)</p>
<p>closing = cv.morphologyEx(thresh, cv.MORPH_CLOSE, rect_kern, iterations=2)</p>
<p>dilation = cv.dilate(thresh, rect_kern, iterations = 1)</p>
<p>#finding the contours</p>
<p>contours, hierarchy = cv.findContours(closing, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)</p>
<p>sorted_contours = sorted(contours, key=lambda ctr: cv.boundingRect(ctr)[0])`</p>
<p>Then after that, I compute the ratio of the width and height of every contour to find the numbers and pass them to the ocr, but that's not my purpose of asking this question. The result of the above image and the above code is the following.</p>
<p><a href="https://i.stack.imgur.com/bC5LO.png" rel="nofollow noreferrer">The final image before reading with the ocr</a></p>
<p>As you can see around the number 9 and 1 there is the glare which resulted in not being able to read the numbers. Is there anyone to solve this issue. I'm open to any kind of advice, even probably using something other than OpenCV. Btw I'm using tesseract as an ocr.</p>
|
<p>Glare is in fact destroying any information locally, in an unrecoverable way.</p>
<p>A solution could be to use an OCR engine that allows "don't know" pixels, but AFAIK Tesseract does not support that.</p>
<p>The damage is lessened if you turn the bright pixels to dark before other processing.</p>
|
python|opencv|image-processing|ocr|python-tesseract
| 0 |
1,907,369 | 67,145,600 |
sqlalchemy+pyodbc for MySQL is giving me an error while trying to create a connection from engine
|
<p>I am trying to connect to a MySQL db using sqlalchemy and pyodbc. Connecting using ODBC is a requirement, so I cannot use any other methods for creating engine and connection.
Here the code I am using to create engine and connection.</p>
<pre><code>params = quote_plus("DRIVER={MySQL ODBC 8.0 Unicode Driver};"
f"SERVER={host}:{port};"
f"DATABASE={db};"
f"UID={username};"
f"PWD={password}")
# Creating dbengine and connection
db_engine = create_engine(f"mysql+pyodbc:///?odbc_connect={params}")
print('Type of dbengine', type(db_engine))
connection = db_engine.connect()
</code></pre>
<p>I am giving the last 3 lines of the stack trace I am getting from <code>connection = db_engine.connect()</code>.</p>
<pre><code> File "C:\ProgramData\Anaconda3\envs\nice_rpa\lib\site-packages\sqlalchemy\engine\base.py", line 1276, in _execute_context
self.dialect.do_execute(
File "C:\ProgramData\Anaconda3\envs\nice_rpa\lib\site-packages\sqlalchemy\engine\default.py", line 608, in do_execute
cursor.execute(statement, parameters)
TypeError: The first argument to execute must be a string or unicode query.
</code></pre>
<p>There is no query I am passing or as per the connect() doc, connect takes only 1 kwarg and no query.
I don't understand why I am getting this error. Can someone explain what and why this error?
Also, seems like pyodbc gives a lot of errors sometimes(as per other resources I read). Is there a good alternative for sqlalchemy+pyodbc. I finally want to pass the <code>connection</code> to <code>pd.to_sql</code> and `pd.read_sql' and using odbc is mandatory.</p>
|
<p>This was an issue with SQLAlchemy 1.3.x and <code>mysql+pyodbc://</code> that has been fixed in SQLAlchemy 1.4.</p>
|
python|mysql|pandas|sqlalchemy|pyodbc
| 1 |
1,907,370 | 51,154,989 |
Numpy-vectorized function to repeat blocks of consecutive elements
|
<p>Numpy has а <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer">repeat</a> function, that repeats each element of the array a given (per element) number of times.</p>
<p>I want to implement a function that does similar thing but repeats not individual elements, but variably sized blocks of consecutive elements. Essentially I want the following function:</p>
<pre><code>import numpy as np
def repeat_blocks(a, sizes, repeats):
b = []
start = 0
for i, size in enumerate(sizes):
end = start + size
b.extend([a[start:end]] * repeats[i])
start = end
return np.concatenate(b)
</code></pre>
<p>For example, given</p>
<pre><code>a = np.arange(20)
sizes = np.array([3, 5, 2, 6, 4])
repeats = np.array([2, 3, 2, 1, 3])
</code></pre>
<p>then</p>
<pre><code>repeat_blocks(a, sizes, repeats)
</code></pre>
<p>returns</p>
<pre><code>array([ 0, 1, 2,
0, 1, 2,
3, 4, 5, 6, 7,
3, 4, 5, 6, 7,
3, 4, 5, 6, 7,
8, 9,
8, 9,
10, 11, 12, 13, 14, 15,
16, 17, 18, 19,
16, 17, 18, 19,
16, 17, 18, 19 ])
</code></pre>
<p>I want to push these loops into numpy in the name of performance. Is this possible? If so, how?</p>
|
<p>Here's one vectorized approach using <code>cumsum</code> -</p>
<pre><code># Get repeats for each group using group lengths/sizes
r1 = np.repeat(np.arange(len(sizes)), repeats)
# Get total size of output array, as needed to initialize output indexing array
N = (sizes*repeats).sum() # or np.dot(sizes, repeats)
# Initialize indexing array with ones as we need to setup incremental indexing
# within each group when cumulatively summed at the final stage.
# Two steps here:
# 1. Within each group, we have multiple sequences, so setup the offsetting
# at each sequence lengths by the seq. lengths preceeeding those.
id_ar = np.ones(N, dtype=int)
id_ar[0] = 0
insert_index = sizes[r1[:-1]].cumsum()
insert_val = (1-sizes)[r1[:-1]]
# 2. For each group, make sure the indexing starts from the next group's
# first element. So, simply assign 1s there.
insert_val[r1[1:] != r1[:-1]] = 1
# Assign index-offseting values
id_ar[insert_index] = insert_val
# Finally index into input array for the group repeated o/p
out = a[id_ar.cumsum()]
</code></pre>
|
python|algorithm|numpy|vectorization
| 4 |
1,907,371 | 51,509,741 |
Python datetime delta format
|
<p>I am attempting to find records in my dataframe that are 30 days old or older. I pretty much have everything working but I need to correct the format of the Age column. Most everything in the program is stuff I found on stack overflow, but I can't figure out how to change the format of the delta that is returned. </p>
<pre><code>import pandas as pd
import datetime as dt
file_name = '/Aging_SRs.xls'
sheet = 'All'
df = pd.read_excel(io=file_name, sheet_name=sheet)
df.rename(columns={'SR Create Date': 'Create_Date', 'SR Number': 'SR'}, inplace=True)
tday = dt.date.today()
tdelta = dt.timedelta(days=30)
aged = tday - tdelta
df = df.loc[df.Create_Date <= aged, :]
# Sets the SR as the index.
df = df.set_index('SR', drop = True)
# Created the Age column.
df.insert(2, 'Age', 0)
# Calculates the days between the Create Date and Today.
df['Age'] = df['Create_Date'].subtract(tday)
</code></pre>
<p>The calculation in the last line above gives me the result, but it looks like <code>-197 days +09:39:12</code> and I need it to just be a positive number <code>197</code>. I have also tried to search using the python, pandas, and datetime keywords.</p>
<pre><code>df.rename(columns={'Create_Date': 'SR Create Date'}, inplace=True)
writer = pd.ExcelWriter('output_test.xlsx')
df.to_excel(writer)
writer.save()
</code></pre>
|
<p>here is what i worked out for basically the same issue.</p>
<pre><code># create timestamp for today, normalize to 00:00:00
today = pd.to_datetime('today', ).normalize()
# match timezone with datetimes in df so subtraction works
today = today.tz_localize(df['posted'].dt.tz)
# create 'age' column for days old
df['age'] = (today - df['posted']).dt.days
</code></pre>
<p>pretty much the same as the answer above, but without the call to <code>abs()</code>.</p>
|
python|python-3.x|pandas|datetime|formatting
| 0 |
1,907,372 | 73,775,125 |
Octal to Decimal with (string) inputs in Python
|
<p>Am stuck with some code. Am trying to write a function to translate octal to decimal accepting a string containing octal data (either a single number or a sequence of numbers separated by spaces) using loops and logic to return a string that contains one or more decimal numbers separated by spaces.</p>
<p>So far I have:</p>
<pre><code>def decode(code):
decimal = 0
code = code.split(" ")
l = len(code)
for i in range (l):
octal = len(i)
for x in range (octal):
digit_position = x - 1
decimal += pow(8, digit_position) * int(x)
result = str(decimal)
</code></pre>
<p>Produces an error. Any ideas?</p>
|
<p><code>int</code> takes an optional second argument (which defaults to 10): the base of the number to convert from. IIUC, you could just use:</p>
<pre class="lang-py prettyprint-override"><code>def decode(code):
return str(int(code, 8)).replace("", " ")
</code></pre>
|
python
| 1 |
1,907,373 | 17,294,642 |
Multi-threaded tools
|
<p>I am still pretty new to python scripting and am trying to speed up and smooth out some of my tools by adding multi-threading support. I feel like I may be miss-understanding some of the workflow theory here so feel free to redirect my mindset if I should be doing this another way. Basically what I am trying to do is the following:</p>
<pre><code>==================================================================
###Pseudo-code -- I apologize if this does not follow existing conventions
main_function()
if do_stuff_function is not running:
Thread1 = new thread running do_stuff_function
do_stuff_function(args)
do some stuff
wait for 60 seconds (possibly using time.sleep())
end thread (tell main_function that the thread is done)
==================================================================
###Abridged code
def main(self):
check = True
index = 0
While index < 5:
if check == True:
check = False
thread1 = threading.Thread(target=self.doStuff, args=(self, index))
def do_stuff(self, index):
###Stuff happens here####
###iterate index and somehow return it (possibly a global variable)
time.sleep(60)
###somehow end the thread (still not entirely sure how to do that)
===================================================================
</code></pre>
<p>Notes:</p>
<p>-- This tool has a gui and it all tends to lock up and freeze if i run the time.sleep() in the main loop which is why I figured that multithreading would be a good solution (feel free to correct me if that is wrong). Or possibly a different way to wait that doesn't freeze the entire thread while waiting.</p>
<p>-- The program freezes in the while loop, is there a way to do this check without having to loop, possibly something like a callback (like a simulated button press when the do_stuff() function ends)? </p>
<p>-- I am also looking to try and add some error checking to this, so based on the results of do_stuff() return different error codes (just something to keep in mind). </p>
<p>I apologize if that is not enough info; feel free to ask for more specific info if you need it. Really guys, I appreciate all the help I can get, I am just trying to get a solid understanding of this stuff! Thanks!</p>
|
<p>threads have some overhead and they all share the same CPU core, threads are good for waiting for user input or downloading files and other things where you are i/o limited, if you need more computing power I would suggest you use the multiprocessing module (see <a href="https://stackoverflow.com/questions/3044580/multiprocessing-vs-threading-python">Multiprocessing vs Threading Python</a>)</p>
<p>another problem with threads is that they 'lock up' because of the Global Interpreter Lock, this is because only 1 thread is allowed to write to memory at any one time, the absurd result is that to many threads brings down your program because they are all waiting to access memory</p>
|
python|python-multithreading
| 2 |
1,907,374 | 70,725,785 |
Topic is not available during auto-create initialization
|
<p>I'm trying to get a kafka consumer to subscribe to 2 topics, yet whenever I try and assign more than one Topic I get this message:</p>
<pre><code>INFO:__main__:Controller module is running and listening...
WARNING:kafka.coordinator.consumer:group_id is None: disabling auto-commit.
INFO:kafka.consumer.subscription_state:Updating subscribed topics to: ('folder-data', 'password')
INFO:kafka.conn:<BrokerConnection node_id=bootstrap-0 host=172.17.0.1:9092 <connecting> [IPv4 ('172.17.0.1', 9092)]>: connecting to 172.17.0.1:9092 [('172.17.0.1', 9092) IPv4]
INFO:kafka.conn:Probing node bootstrap-0 broker version
INFO:kafka.conn:<BrokerConnection node_id=bootstrap-0 host=172.17.0.1:9092 <connecting> [IPv4 ('172.17.0.1', 9092)]>: Connection complete.
INFO:kafka.conn:Broker version identified as 2.5.0
INFO:kafka.conn:Set configuration api_version=(2, 5, 0) to skip auto check_version requests on startup
INFO:__main__:Sending message: <Logger __main__ (INFO)> to topics: find-password, analyze-folder
INFO:kafka.conn:<BrokerConnection node_id=1001 host=172.17.0.1:9092 <connecting> [IPv4 ('172.17.0.1', 9092)]>: connecting to 172.17.0.1:9092 [('172.17.0.1', 9092) IPv4]
INFO:kafka.conn:<BrokerConnection node_id=1001 host=172.17.0.1:9092 <connecting> [IPv4 ('172.17.0.1', 9092)]>: Connection complete.
INFO:kafka.conn:<BrokerConnection node_id=bootstrap-0 host=172.17.0.1:9092 <connected> [IPv4 ('172.17.0.1', 9092)]>: Closing connection.
INFO:__main__:Sent.
INFO:kafka.conn:<BrokerConnection node_id=bootstrap-0 host=172.17.0.1:9092 <connecting> [IPv4 ('172.17.0.1', 9092)]>: connecting to 172.17.0.1:9092 [('172.17.0.1', 9092) IPv4]
INFO:kafka.conn:<BrokerConnection node_id=bootstrap-0 host=172.17.0.1:9092 <connecting> [IPv4 ('172.17.0.1', 9092)]>: Connection complete.
WARNING:kafka.cluster:Topic password is not available during auto-create initialization
WARNING:kafka.cluster:Topic folder-data is not available during auto-create initialization
INFO:kafka.consumer.subscription_state:Updated partition assignment: []
</code></pre>
<p>For some reason, if I restart the container afterwards it works.</p>
<p>Here's my code:</p>
<pre><code> analye_folder = 'analyze-folder'
folder_data = 'folder-data'
find_password = 'find-password'
get_password = 'password'
consumer = KafkaConsumer (auto_offset_reset='earliest',
bootstrap_servers=bootstrap_servers,
api_version=(0,10))
consumer.subscribe([get_password, folder_data])
</code></pre>
<p>How do I get around this?</p>
|
<p>Read the logs - <code>Topic not available during auto-create</code></p>
<p>Create the topics beforehand and disable topic auto-creation in the broker.</p>
|
python|apache-kafka|kafka-python
| 0 |
1,907,375 | 63,970,328 |
Convert a column having mixed strings to epoch date pandas dataframe
|
<p>I have a data frame column with values like</p>
<pre><code>$none
1558044313727
$none
1558058614585
...
</code></pre>
<p>I tried the below query, event with <code>errors='ignore'</code> it is not converting.</p>
<pre><code>df['epoch_date'] = pd.to_datetime(df['epoch_date'], unit='ms')
ERROR: ValueError: non convertible value $none with the unit 'ms'
</code></pre>
<p>How do I ignore $none or convert it into NaN values and rest all with datetime values?</p>
|
<p>Try using <code>errors = 'coerce'</code>:</p>
<pre><code>df['epoch_date'] = pd.to_datetime(df['epoch_date'], unit='ms', errors = 'coerce')
</code></pre>
<p>This will convert your <code>'$none'</code> values (and any other invalid parsing) to <code>NaT</code>, which is <code>NaN</code> eqivalent for <code>datetime64[ns]</code> types.</p>
<p><code>errors = 'ignore'</code> fails because it simply returns the input on invalid parsing, so in the end it's trying to fit a string into datetime object, which fails for obvious reasons.</p>
|
python|pandas|dataframe
| 1 |
1,907,376 | 65,329,670 |
How can access Scala JDBC connection in Python Notebook ---Databricks
|
<p>I have a connection object in Scala cell, which I would like reuse it in Python cell.
Is there alternate to temp table to access this connection.
Databricks</p>
|
<p>Not really - Python code is executed in the different context, so you can have some data exchange either via SparkSession itself (<code>.set</code>/<code>.get</code> on the SparkConf, but it works only for primitive data), or by registering the temp view</p>
|
python|scala|jdbc|databricks
| 0 |
1,907,377 | 65,200,143 |
PyAutoGui and PyScreeze
|
<p>I have coded a simple Osu! bot, but it doesnt work. I get no error until i open (fullscreen) osu. I have tried running it from cmd with administrator, but it just wont work. I get this error:</p>
<p>Traceback (most recent call last):
File "C:/Users/Kris/PycharmProjects/OsuBot/venv/drums.py", line 7, in
if pyautogui.pixel(609, 440)[0] == 235:
File "C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\pyscreeze_<em>init</em>_.py", line 584, in pixel
return (r, g, b)
File "C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\contextlib.py", line 120, in <strong>exit</strong>
next(self.gen)
File "C:\Users\Kris\AppData\Local\Programs\Python\Python38\lib\pyscreeze_<em>init</em>_.py", line 113, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0</p>
<p>Process finished with exit code 1</p>
<p>I get the error while running from IDLE, cmd and PyCharm.</p>
<p>Here is my code:</p>
<pre><code>import pyautogui
import keyboard
import time
while 1:
if pyautogui.pixel(609, 440)[0] == 235:
keyboard.press('x')
time.sleep(0.1)
keyboard.release('x')
if pyautogui.pixel(609, 440)[0] == 67:
keyboard.press('z')
time.sleep(0.1)
keyboard.release('z')
time.sleep(0.01)
# X: 609 Y: 440 RGB: ( 32, 99, 222)
# RED = X: 1534 Y: 485 RGB: (235, 69, 44)
# BLUE = X: 1138 Y: 459 RGB: ( 67, 142, 172)
</code></pre>
<p>Thanks in advance.</p>
|
<p>Looks like <code>pyautogui</code> has some issues with pixel indetification as I've also tried out <code>pyautogui.pixel()</code> and I seem to be getting the same <code>OSError: windll.user32.ReleaseDC failed : return 0</code> however for some reason it works half the time and I get the code to function properly. Not sure why though, I'm not doing anything except re-running the program several times in a row until it works.</p>
<p>You could try the <code>pillow</code> library using <code>pip install pillow</code> which has a <code>getpixel()</code> function. You'd have to take a screenshot first but thankfully <code>pyautogui</code> has that covered:</p>
<pre><code>from PIL import Image
import pyautogui as py
py.screenshot('file.png')
img = Image.open('file.png')
print(img.getpixel((180, 90)))
</code></pre>
<p>I see you're also using the <code>keyboard</code> library, but honestly you could just use <code>pyautogui</code> for that and then you wouldn't need to import an extra library.</p>
<p><strong>FINAL CODE</strong></p>
<pre><code>import time
from PIL import Image
import pyautogui as py
while 1:
py.screenshot('file.png')
img = Image.open('file.png')
if img.getpixel((609, 440))[0] == 235:
py.press('x')
if img.getpixel((609, 440))[0] == 67:
py.press('z')
time.sleep(1)
</code></pre>
|
python|python-3.x|windows|pyautogui
| 0 |
1,907,378 | 71,856,347 |
Reshape a 3D array to a 2D array in Python
|
<p>Suppose I have a data frame of length <code>5800000</code> which is a concatenation of 100 files where each file has 58000 rows. I have an array <code>fv</code> of shape <code>(100, 10, 58000)</code> which I want to add to the data frame by adding 10 columns. <code>df</code> has a length of <code>5800000</code> with two columns but only focuses on the first column index, i.e <code>df.shape[0]</code></p>
<pre><code>list_ = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
fv = np.zeros(len(data), len(list_), int(df.shape[0]/len(files))
</code></pre>
<pre><code>def add_fv_to_dataframe(_data, list_):
for index in range(len(_data):
for name_index, name_in_list in enumerate(list_):
calculate something
calcs_ = _data[index]
fv[index, name_index, :] = calcs_
# add the calculated values to the dataframe
df['fv_{}'.format(name_in_list)] = pd.Series(fv.reshape(-1, (10,1)), index=df.index)
</code></pre>
<p>I would like to have my final data frame in the form;</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">df[0]</th>
<th style="text-align: left;">df[1]</th>
<th style="text-align: left;">fv_a</th>
<th style="text-align: left;">fv_b</th>
<th style="text-align: left;">fv_c</th>
<th style="text-align: left;">fv_d</th>
<th style="text-align: left;">fv_e</th>
<th style="text-align: left;">fv_f</th>
<th style="text-align: left;">fv_g</th>
<th style="text-align: left;">fv_h</th>
<th style="text-align: left;">fv_i</th>
<th style="text-align: left;">fv_j</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
<td style="text-align: left;">1</td>
</tr>
<tr>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
<td style="text-align: left;">:</td>
</tr>
<tr>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
<td style="text-align: left;">5800000</td>
</tr>
</tbody>
</table>
</div>
|
<p>Use <code>np.swapaxes</code>:</p>
<pre class="lang-py prettyprint-override"><code>for i, data in enumerate(np.swapaxes(fv, 0, 1)):
df[f"fv_{i}"] = np.ravel(data)
</code></pre>
|
python|arrays|pandas|numpy
| 1 |
1,907,379 | 62,480,909 |
python return dose not work saying "blabla is not defined"
|
<p>So I'm studying Python and learning <code>def</code> and what it dose but when i try to run the following code</p>
<pre><code>def test1():
a = [" " , " " , " "]
return a
test1()
print(a)
</code></pre>
<p>the error pop up saying that <code>a</code> is not defined.</p>
|
<p><code>a</code> is defined only in the scope of <code>test1</code>. You have to do <code>a = test1()</code> to store the value in a. </p>
|
python|function
| 1 |
1,907,380 | 60,680,186 |
Pandas multiiindex boolean slice
|
<p>I'm so new to this I don't have the vocabulary to properly frame the question. Nor do I know how to include the output very well. </p>
<p>I'm trying to slice a multi indexed dataframe of COVID19 data. I want to select data from countries other than China. I know how to slice using a multiindex based on countries I want to see, I just don't know how to look at everything but a country or set of countries.</p>
<pre><code> 1/22/20 1/23/20 1/24/20...
Country Province
China Hubei 28 28 28
Italy NaN 0 0 0
...
</code></pre>
<p>Obviously the dataframe is much bigger. All I want to do is slice by excluding rather than explicitly including.</p>
<p><code>df.loc['China']</code></p>
<p>Gives me all rows with China. How do I slice to exclude? Below doesn't work, but it gives the idea:</p>
<p><code>df.loc[!='China']</code></p>
<p>Any hints?</p>
<p>Thanks!</p>
|
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_level_values.html" rel="nofollow noreferrer"><code>Index.get_level_values</code></a> with filtering in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p>
<pre><code>df1 = df[df.index.get_level_values(0) != 'China']
print (df1)
1/22/20 1/23/20 1/24/20
Country Province
Italy NaN 0 0 0
</code></pre>
|
pandas|multi-index
| 1 |
1,907,381 | 70,254,953 |
UnicodeDecodeError issue while looping through all the pictures in a folder using CV2
|
<p>My code:</p>
<pre><code>folder_angry = 'C:/Users/User/Desktop/test'
all_vald_img = []
for filename_valid in os.listdir(folder_angry):
img_valid = cv2.imread(os.path.join(folder_angry,filename_valid))
if img_valid is not None:
all_vald_img.append(img_valid)
true_image = image.load_img(img_valid)
img = image.load_img(img_valid, color_mode="grayscale", target_size=(48, 48))
</code></pre>
<p>Error message:</p>
<pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfd in position 1: invalid start byte
</code></pre>
<p>I encountered this error while looping through the entire folder of pictures using cv2.imread. I've tried solutions like</p>
<pre><code>with open(path, 'rb') as f:
contents = f.read()
</code></pre>
<p>or any other solutions start with <code>with open</code> like many people suggested, but none of them really works. However, if I use picture one by one without loop, like</p>
<pre><code>filename_valid = "path"
true_image = image.load_img(filename_valid)
img = image.load_img(filename_valid, color_mode="grayscale", target_size=(48, 48))
</code></pre>
<p>it works, but I have to do it one by one.</p>
<p>Is there any good way to tackle this down?</p>
|
<p>You are getting the error because you are passing the image itself (as NumPy array) to <code>image.load_img</code>, while <code>image.load_img</code> expects an image file name as argument.</p>
<p>Basically you are trying to read each image twice:</p>
<ul>
<li><p>Using OpenCV:<br />
<code>cv2.imread</code> returns an image (as NumPy array) in case of successful reading, and return <code>None</code> when reading fails.</p>
</li>
<li><p>Using Pillow:<br />
<code>image.load_img(file_name)</code> loads the image using Pillow, and returns an object of type <code>PIL.Image.Image</code>.</p>
</li>
</ul>
<p>The issue is that <code>image.load_img</code> expects a file name as an argument, and you are passing it an image (NumPy array) instead of file name.<br />
The NumPy array is not a valid 'utf-8' string, so you are getting the error:</p>
<blockquote>
<p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfd in position 1: invalid start byte.</p>
</blockquote>
<hr />
<p>Assuming that reading each image twice is not an issue...<br />
You may use something like the following code sample:</p>
<pre><code>import os
import cv2
from keras.preprocessing import image
folder_angry = 'C:/Users/User/Desktop/test'
all_vald_img = []
all_vald_img_files = []
for filename_valid in os.listdir(folder_angry):
image_file_name = os.path.join(folder_angry,filename_valid)
img0 = cv2.imread(image_file_name) # Return the image as NumPy array in case of valid reading, and None if not valid.
if img0 is not None:
all_vald_img_files.append(image_file_name) # Append file name to the list (not the image).
true_image = image.load_img(image_file_name) # Use file name as argument to image.load_img
img = image.load_img(image_file_name, color_mode="grayscale", target_size=(48, 48))
all_vald_img.append(img)
# Showing images in all_vald_img for testing:
for img in all_vald_img:
img.show()
</code></pre>
<hr />
<p>Note: I was guessing that you want to keep only the images loaded by <code>image.load_img</code>.</p>
|
python|opencv|computer-vision
| 0 |
1,907,382 | 63,580,114 |
Append multidimensional list in for loop where indices vary with loop iteration
|
<p>I would like to create a list into which a new value is placed every iteration. The list should have dimensions 3x4 (3 rows, 4 columns). I want to iterate x, and for each x, the list should be filled vertically with three values. (Thus, when x = 1, I would like to fill the first index position [1, 1] of the list with the value <em>percentage_a</em>. <em>percentage_b</em> should then fill column 1 (as x is still 1) and row 2. The same for <em>percentage_c</em> for column 1, row 3). Then x goes up by one, and the second column of the list should be filled and so on.
I have code as follows:</p>
<pre><code>list = []
for x in range(1, 4)
a = 2
b = 1
c = 1
sum = 4
percentage_a = a / 4
percentage_b = b / 4
percentage_c = c / 4
list.insert([x, 1], int(percentage_a))
list.insert([x, 2], int(percentage_b))
list.insert([x, 3], int(percentage_c))
</code></pre>
<p>I would wish for output like this:</p>
<pre><code>[0.5 0.5 0.5 0.5
0.25 0.25 0.25 0.25
0.25 0.25 0.25 0.25]
</code></pre>
<p>I am open to do this any way (list, numpy)</p>
|
<p>You can do something like this</p>
<pre><code>import numpy as np
a = 2
b = 1
c = 1
percentage_a = a / 4
percentage_b = b / 4
percentage_c = c / 4
## Option 1
l = np.empty(shape=(3,4))
for x in range(4):
l[:,x]=[percentage_a,percentage_b,percentage_c]
## Option 2, a bit shorter
l = np.array([[percentage_a,percentage_b,percentage_c] for i in range(4)]).T
</code></pre>
<p>This returns a 2D numpy array</p>
<pre><code>array([[0.5 , 0.5 , 0.5 , 0.5 ],
[0.25, 0.25, 0.25, 0.25],
[0.25, 0.25, 0.25, 0.25]])
</code></pre>
<p>Note, you can convert it to a list of lists using <code>l.tolist()</code> or flatten your output to a single list using <code>l.flatten()</code> depending on what you actually need.</p>
|
python|arrays|list|for-loop|indexing
| 1 |
1,907,383 | 61,123,478 |
Error during install of `pymssql` on Mac -- FreeTDS
|
<p>I have reviewed numerous questions on this topic but all seem either out of date or unhelpful. I am attempting to set up <code>pymssql</code> using <code>pip3</code>. I have python version 3.7 and freetds version 1.1.26. When I run <code>pip3 install pymssql</code> here is the lengthy error I encounter. At first glance I thought it could be an issue with the freetds version (<a href="https://github.com/pymssql/pymssql/issues/543" rel="nofollow noreferrer">see here</a>) and I also tried installing directly from the github repo: <code>pip3 install git+https://github.com/pymssql/pymssql</code> but the wheel failed to build. </p>
<pre><code>Collecting pymssql
Using cached pymssql-2.1.4.tar.gz (691 kB)
Building wheels for collected packages: pymssql
Building wheel for pymssql (setup.py) ... error
ERROR: Command errored out with exit status 1:
command: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/setup.py'"'"'; __file__='"'"'/private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-wheel-tfqq1pua
cwd: /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/
Complete output (35 lines):
setup.py: platform.system() => 'Darwin'
setup.py: platform.architecture() => ('64bit', '')
setup.py: platform.libc_ver() => ('', '')
setup.py: Detected Darwin/Mac OS X.
You can install FreeTDS with Homebrew or MacPorts, or by downloading
and compiling it yourself.
Homebrew (http://brew.sh/)
--------------------------
brew install freetds
MacPorts (http://www.macports.org/)
-----------------------------------
sudo port install freetds
setup.py: Not using bundled FreeTDS
setup.py: include_dirs = ['/usr/local/include']
setup.py: library_dirs = ['/usr/local/lib']
running bdist_wheel
running build
running build_ext
cythoning src/_mssql.pyx to src/_mssql.c
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/src/_mssql.pxd
tree = Parsing.p_module(s, pxd, full_module_name)
warning: src/_mssql.pyx:150:4: Exception already a builtin Cython type
cythoning src/pymssql.pyx to src/pymssql.c
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/src/pymssql.pyx
tree = Parsing.p_module(s, pxd, full_module_name)
building '_mssql' extension
creating build
creating build/temp.macosx-10.9-x86_64-3.7
creating build/temp.macosx-10.9-x86_64-3.7/src
gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -I/usr/local/include -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c src/_mssql.c -o build/temp.macosx-10.9-x86_64-3.7/src/_mssql.o -DMSDBLIB
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
error: command 'gcc' failed with exit status 1
----------------------------------------
ERROR: Failed building wheel for pymssql
Running setup.py clean for pymssql
Failed to build pymssql
Installing collected packages: pymssql
Running setup.py install for pymssql ... error
ERROR: Command errored out with exit status 1:
command: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/setup.py'"'"'; __file__='"'"'/private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-record-tjfo0sbt/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m/pymssql
cwd: /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/
Complete output (35 lines):
setup.py: platform.system() => 'Darwin'
setup.py: platform.architecture() => ('64bit', '')
setup.py: platform.libc_ver() => ('', '')
setup.py: Detected Darwin/Mac OS X.
You can install FreeTDS with Homebrew or MacPorts, or by downloading
and compiling it yourself.
Homebrew (http://brew.sh/)
--------------------------
brew install freetds
MacPorts (http://www.macports.org/)
-----------------------------------
sudo port install freetds
setup.py: Not using bundled FreeTDS
setup.py: include_dirs = ['/usr/local/include']
setup.py: library_dirs = ['/usr/local/lib']
running install
running build
running build_ext
cythoning src/_mssql.pyx to src/_mssql.c
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/src/_mssql.pxd
tree = Parsing.p_module(s, pxd, full_module_name)
warning: src/_mssql.pyx:150:4: Exception already a builtin Cython type
cythoning src/pymssql.pyx to src/pymssql.c
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/src/pymssql.pyx
tree = Parsing.p_module(s, pxd, full_module_name)
building '_mssql' extension
creating build
creating build/temp.macosx-10.9-x86_64-3.7
creating build/temp.macosx-10.9-x86_64-3.7/src
gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -I/usr/local/include -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c src/_mssql.c -o build/temp.macosx-10.9-x86_64-3.7/src/_mssql.o -DMSDBLIB
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
error: command 'gcc' failed with exit status 1
----------------------------------------
ERROR: Command errored out with exit status 1: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/setup.py'"'"'; __file__='"'"'/private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-install-2jerl6n6/pymssql/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/ty/b0h4wy9938vbwh98tn_r9ryh0000gn/T/pip-record-tjfo0sbt/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m/pymssql Check the logs for full command output.
</code></pre>
|
<p>On MacOs Big Sur</p>
<pre><code>brew install freetds openssl
export LDFLAGS="-L/opt/homebrew/opt/freetds/lib -L/opt/homebrew/opt/openssl@1.1/lib"
export CFLAGS="-I/opt/homebrew/opt/freetds/include"
pip3 install pymssql
</code></pre>
|
python|freetds|pymssql
| 2 |
1,907,384 | 66,240,608 |
Python subprocess different approaches
|
<p>I have the following structure</p>
<pre><code>- folder1
-- script1.py
- folder2
-- script2_1.py
-- script2_2.py
- folder2
-- script3.py
</code></pre>
<p>script2_1.py has the following line in it</p>
<pre><code>os.system("python3 script2_2.py "+str(id))
</code></pre>
<p>If I SSH into the instance, cd to folder2 and then run script2_1.py</p>
<pre><code>python3 script2_1.py
</code></pre>
<p>it works fine and script2_2.py is called as expected.</p>
<hr />
<p>Now in script1.py I want to call both script2_2.py and script3.py. I've tested different approaches but no success yet.</p>
<p><strong>Approach 1</strong>:</p>
<pre><code>id = str(id)
subprocess.check_call(["/folder2", "script2_2.py "+id])
subprocess.check_call(["/folder3", "script3.py "+id])
</code></pre>
<p>which gives</p>
<blockquote>
<p>PermissionError: [Errno 13] Permission denied: '/folder2'</p>
</blockquote>
<p><strong>Approach 2:</strong></p>
<pre><code>id = str(id)
commands = '''
cd /folder2/
python3 script2_2.py {}
cd /folder3/
python3 script3.py {}
'''.format(id, id)
p = subprocess.Popen("/bin/sh", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate(commands.encode('utf-8'))
</code></pre>
<p>which gives</p>
<blockquote>
<p>/bin/sh: python3: not found</p>
</blockquote>
<p><strong>Approach 3:</strong></p>
<pre><code>id = str(id)
subprocess.call(['cd /folder2/','python3 script2_2.py {}'.format(id)])
subprocess.call(['cd /folder3/','python3 script3.py {}'.format(id)])
</code></pre>
<p>which gives</p>
<blockquote>
<p>FileNotFoundError: [Errno 2] No such file or directory: 'cd /folder2/': 'cd /folder2/'</p>
</blockquote>
<p><strong>Approach 4</strong>:</p>
<p>In this one I've tested args with both string and list, specifying the full path to the .py file, with and without shell=True, without sys.path and with full path in subprocess.call, ...</p>
<pre><code>id = str(id)
#import sys
#sys.path.insert(1, '/folder2/')
subprocess.call(['/usr/local/bin/python3','/folder2/script2_2.py {}'.format(id)])
#sys.path.insert(1, '/folder3/')
subprocess.call(['/usr/local/bin/python3','/folder3/script3.py {}'.format(id)])
</code></pre>
<p>which gives</p>
<blockquote>
<p>/usr/local/bin/python3: can't open file '/folder2/script2_2.py 80': [Errno 2] No such file or directory</p>
<p>/usr/local/bin/python3: can't open file '/folder3/script3.py 80': [Errno 2] No such file or directory</p>
</blockquote>
|
<p>Eventually I manage to solve it by using and adaptation of <strong>Approach 2</strong> with the full path to python3.</p>
<pre><code>id = str(id)
commands = '''
cd /folder2/
/usr/local/bin/python3 script2_2.py {}
cd /folder3/
/usr/local/bin/python3 script3.py {}
'''.format(id, id)
p = subprocess.Popen("/bin/sh", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate(commands.encode('utf-8'))
</code></pre>
<p>To know which one is I SSH into the instance and ran</p>
<pre><code>which python3
</code></pre>
<p>which returned</p>
<pre><code>/usr/local/bin/python3
</code></pre>
|
python|subprocess
| 1 |
1,907,385 | 31,454,195 |
How to access data in tuples in a datatype list
|
<p>I have this list of tuples:</p>
<pre><code>(u'firstname', u'ABCDEFG'), (u'lastname', u'ZXYVUW')]
</code></pre>
<p>How do I access the data using the key for example firstname in the tuple?</p>
|
<p>You can index as suggested with <code>l[0][0]</code> for the first element of the first tuple <code>[1][0]</code> for the first element of the second tuple etc.. but maybe creating a dict would be a better approach if you know the keys you want to use:</p>
<pre><code> l = [(u'firstname', u'ABCDEFG'), (u'lastname', u'ZXYVUW')]
data = dict(l)
print(data["firstname"])
print(data["lastname"])
</code></pre>
<p>Output:</p>
<pre><code>ABCDEFG
ZXYVUW
</code></pre>
|
python|python-2.7
| 3 |
1,907,386 | 50,317,974 |
No module named 'numpy' in pycharm
|
<p>I am quite new to python and pycharm.<br>
I installed python 3.6 through anaconda, and I can see many packages including numpy are installed as I can see them in cmd (im using windows) by typing 'conda list'. Also, it works if i type 'import numpy' in python through window command prompt.</p>
<p>However, if I open pycharm and run "import numpy" there, it gives me 'No module named 'numpy' in pycharm'. May I know whats wrong with my setting? I guess it must be some problem with my interpreter setting.</p>
<p>I think my python is installed in C:\Users\AAA\Anaconda3\python.exe
I checked in pycharm, project interpreter is "C:\Users\AAA\PycharmProjects\untitled\venv\Scripts\python.exe"</p>
<p>Should I change it to the one under anaconda3 folder?<br>
What is venv folder under "pycharmprejcts"? Is it a virtual environment? It shows (see the attached screenshot) the base interpreter is the one under anaconda? Should I choose to inherit global site-packages?</p>
<p><img src="https://i.stack.imgur.com/IpuZi.jpg" alt="Please click here to see the screenshot of my current project interpreter location"></p>
|
<p>You should select Conda environment in Pycharm, not create a new, blank Virtualenv</p>
<p>Or at the very least - System interpreter, then find the Python executable for Anaconda</p>
<blockquote>
<p>What is venv folder under "pycharmprejcts"? Is it a virtual environment?</p>
</blockquote>
<p>Yes, it allows your project to be more portable - you define the minimum set of dependencies for your code rather than rely on everything installed only locally on your machine </p>
|
python|pycharm
| 2 |
1,907,387 | 61,421,891 |
Glut methods not recognised even with dll's(Pyopengl3/Python3.8/Windows10-64)
|
<p>On running the main script in Pyopengl3.1.5(Python3.8- Windows10Pro/64bit) <strong>installed via Pip</strong>,the compiler doesn't recognise Glut methods. </p>
<p>After following these stackoverflow answers (<a href="https://stackoverflow.com/questions/26700719/pyopengl-glutinit-nullfunctionerror#answer-40354664">1</a> & <a href="https://stackoverflow.com/questions/39181192/attempt-to-call-an-undefined-function-glutinit/39181193#39181193">2</a>) ie.reinstalling <a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyopengl" rel="nofollow noreferrer">Pyopengl wheel</a> & putting <a href="https://www.transmissionzero.co.uk/software/freeglut-devel#content" rel="nofollow noreferrer">dll's</a> in main script folder(<strong>C:..Python\…\site-packages</strong> - PyOpengl's main directory) ,Environment Path,System32 & SysWow64 , the compiler still gives the same error : </p>
<pre><code>import OpenGL.GLUT
glutInit()
NameError: name 'glutInit' is not defined (# checked for casetype )
</code></pre>
<p>However, there is a python script named "special.py" located in Site-packages\Opengl\Glut which has the glut methods defined.So on adding the glutinit method's path to <em>init</em>.py (Glut directory)and compiling, the compiler still gives following errors. </p>
<pre><code>OpenGL\GLUT\special.py:- def glutInit(INITIALIZED = False)
OpenGL\GLUT\init.py:- from OpenGL.GLUT.special import *
from OpenGL.GLUT.special import glutInit (#added)
OpenGL\GLUT\main.py:- import OpenGL.GLUT
import OpenGL.GLUT.special(#added)
import OpenGL.GLUT.special.glutInit (#added)
glutInit(INITIALIZED = True) (# function call)
ModuleNotFoundError: No module named 'OpenGL.GLUT.special.glutInit'; 'OpenGL.GLUT.special' is not a package
</code></pre>
<p>So the question is - How to get the <strong><em>compiler to recognise the glut methods in special.py</em></strong> and also is there <strong><em>any way to update the .pyc files</em></strong> so as to reflect the updated init.py import path's? </p>
<p>Main Pyopengl Script (stackabuse.com)</p>
<pre><code>import OpenGL
import OpenGL.GL
import OpenGL.GLUT
import OpenGL.GLUT.special #(added)
import OpenGL.GLUT.special.glutInit #(added)
import OpenGL.GLU
print("Imports successful!")
w, h = 500,500
# define square
def square():
# We have to declare the points in this sequence: bottom left, bottom right, top right, top left
glBegin(GL_QUADS) # Begin the sketch
glVertex2f(100, 100) # Coordinates for the bottom left point
glVertex2f(200, 100) # Coordinates for the bottom right point
glVertex2f(200, 200) # Coordinates for the top right point
glVertex2f(100, 200) # Coordinates for the top left point
glEnd() # Mark the end of drawing
# draw square
def showScreen():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Remove everything from screen (i.e. displays all white)
glLoadIdentity() # Reset all graphic/shape's position
square() # Draw a square using our function
glutSwapBuffers()
# Initialise and create Opengl screen
glutInit(True)
glutInitDisplayMode(GLUT_RGBA) # Set the display mode to be colored
glutInitWindowSize(500, 500) # Set the w and h of your window
glutInitWindowPosition(0, 0) # Set the position at which this windows should appear
wind = glutCreateWindow("OpenGL Coding Practice") # Set a window title
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen) # Keeps the window open
glutMainLoop() # Keeps the above created window displaying/running in a loop
</code></pre>
|
<p>Either you have to precede the module path to at each function call:</p>
<p>For instance:</p>
<p><s><code>glutInit(True)</code></s></p>
<pre class="lang-py prettyprint-override"><code>OpenGL.GLUT.glutInit()
</code></pre>
<p>Or you have to change the <a href="https://docs.python.org/3/reference/simple_stmts.html#import" rel="nofollow noreferrer"><code>import</code> statements</a>, by using the <code>from</code> clause. </p>
<p>For instance:</p>
<pre class="lang-py prettyprint-override"><code>from OpenGL import *
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
</code></pre>
|
python|python-3.x|windows|pyopengl|pyc
| 0 |
1,907,388 | 57,531,997 |
python scrape next strings to a given string
|
<p>I have +1000 txt files to scrape (Python). I already created the <code>file_list</code> variable that lists all the .txt file paths. I have five fields to scrape: file_form, date, company, company id, and price range. For the first four variables I have no issue since they're very structured in separate lines at the beginning of each .txt file:</p>
<pre><code>FILE FORM: 10-K
DATE: 20050630
COMPANY: APPLE INC
COMPANY CIK: 123456789
</code></pre>
<p>I used the following code for these four ones:</p>
<pre><code> import sys, os, re
exemptions=[]
for eachfile in file_list:
line2 = "" # for the following loop I need the .txt in lines. Right now, the file is read one in all. Create var with lines
with open(eachfile, 'r') as f:
for line in f:
line2 = line2 + line # append each line. Shortcut: "line2 += line"
if "FILE FORM" in line:
exemptions.append(line.strip('\n').replace("FILE FORM:", "")) #append line stripping 'S-1\n' from field in + replace FILE FORM with blanks
elif "COMPANY" in line:
exemptions.append(line.rstrip('\n').replace("COMPANY:", "")) # rstrip=strips trailing characters '\n'
elif "DATE" in line:
exemptions.append(line.rstrip('\n').replace("DATE:", "")) # add field
elif "COMPANY CIK" in line:
exemptions.append(line.rstrip('\n').replace("COMPANY CIK:", "")) # add field
print(exemptions)
</code></pre>
<p>These gives me a list <code>exemptions</code> with all the associated values as in the above example. However, the "price range" field is found in the middle of the .txt file in sentences like:</p>
<pre><code>We anticipate that the initial public offering price will be between $&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;and
$&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;per share.
</code></pre>
<p>And I don't know how to keep the <code>$whateveritis;and $whateveritis;per share.</code> as my last fifth variable. Good news is that a lot of files use the same structure, where sometimes instead of the "&nbsp" I have $amounts. Example: <code>We anticipate that the initial public offering price will be between $12.00&nbsp;and $15.00&nbsp; per share.</code>.</p>
<p>I would like this "12.00;and;15.00" as my fifth variable in the <code>exemptions</code> list (or something similar I can easily work afterwards in a csv file).</p>
<p>Thank you so much in advance.</p>
|
<p>Looks like you have already imported regular expressions so why don't you use that? A regex such as <code>\$[\d.]+\&nbsp;and \$[\d.]+</code> should match the prices and then you can easily refine it from there:</p>
<pre class="lang-py prettyprint-override"><code>import sys, os, re
exemptions=[]
for eachfile in file_list:
line2 = ""
with open(eachfile, 'r') as f:
for line in f:
line2 = line2 + line
m = re.search('\$[\d.]+\&nbsp;and \$[\d.]+', line)
if "FILE FORM" in line:
.
.
.
elif m:
exemptions.append(m.group(0)) # m.group(0) will be the first occurrence and you can refine it from there
print(exemptions)
</code></pre>
|
python|string|parsing
| 0 |
1,907,389 | 46,416,044 |
Casting User-Provided Numbers to Integers and Floats in Python
|
<p>I'm trying to create a change return program that takes in a cost of an item and the money given and returns the proper change in terms of notes, quarters, dimes, etc.</p>
<p>I'm fairly new to programming and I'm stuck on trying to split it up. I've looked on StackOverflow and found the method <code>math.modf(x)</code> to be relevant. However, I am having a hard time implementing it.</p>
<p>Can you please let me know why <code>change</code> and <code>y</code> <code>is not defined</code>?</p>
<p>Thanks</p>
<pre><code>import math
def changereturn():
quarter = 0.25
dime = 0.1
nickel = 0.05
penny = 0.01
cost = float(raw_input('Please enter the cost of the item in USD: '))
money = float(raw_input('Please enter the amount of money given in USD: '))
change = money - cost
y = math.modf(change)
return change
return y
</code></pre>
|
<p>A function (<code>def</code>) can only <code>return</code> one time, but python allows you to return tuples for result.</p>
<p>This implementation may be what you need:</p>
<pre><code>import math
def changereturn():
quarter = 0.25
dime = 0.1
nickel = 0.05
penny = 0.01
cost = float(input('Please enter the cost of the item in USD: '))
money = float(input('Please enter the amount of money given in USD: '))
change = money - cost
y = math.modf(change)
return change, y
print(changereturn())
</code></pre>
|
python|user-input
| 1 |
1,907,390 | 49,565,423 |
Where do I place a maya script if I'm gonna run it without launching maya?
|
<p>Is it possible to run a Maya Python script from outside Maya and see the result in Maya simultaneously?</p>
<p>If not, how to make my leap motion code work in Maya without terminating after closing the text input pop-up window?</p>
<p>I'm working on a project where I manipulate Maya Objects using a Leap Motion Device and Maya keeps asking me for a text Input and once I close it, it terminates leap motion code.</p>
<p>Any help?</p>
<p>You can find my code below:</p>
<pre><code> from os.path import join
import maya.standalone; maya.standalone.initialize()
import maya.cmds as cmds
import Leap, sys, thread, time
from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture, SwipeGesture
class LeapMotionListener(Leap.Listener) :
# Naming the fingers and bones and states
finger_names = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']
bone_names = ['Metacarpal', 'Proximal', 'Intermediate', 'Distal']
state_names = ['STATE_INVALID', 'STATE_START', 'STATE_UPDATE', 'STATE_END']
# Determines what happens when Initialized
def on_init(self, controller):
print("Initialized")
# Determines what happens when connected
def on_connect(self, controller):
print ("Motion Sensor Connected!")
controller.enable_gesture(Leap.Gesture.TYPE_CIRCLE);
controller.enable_gesture(Leap.Gesture.TYPE_KEY_TAP);
controller.enable_gesture(Leap.Gesture.TYPE_SCREEN_TAP);
controller.enable_gesture(Leap.Gesture.TYPE_SWIPE);
def on_disconnect(self, controller):
print("Motion Sensor Disconnected")
def on_exit(self, controller):
print("Exited")
def on_frame(self, controller):
frame = controller.frame()
for gesture in frame.gestures():
if gesture.type is Leap.Gesture.TYPE_CIRCLE:
circle = CircleGesture(gesture)
if circle.pointable.direction.angle_to(circle.normal) <= Leap.PI/2: #If Clockwise
clockwiseness = "clockwise"
else:
clockwiseness = "counter-clockwise"
swept_angle = 0
if circle.state != Leap.Gesture.STATE_START:
#We create a new Circle gesture, with the id of the gesture created by the previous frame
previous = CircleGesture(controller.frame(1).gesture(circle.id))
#We get the angle rotated from the previous frame till the current one
swept_angle = (circle.progress - previous.progress) * 2 * Leap.PI
print "ID: " + str(circle.id) + ", progress: " + str(circle.progress) + ", Radius (mm): " + str(circle.radius) \
+ ", Swept Angle: " + str(swept_angle * Leap.RAD_TO_DEG) + ", Direction: " + clockwiseness
#Create a polyCube when I do a circle gesture
result = cmds.polyCube(w = 9, h = 9 , d = 9, name ='myCube#')
def main():
listener = LeapMotionListener()
controller = Leap.Controller()
controller.add_listener(listener)
print("Press Enter to quit.")
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
finally:
controller.remove_listener(listener)
if __name__ == "__main__":
main()
</code></pre>
|
<p>You're asking maya for the text box in the lines</p>
<p><code>
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
finally:
controller.remove_listener(listener)
</code></p>
<p>But the input will block access to the scene. You should probably add a gesture to trigger the disconnection instead, that way you won't have anything to worry about from the text box. Without the SDK it's not easy to test, but something like this:</p>
<pre><code>class LeapMotionListener(Leap.Listener) :
#... other code here
def on_frame(self, controller):
frame = controller.frame()
for gesture in frame.gestures():
#.... other code here....
if gesture.type is Leap.Gesture.TYPE_SWIPE:
controller.remove_listener(this)
listener = LeapMotionListener()
controller = Leap.Controller()
controller.add_listener(listener)
</code></pre>
|
python|python-2.7|maya|leap-motion
| 0 |
1,907,391 | 53,638,903 |
Python Machine Learning Classifying Words in Sentence
|
<p>I want to make an personal assistant using artificial intelligence and machine learging techniques. I am using Python 3.7 and I have an question.</p>
<p>When software starts, first it will ask user's name. I want it to get user's name.</p>
<pre><code>in = input('Hey, what is your name?')
#some classifier things
#...
print = input('Nice to meet you ' + in + '!')
</code></pre>
<p>But I want to know name correctly if user enters an sentence.
Here is an example:</p>
<pre><code>Hey, what is your name?
John
Nice to meet you John!
</code></pre>
<p>But I want to get name even if person enters like this:</p>
<pre><code>Hey, what is your name?
It's John.
Nice to meet you John!
</code></pre>
<p>But I couldn't understand how can I just get the user's name. I think I should classify the words in sentence but I don't know. Can you help?</p>
|
<p>You need to get proper nouns. The below code does it:</p>
<pre><code>from nltk.tag import pos_tag
sentence = " It's John"
tagged_sent = pos_tag(sentence.split())
propernouns = [word for word,pos in tagged_sent if pos == 'NNP']
</code></pre>
|
python|python-3.x|machine-learning|artificial-intelligence|part-of-speech
| 0 |
1,907,392 | 40,233,979 |
How to write a python script to interact with shell scripts
|
<p>I encountered a problem in work. Here it is.</p>
<p>I have several scripts(mostly are shell scripts) to execute, and I want to write a python script to run them automatically. One of these shell scripts needs <strong>interactive input</strong> during it's execution. What troubled me is that I can't find a way to read its input prompt, so I can't decide what to enter to continue.</p>
<p>I simplified the problem to something like this:</p>
<p>There is a script named <code>mediator.py</code>, which run <code>greeter.sh</code> inside. The <code>mediator</code> takes <code>greeter</code>'s input prompt and print it to the user, then gets user's input and pass it to <code>greeter</code>. The <code>mediator</code> needs to act exactly the same as the <code>greeter</code> from user's point of view.</p>
<p>Here is <code>greeter.sh</code>:</p>
<pre><code>#! /bin/bash
echo "Please enter your name: " # <- I want 'mediator.py' to read this prompt and show it to me, and then get what I input, then pass my input to 'greeter.sh'
read name
echo "Hello, " $name
</code></pre>
<p>I want to do this in the following order:</p>
<ol>
<li>The user (that's me) run <code>mediator.py</code></li>
<li>The <code>mediator</code> run <code>greeter.sh</code> inside</li>
<li>The <code>mediator</code> <strong>get the input prompt of <code>greeter</code></strong>, and output it on the screen.<em>(At this time, the <code>greeter</code> is waiting for user's input. This is the main problem I stuck with)</em></li>
<li>The user input a string (for example, 'Mike'), <code>mediator</code> get the string 'Mike' and transmit it to <code>greeter</code></li>
<li>The <code>greeter</code> get the name 'Mike', and print a greeting</li>
<li>The <code>mediator</code> get the greeting, and output it on the screen.</li>
</ol>
<p>I searched for some solution and determined to use <code>Popen</code> function in <code>subprocess</code> module with <code>stdout</code> of sub-process directed to <code>PIPE</code>, it's something like this:</p>
<pre><code>sb = subprocess.Popen(['sh', 'greeter.sh'], stdout = subprocess.PIPE, stdin = stdout, stderr = stdout)
</code></pre>
<p>but I can't solve the main problem in <strong>step 3</strong> above. Can anyone give me some advice for help? Thanks very much!</p>
|
<p>You make it much more complicated (and brittle) than it has to be. Instead of coding everything at the top-level and try to use subprocess or whatever to use your scripts as if they where functions, just write modules and functions and use them from your main script. </p>
<p>Here's an example with all contained in the script itself, but you can split it into distinct modules if you need to share some functions between different scripts</p>
<pre><code># main.py
def ask_name():
return raw_input("Please enter your name: ")
def greet(name):
return "Hello, {} name !\n".format(name)
def main():
name = ask_name()
print greet(name)
if __name__ == "__main__":
main()
</code></pre>
|
python|shell|subprocess|nonblocking|python-interactive
| 0 |
1,907,393 | 52,053,491 |
A command without name, in Click
|
<p>I want to have a command line tool with a usage like this:</p>
<pre><code>$ program <arg> does something, no command name required
$ program cut <arg>
$ program eat <arg>
</code></pre>
<p>The Click code would look like this:</p>
<pre><code>@click.group()
def main() :
pass
@main.command()
@click.argument('arg')
def noname(arg) :
# does stuff
@main.command()
@click.argument('arg')
def cut(arg) :
# cuts stuff
@main.command()
@click.argument('arg')
def eat(arg) :
# eats stuff
</code></pre>
<p>My problem is that with this code, there is always a required command name, ie: I need to run <code>$ program noname arg</code>. But I want to be able to run <code>$ program arg</code>. </p>
|
<p><a href="https://github.com/click-contrib/click-default-group" rel="noreferrer">click-default-group</a> is doing what you are looking for. It is part of the click-contrib collection.</p>
<p>The advantage of that instead of using <code>invoke_without_command</code> is that it passes the options and arguments flawlessly to the default command, something that is not trivial (or even possible) with the built-in functionality.</p>
<p>Example code:</p>
<pre class="lang-py prettyprint-override"><code>import click
from click_default_group import DefaultGroup
@click.group(cls=DefaultGroup, default='foo', default_if_no_args=True)
def cli():
print("group execution")
@cli.command()
@click.option('--config', default=None)
def foo(config):
click.echo('foo execution')
if config:
click.echo(config)
</code></pre>
<p>Then, it's possible to call <code>foo</code> command with its option as:</p>
<pre><code>$ program foo --config bar <-- normal way to call foo
$ program --config bar <-- foo is called and the option is forwarded.
Not possible with vanilla Click.
</code></pre>
|
python|python-click
| 6 |
1,907,394 | 39,711,271 |
Pandas keep only index with values in both columns
|
<p>I have a DataFrame with an index called <code>SubjectID</code> two columns with integer values. I want to keep only Subjects that have values in the <code>Value 1</code> column and the <code>Value 2</code> column, and get rid of Subjects that have only one value. </p>
<p>Here is an example of my data frame: </p>
<pre><code>SubjectID Value1 Value2
B1 1.57 1.75
B2 N/A 1.56
</code></pre>
<p>So I would only want to keep the first row. Here is the code I have written so far:</p>
<pre><code>df_to_add = []
for sub in df.index:
values = df.loc[df.index]['Value1']['Value2']
if type(values) is pd.Series: # check that subject had multiple values, don't want otherwise
array = values.values
if "'Value1'" in scans_array and "'Value2'" in array:
df_to_add.append(df.loc[df.index])
else:
pass
</code></pre>
|
<p>Assuming your <code>N/A</code> is an actual <code>NaN</code>, you can simply <code>.dropna()</code> your DataFrame:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'SubjectID': ['B1', 'B2'],
'Value1': [1.57, float('nan')],
'Value2': [1.75, 1.56]})
df = df.set_index('SubjectID')
print(df)
# Value1 Value2
# SubjectID
# B1 1.57 1.75
# B2 NaN 1.56
print(df.dropna())
# Value1 Value2
# SubjectID
# B1 1.57 1.75
</code></pre>
|
pandas|dataframe
| 2 |
1,907,395 | 27,200,844 |
How to get parent classes of class in my meta class?
|
<p>I have the <a href="http://ideone.com/XFRDr5" rel="nofollow">following script</a>:</p>
<pre><code>#!/usr/bin/python3
class MyMeta(type):
def __new__(mcs, name, bases, dct):
print(name + " " + str(bases))
return super(MyMeta, mcs).__new__(mcs, name, bases, dct)
class A(metaclass=MyMeta):
def foo(self):
pass
class B(A):
pass
class C(B):
def foo(self):
pass
def main():
pass
if __name__ == "__main__":
main()
</code></pre>
<p>I get the following output:</p>
<pre><code>A ()
B (<class '__main__.A'>,)
C (<class '__main__.B'>,)
</code></pre>
<p>But I expect it:</p>
<pre><code>A ()
B (<class '__main__.A'>,)
C (<class '__main__.B'>, <class '__main__.A'>)
</code></pre>
<p>Where I make a mistake?</p>
|
<p><code>bases</code> parameter list base classes listed in the class definition.</p>
<p>It seems like you want <a href="https://docs.python.org/3/library/stdtypes.html#class.mro" rel="nofollow"><code>class.mro</code></a>:</p>
<pre><code>class MyMeta(type):
def __new__(mcs, name, bases, dct):
ret = super(MyMeta, mcs).__new__(mcs, name, bases, dct)
print(name + " " + str(ret.mro()[1:-1]))
return ret
</code></pre>
|
inheritance|python-3.x|metaprogramming|metaclass|python-datamodel
| 1 |
1,907,396 | 41,907,071 |
IPython : groupby column to find processing time
|
<p>I have a dataframe which produces output as </p>
<pre><code>COL1 COL 2 COL3
abc 143613948 143614469
abc 143613945 143614466
xyz 164859569 164901557
xyz 164859531 164900406
</code></pre>
<p>How can COL1 be grouped to derive a new column which is max(COL3) - min (COL2)?</p>
<p>Desired output will look like dataframe: </p>
<pre><code>COL1 COL4
abc 524
xyz 42026
</code></pre>
|
<p>using <code>agg</code></p>
<pre><code>agg = df.groupby('COL1').agg(dict(COL2='min', COL3='max'))
(agg.COL3 - agg.COL2).reset_index(name='COL4')
COL1 COL4
0 abc 524
1 xyz 42026
</code></pre>
<p>using <code>apply</code></p>
<pre><code>df.groupby('COL1').apply(
lambda d: d.COL3.max() - d.COL2.min()).reset_index(name='COL4')
COL1 COL4
0 abc 524
1 xyz 42026
</code></pre>
|
pandas|ipython
| 1 |
1,907,397 | 64,467,556 |
Beautifulsoup doesn't show all html elements
|
<p>I am fairly new to scraping and tried to get a list of companies from this <a href="https://www.kimaventures.com/portfolio/" rel="nofollow noreferrer">webpage</a> with this code:</p>
<pre><code>import requests
import bs4
base_url = 'https://www.kimaventures.com/portfolio/'
res = requests.get(base_url)
soup = bs4.BeautifulSoup(res.text,"lxml")
soup
</code></pre>
<p>Does anyone know why I can't access all the html from the page?</p>
<p>Thanks for your help</p>
|
<p>You can do a get <a href="https://www.payitforward.vc/api/portfolio/VV7gXduVxznYhTZuZZP39Y/" rel="nofollow noreferrer">https://www.payitforward.vc/api/portfolio/VV7gXduVxznYhTZuZZP39Y/</a> to get at the JSON that the page loads. (Too busy to do this in python.)</p>
<pre><code>curl "https://www.payitforward.vc/api/portfolio/VV7gXduVxznYhTZuZZP39Y/" ^
-H "Connection: keep-alive" ^
-H "Pragma: no-cache" ^
-H "Cache-Control: no-cache" ^
-H "Accept: application/json, text/plain, */*" ^
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36" ^
-H "DNT: 1" ^
-H "Origin: https://www.kimaventures.com" ^
-H "Sec-Fetch-Site: cross-site" ^
-H "Sec-Fetch-Mode: cors" ^
-H "Sec-Fetch-Dest: empty" ^
-H "Referer: https://www.kimaventures.com/" ^
-H "Accept-Language: en-US,en;q=0.9,fil;q=0.8"
</code></pre>
|
python|web-scraping|beautifulsoup
| 2 |
1,907,398 | 64,613,184 |
Newton's Method with Looping Recursion
|
<p>I have the code here all figured out. The directions say to <strong>"Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton. (Hint: The estimate of the square root should be passed as a second argument to the function.)"</strong>
How would I work out these directions according to my code here?</p>
<pre><code># Initialize the tolerance
TOLERANCE = 0.000001
def newton(x):
"""Returns the square root of x."""
# Perform the successive approximations
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= TOLERANCE:
break
return estimate
def main():
"""Allows the user to obtain square roots."""
while True:
# Receive the input number from the user
x = input("Enter a positive number or enter/return to quit: ")
if x == "":
break
x = float(x)
# Output the result
print("The program's estimate is", newton(x))
print("Python's estimate is ", math.sqrt(x))
if __name__ == "__main__":
main()
</code></pre>
|
<p>essentialy you need to convert the <code>while True:</code> part of your code in the recursive function
something like this:</p>
<pre><code>def newton(x, estimate):
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference > TOLERANCE:
estimate = newton(x, estimate)
return estimate
</code></pre>
<p>notice how the condition is different so you check if you need to continue, after you don't the final value is carried along out of the recursion and returned</p>
|
python|recursion
| 2 |
1,907,399 | 64,460,498 |
Transport equation in 1D (python)
|
<p>I'm trying to write a python program to solve the convection equation in 1D using the finite differences method (upwind scheme). The problem is as follows:</p>
<p>Here's what I've attempted</p>
<pre><code>from numpy import *
from numpy.linalg import *
from matplotlib.pyplot import *
def u0(x):
if (0.4 <= x <= 0.5):
y = 10*(x - 0.4)
elif (0.5 <= x <= 0.6):
y = 10*(0.6 - x)
else:
y = 0
return y
print('Choix de la vitesse de transport c : ')
c = float(input('c = '))
def solex(x, t):
return u0(x - c*t)
print('Choix de pas h : ')
h = float(input('h = '))
print('Choix du pas dt et du temps final T : ')
dt = float(input('dt = '))
T = float(input('T = '))
# Maillage
N = int((1/h) - 1)
x = linspace(0, 1, N + 2)
M = int((T/dt) - 1)
t = linspace(0, T, M + 2)
# Itération
U1 = zeros(N)
U2 = zeros(N)
sol = zeros((N, M + 2))
for i in range(1, N + 1):
U1[i - 1] = u0(x[i])
sol[:, 0] = U1
for j in range(1, size(t)):
for i in range(1, N-1):
U2[i] = U1[i] - c*(dt/h)*(U1[i] - U1[i - 1])
sol[:, j] = U2
U1 = U2
</code></pre>
<p>It doesn't seem to work and I don't know why</p>
|
<p>Though you said you already solved your problem, I would still like to suggest some general improvements:</p>
<ol>
<li>wildcard imports like <code>from numpy import *</code> are considered bad practice, better use <code>import numpy as np</code> and refer to the necessary functions as <code>np.linspace</code> etc.</li>
<li>the power of <code>numpy</code> comes from vectorization, so try to replace as much <code>for</code>-loops as possible by vectorized operations.</li>
<li>at least from what you showed us, the variables <code>U1</code> and <code>U2</code> are not really necessary.</li>
<li>using <code>input</code> for every single parameter might be overkill</li>
</ol>
<p>The following code includes my suggested improvements. Note how I replaced your <code>u0</code> with a vectorized version using <code>np.piecewise</code> and replaced several <code>for</code>-loops. I also added a visualisation.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def u0(x):
y= np.piecewise(
x,
[(0.4 <= x)&(x <= 0.5), (0.5 <= x)&(x<= 0.6) ],
[lambda x: 10*(x - 0.4), lambda x: 10*(0.6 - x), 0])
return y
c = 0.9
h = 0.01
dt = 0.01
T = 2
N = int(np.ceil(1/h))
x = np.linspace(0, 1, N)
M = int(np.ceil(T/dt))
t = np.linspace(0, T, M)
#solve with upwind scheme
sol = np.zeros((N, M))
sol[:,0] = u0(x)
#you could add boundary values here by setting
#sol[0,:] = <your_boundary_data>
for i in range(1,len(t)):
sol[1:,i] = sol[1:,i-1] - c*(dt/h)*(sol[1:,i-1] - sol[:-1,i-1])
#Visualization
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_xlabel('x')
ax.set_ylabel('t')
T, X = np.meshgrid(t, x)
surf = ax.plot_surface(X, T, sol)
</code></pre>
|
python|differential-equations
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.