title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Access to Django settings using Redis
| 39,427,603 |
<p>I have a project on Heroku. I just recently added Redis for job queueing through Heroku's add-ons feature.</p>
<p>I've followed Heroku's simple <a href="https://devcenter.heroku.com/articles/python-rq" rel="nofollow">tutorial</a> to get things up and running.</p>
<p>I call the function like so:
<code>result = q.enqueue(some_other_class.some_function, some_argument)</code></p>
<p>In <code>some_function</code> there is a call to a variable from the Django's settings file. I follow the normal procedure, which works without Redis: <code>from django.conf import settings</code> and then get the variable <code>settings.THE_VARIABLE</code>.</p>
<p>When I use Redis though, that doesn't work. I get the error: </p>
<p><code>ImproperlyConfigured: Requested setting THE_VARIABLE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings</code></p>
<p>The <code>DJANGO_SETTINGS_MODULE</code> variable is set. Does the worker not have access to Django settings? If so, how can I get around this?</p>
| 0 |
2016-09-10T15:31:15Z
| 39,460,208 |
<p>Someone with the power please close this question.</p>
<p>It turns at that <code>DJANGO_SETTINGS_MODULE</code> was not set properly.</p>
| 0 |
2016-09-12T23:32:20Z
|
[
"python",
"django",
"heroku"
] |
Adding/Updating object to/in nested array in mongodb
| 39,427,607 |
<p>I have a document:</p>
<pre><code>{
"_id": "57d421bbbc44538f0634081c",
"in_date": "1473724800",
"bboxes": [
{ "bbox_index": "4124432432311", "data": {} },
{ "bbox_index": "4124435342332", "data": {} },
...
]
}
</code></pre>
<p>I'm trying to update entire object found in <code>bboxes</code> with specific <code>bboxes.bbox_index</code>:</p>
<pre><code>bbox_index = 4124432432311
in_date = 1473724800
self.db['my_table'].update(
{
'in_date': in_date,
'bboxes.bbox_index': bbox_index
},
{
'$set': {'bboxes.$': dict(item)}
},
upsert=True
)
</code></pre>
<p>I expect this object <code>{ "bbox_index": "4124432432311", "data": {} }</code> to be replaced with <code>dict(item)</code></p>
<p>This works fine when object with required <code>bbox_index</code> already exists. When it doesn't exist, I get <code>The positional operator did not find the match needed from the query. Unexpanded update: bboxes.$</code></p>
<p>In order to make it work I have to do the same query but instead of <code>$set</code> do <code>{'$push': {'bboxes': dict(item)}}</code>. Of course, this doesn't work well when I do already have required object in database. In this case I'm pushing same object again. Possible solution would be to check for the object before updating it but I wanted to make it in one single expression. I thought <code>upsert=True</code> was made exactly for this purpose. Is there any way to do what I want?</p>
| 1 |
2016-09-10T15:31:28Z
| 39,608,868 |
<p>Instead of using <code>$push</code>, you can use <code>$addToSet</code> which will insert a new entry in the array only if the entry doesn't exist yet.</p>
<p>To paraphrase the relevant manual page <a href="https://docs.mongodb.com/manual/reference/operator/update/addToSet/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/update/addToSet/</a>:</p>
<blockquote>
<p>The <strong>$addToSet</strong> operator adds a value to an array unless the value is already present, in which case <strong>$addToSet</strong> does nothing to that array.</p>
</blockquote>
| 0 |
2016-09-21T06:22:25Z
|
[
"python",
"mongodb",
"pymongo"
] |
How to traverse cyclic directed graphs with modified DFS algorithm
| 39,427,638 |
<p><strong>OVERVIEW</strong></p>
<p>I'm trying to figure out how to traverse <strong>directed cyclic graphs</strong> using some sort of DFS iterative algorithm. Here's a little mcve version of what I currently got implemented (it doesn't deal with cycles):</p>
<pre><code>class Node(object):
def __init__(self, name):
self.name = name
def start(self):
print '{}_start'.format(self)
def middle(self):
print '{}_middle'.format(self)
def end(self):
print '{}_end'.format(self)
def __str__(self):
return "{0}".format(self.name)
class NodeRepeat(Node):
def __init__(self, name, num_repeats=1):
super(NodeRepeat, self).__init__(name)
self.num_repeats = num_repeats
def dfs(graph, start):
"""Traverse graph from start node using DFS with reversed childs"""
visited = {}
stack = [(start, "")]
while stack:
# To convert dfs -> bfs
# a) rename stack to queue
# b) pop becomes pop(0)
node, parent = stack.pop()
if parent is None:
if visited[node] < 3:
node.end()
visited[node] = 3
elif node not in visited:
if visited.get(parent) == 2:
parent.middle()
elif visited.get(parent) == 1:
visited[parent] = 2
node.start()
visited[node] = 1
stack.append((node, None))
# Maybe you want a different order, if it's so, don't use reversed
childs = reversed(graph.get(node, []))
for child in childs:
if child not in visited:
stack.append((child, node))
if __name__ == "__main__":
Sequence1 = Node('Sequence1')
MtxPushPop1 = Node('MtxPushPop1')
Rotate1 = Node('Rotate1')
Repeat1 = NodeRepeat('Repeat1', num_repeats=2)
Sequence2 = Node('Sequence2')
MtxPushPop2 = Node('MtxPushPop2')
Translate = Node('Translate')
Rotate2 = Node('Rotate2')
Rotate3 = Node('Rotate3')
Scale = Node('Scale')
Repeat2 = NodeRepeat('Repeat2', num_repeats=3)
Mesh = Node('Mesh')
cyclic_graph = {
Sequence1: [MtxPushPop1, Rotate1],
MtxPushPop1: [Sequence2],
Rotate1: [Repeat1],
Sequence2: [MtxPushPop2, Translate],
Repeat1: [Sequence1],
MtxPushPop2: [Rotate2],
Translate: [Rotate3],
Rotate2: [Scale],
Rotate3: [Repeat2],
Scale: [Mesh],
Repeat2: [Sequence2]
}
dfs(cyclic_graph, Sequence1)
print '-'*80
a = Node('a')
b = Node('b')
dfs({
a : [b],
b : [a]
}, a)
</code></pre>
<p>The above code is testing a couple of cases, the first would be some sort of representation of the below graph:</p>
<p><a href="http://i.stack.imgur.com/s2DSc.png"><img src="http://i.stack.imgur.com/s2DSc.png" alt="enter image description here"></a></p>
<p>The second one is the simplest case of one graph containing one "infinite" loop <code>{a->b, b->a}</code></p>
<p><strong>REQUIREMENTS</strong></p>
<ul>
<li>There won't exist such a thing like "infinite cycles", let's say when one "infinite cycle" is found, there will be a maximum threshold (global var) to indicate when to stop looping around those "pseudo-infinite cycles"</li>
<li>All graph nodes are able to create cycles but there will exist a special node called <code>Repeat</code> where you can indicate how many iterations to loop around the cycle</li>
<li>The above mcve I've posted is an iterative version of the traversal algorithm which <strong>doesn't know how to deal with cyclic graphs</strong>. Ideally the solution would be also iterative but if there exists a much better recursive solution, that'd be great</li>
<li>The data structure we're talking about here shouldn't be called "directed acyclic graphs" really because in this case, <strong>each node has its children ordered</strong>, and in graphs node connections have no order. </li>
<li>Everything can be connected to anything in the editor. You'll be able to execute any block combination and the only limitation is the execution counter, which will overflow if you made neverending loop or too many iterations.</li>
<li>The algorithm will preserve start/middle/after node's method execution similarly than the above snippet</li>
</ul>
<p><strong>QUESTION</strong></p>
<p>Could anyone provide some sort of solution which knows how to traverse infinite/finite cycles?</p>
<p><strong>REFERENCES</strong></p>
<p>If question is not clear yet at this point, you can read this more about this problem on this <a href="http://www.bitfellas.org/e107_plugins/content/content.php?content.674">article</a>, the whole idea will be using the traversal algorithm to implement a similar tool like the shown in that article. </p>
<p>Here's a screenshot showing up the whole power of this type of data structure I want to figure out how to traverse&run:</p>
<p><a href="http://i.stack.imgur.com/N2OtM.jpg"><img src="http://i.stack.imgur.com/N2OtM.jpg" alt="enter image description here"></a></p>
| 22 |
2016-09-10T15:34:11Z
| 39,456,032 |
<p>Before I start, <a href="http://www.codeskulptor.org/#user42_MYuqELNPFl_7.py" rel="nofollow">Run the code on CodeSkulptor!</a> I also hope that the comments elaborate what I have done enough. If you need more explanation, look at my explanation of the <em>recursive</em> approach below the code.</p>
<pre><code># If you don't want global variables, remove the indentation procedures
indent = -1
MAX_THRESHOLD = 10
INF = 1 << 63
def whitespace():
global indent
return '| ' * (indent)
class Node:
def __init__(self, name, num_repeats=INF):
self.name = name
self.num_repeats = num_repeats
def start(self):
global indent
if self.name.find('Sequence') != -1:
print whitespace()
indent += 1
print whitespace() + '%s_start' % self.name
def middle(self):
print whitespace() + '%s_middle' % self.name
def end(self):
global indent
print whitespace() + '%s_end' % self.name
if self.name.find('Sequence') != -1:
indent -= 1
print whitespace()
def dfs(graph, start):
visits = {}
frontier = [] # The stack that keeps track of nodes to visit
# Whenever we "visit" a node, increase its visit count
frontier.append((start, start.num_repeats))
visits[start] = visits.get(start, 0) + 1
while frontier:
# parent_repeat_count usually contains vertex.repeat_count
# But, it may contain a higher value if a repeat node is its ancestor
vertex, parent_repeat_count = frontier.pop()
# Special case which signifies the end
if parent_repeat_count == -1:
vertex.end()
# We're done with this vertex, clear visits so that
# if any other node calls us, we're still able to be called
visits[vertex] = 0
continue
# Special case which signifies the middle
if parent_repeat_count == -2:
vertex.middle()
continue
# Send the start message
vertex.start()
# Add the node's end state to the stack first
# So that it is executed last
frontier.append((vertex, -1))
# No more children, continue
# Because of the above line, the end method will
# still be executed
if vertex not in graph:
continue
## Uncomment the following line if you want to go left to right neighbor
#### graph[vertex].reverse()
for i, neighbor in enumerate(graph[vertex]):
# The repeat count should propagate amongst neighbors
# That is if the parent had a higher repeat count, use that instead
repeat_count = max(1, parent_repeat_count)
if neighbor.num_repeats != INF:
repeat_count = neighbor.num_repeats
# We've gone through at least one neighbor node
# Append this vertex's middle state to the stack
if i >= 1:
frontier.append((vertex, -2))
# If we've not visited the neighbor more times than we have to, visit it
if visits.get(neighbor, 0) < MAX_THRESHOLD and visits.get(neighbor, 0) < repeat_count:
frontier.append((neighbor, repeat_count))
visits[neighbor] = visits.get(neighbor, 0) + 1
def dfs_rec(graph, node, parent_repeat_count=INF, visits={}):
visits[node] = visits.get(node, 0) + 1
node.start()
if node not in graph:
node.end()
return
for i, neighbor in enumerate(graph[node][::-1]):
repeat_count = max(1, parent_repeat_count)
if neighbor.num_repeats != INF:
repeat_count = neighbor.num_repeats
if i >= 1:
node.middle()
if visits.get(neighbor, 0) < MAX_THRESHOLD and visits.get(neighbor, 0) < repeat_count:
dfs_rec(graph, neighbor, repeat_count, visits)
node.end()
visits[node] = 0
Sequence1 = Node('Sequence1')
MtxPushPop1 = Node('MtxPushPop1')
Rotate1 = Node('Rotate1')
Repeat1 = Node('Repeat1', 2)
Sequence2 = Node('Sequence2')
MtxPushPop2 = Node('MtxPushPop2')
Translate = Node('Translate')
Rotate2 = Node('Rotate2')
Rotate3 = Node('Rotate3')
Scale = Node('Scale')
Repeat2 = Node('Repeat2', 3)
Mesh = Node('Mesh')
cyclic_graph = {
Sequence1: [MtxPushPop1, Rotate1],
MtxPushPop1: [Sequence2],
Rotate1: [Repeat1],
Sequence2: [MtxPushPop2, Translate],
Repeat1: [Sequence1],
MtxPushPop2: [Rotate2],
Translate: [Rotate3],
Rotate2: [Scale],
Rotate3: [Repeat2],
Scale: [Mesh],
Repeat2: [Sequence2]
}
dfs(cyclic_graph, Sequence1)
print '-'*40
dfs_rec(cyclic_graph, Sequence1)
print '-'*40
dfs({Sequence1: [Translate], Translate: [Sequence1]}, Sequence1)
print '-'*40
dfs_rec({Sequence1: [Translate], Translate: [Sequence1]}, Sequence1)
</code></pre>
<p>The input and (well formatted and indented) output can be found <a href="http://www.hastebin.com/etedihayay.py" rel="nofollow">here</a>. If you want to see <em>how</em> I formatted the output, please refer to the code, which can also be <a href="http://www.codeskulptor.org/#user42_MYuqELNPFl_7.py" rel="nofollow">found on CodeSkulptor</a>.</p>
<hr>
<p>Right, on to the explanation. The easier to understand but much more inefficient recursive solution, which I'll use to help explain, follows:</p>
<pre><code>def dfs_rec(graph, node, parent_repeat_count=INF, visits={}):
visits[node] = visits.get(node, 0) + 1
node.start()
if node not in graph:
node.end()
return
for i, neighbor in enumerate(graph[node][::-1]):
repeat_count = max(1, parent_repeat_count)
if neighbor.num_repeats != INF:
repeat_count = neighbor.num_repeats
if i >= 1:
node.middle()
if visits.get(neighbor, 0) < MAX_THRESHOLD and visits.get(neighbor, 0) < repeat_count:
dfs_rec(graph, neighbor, repeat_count, visits)
node.end()
visits[node] = 0
</code></pre>
<ol>
<li>The first thing we do is visit the node. We do this by incrementing the number of visits of the node in the dictionary.</li>
<li>We then raise the <code>start</code> event of the node.</li>
<li>We do a simple check to see if the node is a childless (leaf) node or not. If it is, we raise the <code>end</code> event and return.</li>
<li>Now that we've established that the node has neighbors, we iterate through each neighbor. <strong>Side Note:</strong> I reverse the neighbor list (by using <code>graph[node][::-1]</code>) in the recursive version to maintain the same order (right to left) of traversal of neighbors as in the iterative version.
<ol>
<li>For each neighbor, we first calculate the repeat count. The repeat count propagates (is inherited) through from the ancestor nodes, so the inherited repeat count is used <em>unless</em> the <em>neighbor</em> contains a repeat count value.</li>
<li>We raise the <code>middle</code> event of the current node (<strong>not</strong> the neighbor) if the second (or greater) neighbor is being processed.</li>
<li>If the neighbor can be visited, the neighbor is visited. The visitability check is done by checking whether the neighbor has been visited less than a) <code>MAX_THRESHOLD</code> times (for pseudo-infinite cycles) and b) the above calculated repeat count times.</li>
</ol></li>
<li>We're now done with this node; raise the <code>end</code> event and clear its visits in the hashtable. This is done so that if some other node calls it again, it does not fail the visitability check and/or execute for less than the required number of times.</li>
</ol>
| 7 |
2016-09-12T17:54:10Z
|
[
"python",
"algorithm",
"python-2.7",
"depth-first-search",
"demoscene"
] |
How to traverse cyclic directed graphs with modified DFS algorithm
| 39,427,638 |
<p><strong>OVERVIEW</strong></p>
<p>I'm trying to figure out how to traverse <strong>directed cyclic graphs</strong> using some sort of DFS iterative algorithm. Here's a little mcve version of what I currently got implemented (it doesn't deal with cycles):</p>
<pre><code>class Node(object):
def __init__(self, name):
self.name = name
def start(self):
print '{}_start'.format(self)
def middle(self):
print '{}_middle'.format(self)
def end(self):
print '{}_end'.format(self)
def __str__(self):
return "{0}".format(self.name)
class NodeRepeat(Node):
def __init__(self, name, num_repeats=1):
super(NodeRepeat, self).__init__(name)
self.num_repeats = num_repeats
def dfs(graph, start):
"""Traverse graph from start node using DFS with reversed childs"""
visited = {}
stack = [(start, "")]
while stack:
# To convert dfs -> bfs
# a) rename stack to queue
# b) pop becomes pop(0)
node, parent = stack.pop()
if parent is None:
if visited[node] < 3:
node.end()
visited[node] = 3
elif node not in visited:
if visited.get(parent) == 2:
parent.middle()
elif visited.get(parent) == 1:
visited[parent] = 2
node.start()
visited[node] = 1
stack.append((node, None))
# Maybe you want a different order, if it's so, don't use reversed
childs = reversed(graph.get(node, []))
for child in childs:
if child not in visited:
stack.append((child, node))
if __name__ == "__main__":
Sequence1 = Node('Sequence1')
MtxPushPop1 = Node('MtxPushPop1')
Rotate1 = Node('Rotate1')
Repeat1 = NodeRepeat('Repeat1', num_repeats=2)
Sequence2 = Node('Sequence2')
MtxPushPop2 = Node('MtxPushPop2')
Translate = Node('Translate')
Rotate2 = Node('Rotate2')
Rotate3 = Node('Rotate3')
Scale = Node('Scale')
Repeat2 = NodeRepeat('Repeat2', num_repeats=3)
Mesh = Node('Mesh')
cyclic_graph = {
Sequence1: [MtxPushPop1, Rotate1],
MtxPushPop1: [Sequence2],
Rotate1: [Repeat1],
Sequence2: [MtxPushPop2, Translate],
Repeat1: [Sequence1],
MtxPushPop2: [Rotate2],
Translate: [Rotate3],
Rotate2: [Scale],
Rotate3: [Repeat2],
Scale: [Mesh],
Repeat2: [Sequence2]
}
dfs(cyclic_graph, Sequence1)
print '-'*80
a = Node('a')
b = Node('b')
dfs({
a : [b],
b : [a]
}, a)
</code></pre>
<p>The above code is testing a couple of cases, the first would be some sort of representation of the below graph:</p>
<p><a href="http://i.stack.imgur.com/s2DSc.png"><img src="http://i.stack.imgur.com/s2DSc.png" alt="enter image description here"></a></p>
<p>The second one is the simplest case of one graph containing one "infinite" loop <code>{a->b, b->a}</code></p>
<p><strong>REQUIREMENTS</strong></p>
<ul>
<li>There won't exist such a thing like "infinite cycles", let's say when one "infinite cycle" is found, there will be a maximum threshold (global var) to indicate when to stop looping around those "pseudo-infinite cycles"</li>
<li>All graph nodes are able to create cycles but there will exist a special node called <code>Repeat</code> where you can indicate how many iterations to loop around the cycle</li>
<li>The above mcve I've posted is an iterative version of the traversal algorithm which <strong>doesn't know how to deal with cyclic graphs</strong>. Ideally the solution would be also iterative but if there exists a much better recursive solution, that'd be great</li>
<li>The data structure we're talking about here shouldn't be called "directed acyclic graphs" really because in this case, <strong>each node has its children ordered</strong>, and in graphs node connections have no order. </li>
<li>Everything can be connected to anything in the editor. You'll be able to execute any block combination and the only limitation is the execution counter, which will overflow if you made neverending loop or too many iterations.</li>
<li>The algorithm will preserve start/middle/after node's method execution similarly than the above snippet</li>
</ul>
<p><strong>QUESTION</strong></p>
<p>Could anyone provide some sort of solution which knows how to traverse infinite/finite cycles?</p>
<p><strong>REFERENCES</strong></p>
<p>If question is not clear yet at this point, you can read this more about this problem on this <a href="http://www.bitfellas.org/e107_plugins/content/content.php?content.674">article</a>, the whole idea will be using the traversal algorithm to implement a similar tool like the shown in that article. </p>
<p>Here's a screenshot showing up the whole power of this type of data structure I want to figure out how to traverse&run:</p>
<p><a href="http://i.stack.imgur.com/N2OtM.jpg"><img src="http://i.stack.imgur.com/N2OtM.jpg" alt="enter image description here"></a></p>
| 22 |
2016-09-10T15:34:11Z
| 39,465,446 |
<p>As per <a href="http://stackoverflow.com/questions/39427638/how-to-traverse-cyclic-directed-graphs-with-modified-dfs-algorithm#comment66244567_39427638">comment66244567</a> - reducing the graph to a tree by ignoring links to visited nodes and performing a breadth-first search, as this would produce a more natural-looking (and likely more balanced) tree:</p>
<pre><code>def traverse(graph,node,process):
seen={node}
current_level=[node]
while current_level:
next_level=[]
for node in current_level:
process(node)
for child in (link for link in graph.get(node,[]) if link not in seen):
next_level.append(child)
seen.add(child)
current_level=next_level
</code></pre>
<p>With your graph and <code>def process(node): print node</code>, this produces:</p>
<pre><code>In [24]: traverse(cyclic_graph,Sequence1,process)
Sequence1
MtxPushPop1
Rotate1
Sequence2
Repeat1
MtxPushPop2
Translate
Rotate2
Rotate3
Scale
Repeat2
Mesh
</code></pre>
<p>The other BFS algorithm, <a href="http://stackoverflow.com/questions/34821242/non-recursive-breadth-first-traversal-without-a-queue/34821397#34821397">iterative deepening DFS</a> (uses less memory at the cost of speed) isn't going to win you anything in this case: since you have to store references to visited nodes, you already consume <em>O(n)</em> memory. Neither you need to produce intermediate results (but you can anyway - e.g. <code>yield</code> something after processing a level).</p>
| 1 |
2016-09-13T08:27:56Z
|
[
"python",
"algorithm",
"python-2.7",
"depth-first-search",
"demoscene"
] |
How to send parameters in bitstamp api using python requests module
| 39,427,756 |
<p>I am trying to use Bitstamp api and am able to successfully call any thing that only requires key, signature, and nonce parameters. However, when I try transferring or ordering, which require additional parameters like address or price and amount, my request seems to get messed up. I am new to programming, apis and requests. </p>
<pre><code>def sell(self, product):
nonce = self.get_nonce() #an integer time.time()*10000
btc = self.get_btc_bal() #float
price = self.get_btcusd_bid() #float
amount = float(str(btc)[:5])
message = str(nonce) + self.customer_id + self.api_key
signature = hmac.new(self.api_secret, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
r = requests.post(self.url + 'sell/btcusd/', params={'key':self.api_key, 'signature':signature, 'nonce': nonce, 'amount': amount, 'price':price})
r = r.json()
print(r)
print('open sell order in Bitstamp for %s BTC at %s USD'%(amount,price))
</code></pre>
<p>My exact question is how to format/organize/code the parameters correctly. when i send it like so, it returns </p>
<pre><code>{"status": "error", "reason": "Missing key, signature and nonce parameters.", "code": "API0000"}
</code></pre>
<p>if i don't use <code>params=</code> it returns</p>
<pre><code>{"status": "error", "reason": "Invalid nonce", "code": "API0004"}
</code></pre>
<p>I don't believe the nonce reason because I use the exact same get_nonce() method for all my requests. I hope someone can see where I am wrong please and thank you</p>
| 0 |
2016-09-10T15:44:48Z
| 39,429,943 |
<p>You should be using <em>data =</em> not <em>params</em>:</p>
<pre><code>requests.post(self.url + 'sell/btcusd/', data={'key':self.api_key, 'signature':signature, 'nonce': nonce, 'amount': amount, 'price':price})
</code></pre>
<p>When you use <em>data =</em>, the data is sent in the body of the request:</p>
<pre><code>In [17]: req = requests.post("https://httpbin.org/post", data=data)
In [18]: req.request.body
Out[18]: 'foo=bar'
In [19]: req.json()
Out[19]:
{u'args': {},
u'data': u'',
u'files': {},
u'form': {u'foo': u'bar'},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate',
u'Content-Length': u'7',
u'Content-Type': u'application/x-www-form-urlencoded',
u'Host': u'httpbin.org',
u'User-Agent': u'python-requests/2.10.0'},
u'json': None,
u'origin': u'178.167.254.183',
u'url': u'https://httpbin.org/post'}
</code></pre>
<p>Using <em>params</em> creates a query string with key/value pairs in the url and the request has no body:</p>
<pre><code>In [21]: req = requests.post("https://httpbin.org/post", params=data)
In [22]: req.request.body
In [23]: req.json()
Out[23]:
{u'args': {u'foo': u'bar'},
u'data': u'',
u'files': {},
u'form': {},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate',
u'Content-Length': u'0',
u'Host': u'httpbin.org',
u'User-Agent': u'python-requests/2.10.0'},
u'json': None,
u'origin': u'178.167.254.183',
u'url': u'https://httpbin.org/post?foo=bar'}
In [24]: req.url
Out[24]: u'https://httpbin.org/post?foo=bar'
</code></pre>
| 0 |
2016-09-10T19:41:49Z
|
[
"python",
"python-requests",
"bitcoin"
] |
Is there a way to manually install modules for python?
| 39,427,840 |
<p>I keep running into problems with installing modules for python. Either because the modules themselves aren't able to be downloaded via pip or because of some error or another. </p>
<p>Is it possible to simply download the module as a .zip or tar.gz file (as I see a lot of links to do just that) and then somehow place them within the file that Python uses to store its modules (I think it's the Lib folder).</p>
<p>Is this possible? What are the pitfalls for doing something like this? </p>
| -1 |
2016-09-10T15:53:06Z
| 39,437,190 |
<p>As you noticed, you can download a module's source (usually in the form of a <code>.tar.gz</code> archive) from <a href="https://pypi.python.org" rel="nofollow">PyPI</a>. First, unpack the archive, then enter the folder that is created. Assuming that your Python binary is on your path, simply run</p>
<pre><code>python setup.py install
</code></pre>
<p>or (for Python 3)</p>
<pre><code>python3 setup.py install
</code></pre>
<p>and it will be built and installed. Of course, if the module contains extensions written in C/C++ that need to be compiled, you'll need to have a compiler installed and configured on your system, along with any requisite libraries.</p>
<p>If you're on Windows, you can find pre-compiled <code>.whl</code>s for many packages <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">here</a>.</p>
<p>Details about all of this are easily available by googling. </p>
| 0 |
2016-09-11T14:39:18Z
|
[
"python",
"module",
"install"
] |
How to import the six library to python 2.5.2
| 39,427,946 |
<p>I'm wondering how I can import the six library to python 2.5.2? It's not possible for me to install using pip, as it's a closed system I'm using.</p>
<p>I have tried to add the six.py file into the lib path. and then use "import six". However, it doesnt seem to be picking up the library from this path.</p>
| 0 |
2016-09-10T16:03:53Z
| 39,427,972 |
<p>You can't use <code>six</code> on Python 2.5; it requires Python 2.6 or newer.</p>
<p>From the <a href="https://bitbucket.org/gutworth/six" rel="nofollow"><code>six</code> project homepage</a>:</p>
<blockquote>
<p>Six supports every Python version since 2.6.</p>
</blockquote>
<p>Trying to install <code>six</code> on Python 2.5 anyway fails as the included <code>setup.py</code> tries to import the <code>six</code> module, which tries to access objects not available in Python 2.5:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/private/tmp/test/build/six/setup.py", line 8, in <module>
import six
File "six.py", line 604, in <module>
viewkeys = operator.methodcaller("viewkeys")
AttributeError: 'module' object has no attribute 'methodcaller'
</code></pre>
| 0 |
2016-09-10T16:05:45Z
|
[
"python",
"python-import"
] |
How to import the six library to python 2.5.2
| 39,427,946 |
<p>I'm wondering how I can import the six library to python 2.5.2? It's not possible for me to install using pip, as it's a closed system I'm using.</p>
<p>I have tried to add the six.py file into the lib path. and then use "import six". However, it doesnt seem to be picking up the library from this path.</p>
| 0 |
2016-09-10T16:03:53Z
| 39,428,032 |
<p>According to project history, <a href="https://bitbucket.org/gutworth/six/src/a9b120c9c49734c1bd7a95e7f371fd3bf308f107?at=1.9.0" rel="nofollow">version 1.9.0</a> supports Python 2.5. Compatibility broke with 1.10.0 release.</p>
<blockquote>
<p>Six supports every Python version since 2.5. It is contained in only
one Python file, so it can be easily copied into your project. (The
copyright and license notice must be retained.)</p>
</blockquote>
<p><a href="https://bitbucket.org/gutworth/six/commits/2dfeb4ba983d8d5985b5efae3859417d2a57e487" rel="nofollow">There is a commit in version control system which mentions change of minimum supported version</a>.</p>
<p>Note that pip is able to install fixed version of package if you want to.</p>
<pre><code>pip install six==1.9.0
</code></pre>
| 1 |
2016-09-10T16:12:11Z
|
[
"python",
"python-import"
] |
Removing new line character from Resultset (Python)
| 39,427,977 |
<p>I have ResultSet that contains information as below - </p>
<pre><code>[<div id="Description">\n This is the content example.\n\r\nThese characters I need to remove from complete string.\n\r\nI tried strip,lstrip,rstrip and replace.\n\r\nBut for these I found the Attributeerror: resultset object has no attribute 'strip'(lstrip/rstrip/replace).\n</div>]
</code></pre>
<p>I retrieved it with:</p>
<pre><code>webPage=urllib2.urlopen(GivenUrl)
soup=BeautifulSoup(webPage,"html.parser")
soupResultSet=soup.findAll('div',id='Description') #This result set contains the above information.
</code></pre>
<p>I am using python 2.7.12.</p>
<p>The original HTML:</p>
<pre><code><div id="Description">
This is the content example.
These characters I need to remove from complete string.
I tried strip,lstrip,rstrip and replace.
But for these I found the Attributeerror: resultset object has no attribute 'strip'(lstrip/rstrip/replace).
</div>
</code></pre>
| -1 |
2016-09-10T16:06:04Z
| 39,428,029 |
<p><code>ResultSet</code> is a simple <code>list</code> subclass. <code>str.strip()</code> does not exist on lists, nor on the <code>div</code> element.</p>
<p>Get the <em>text</em> from each element, you can use the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>Tag.get_text()</code> method</a>, which supports stripping directly:</p>
<pre><code>[tag.get_text(strip=True) for tag in soup.find_all('div', id='Description')]
</code></pre>
<p>Since you appear to be looking for a <code><div></code> with an <code>id</code> attribute, there should be only <em>one</em> such element. In that case, rather than use <code>soup.find_all()</code>, you should be using <code>soup.find()</code> and just get that one element rather than a list:</p>
<pre><code>soup.find('div', id='Description').get_text(strip=True)
</code></pre>
<p>This gives you <em>one</em> <code>str</code> object, with whitespace removed from the start and end. You can further process this if you need to remove all newlines from the middle of the string too.</p>
| 1 |
2016-09-10T16:12:08Z
|
[
"python",
"beautifulsoup"
] |
Use selenium with chromedriver on Mac
| 39,428,042 |
<p>I want to use selenium with chromedriver on Mac,but I have some troubles on it.</p>
<ol>
<li>I download the chromedriver from <a href="https://sites.google.com/a/chromium.org/chromedriver/home" rel="nofollow">ChromeDriver - WebDriver for Chrome</a></li>
<li>But I don't want to put it to PATH.So I do this.</li>
</ol>
<p><a href="http://i.stack.imgur.com/iz0kG.png" rel="nofollow"><img src="http://i.stack.imgur.com/iz0kG.png" alt="enter image description here"></a></p>
<pre><code>import os
from selenium import webdriver
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DRIVER_BIN = os.path.join(PROJECT_ROOT, "bin/chromedriver_for_mac")
print DRIVER_BIN
browser = webdriver.Chrome(DRIVER_BIN)
browser.get('http://www.baidu.com/')
</code></pre>
<p>But I can't get the result I want.</p>
<pre><code>Traceback (most recent call last):
File "/Users/wyx/project/python-scraping/se/test.py", line 15, in <module>
browser = webdriver.Chrome(DRIVER_BIN)
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
self.service.start()
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver_for_mac' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.chrome.service.Service object at 0x107f96150>> ignored
</code></pre>
<ol start="3">
<li><p>Then I run <code>brew install chromedriver</code>.And I only run this
without the driver path.</p>
<pre><code>browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')
</code></pre></li>
</ol>
<p>But it can't work either.</p>
<pre><code>Traceback (most recent call last):
File "/Users/wyx/project/python-scraping/se/test.py", line 16, in <module>
browser = webdriver.Chrome()
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
self.service.start()
File "/Users/wyx/project/python-scraping/.env/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.chrome.service.Service object at 0x105c08150>> ignored
Process finished with exit code 1
</code></pre>
<p>Finally I try to put it to /usr/bin</p>
<pre><code>â Downloads sudo cp chromedriver /usr/bin
Password:
cp: /usr/bin/chromedriver: Operation not permitted
</code></pre>
<p>and I try to use <code>export PATH=$PATH:/Users/wyx/project/python-scraping/se/bin/chromedriver_for_mac</code> in .zshrc . But </p>
<blockquote>
<p>selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.</p>
</blockquote>
<p>So how to solve itï¼I want to use it with the driver path not in the PATH so I can deploy my project easily.</p>
<p>Solution:</p>
<ol>
<li><code>brew install chromedriver</code></li>
<li><code>which chromedriver</code> get the driver path</li>
<li>And then use it like this <code>webdriver.Chrome("/usr/local/bin/chromedriver")</code></li>
</ol>
<blockquote>
<p>But I don't know why so complex to use selenium.</p>
</blockquote>
| 0 |
2016-09-10T16:12:58Z
| 39,428,368 |
<blockquote>
<p>selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.</p>
</blockquote>
<p><a href="http://stackoverflow.com/questions/8255929/running-webdriver-chrome-with-selenium">To launch chrome browser using <code>ChromeDriver</code></a> you need to pass <a href="https://sites.google.com/a/chromium.org/chromedriver/home" rel="nofollow">executable chromedriver</a> location with executable itself into <code>executable_path</code>.</p>
<p>You should try as below :-</p>
<pre><code>from selenium import webdriver
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DRIVER_BIN = os.path.join(PROJECT_ROOT, "bin/chromedriver_for_mac")
browser = webdriver.Chrome(executable_path = DRIVER_BIN)
browser.get('http://www.baidu.com/')
</code></pre>
<p>Or set <code>PATH</code> variable <a href="http://codrspace.com/rails4sandeep/install-and-set-path-to-chromedriver-on-mac-or-linux/" rel="nofollow">using command with executable</a> as :-</p>
<pre><code>export PATH=$PATH:/Users/wyx/project/python-scraping/se/bin/chromedriver_for_mac
</code></pre>
<p>Then try to Initialize <code>ChromeDriver</code> as :-</p>
<pre><code>from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')
</code></pre>
| 0 |
2016-09-10T16:48:35Z
|
[
"python",
"selenium"
] |
Using a list as arguments for a function in OCaml
| 39,428,119 |
<p>I am currently trying to learn OCaml. And I am searching for the equivalent of this python code:</p>
<pre><code>f(*l[:n])
</code></pre>
<p>I thought I'd try to write a function that emulates this behavior, but it doesn't work. Here is the code:</p>
<pre><code>let rec arg_supply f xs n =
if n = 0 then
f
else
match xs with
| x :: remainder -> arg_supply (f x) remainder (n - 1);;
</code></pre>
<p>And here is the error message I get:</p>
<pre><code>Error: This expression has type 'a but an expression was expected of type
'b -> 'a
The type variable 'a occurs inside 'b -> 'a
</code></pre>
<p>Any help is appreciated, be it a way to get my function working, or another way to supply the first n elements of a list to a function as arguments.</p>
<p>Edit: <code>n</code> is the amount of arguments needed to call the function, and constant because of it.</p>
<p>Edit: This one doesn't work either.</p>
<pre><code>type ('a, 'r) as_value = ASFunction of ('a -> ('a, 'r) as_value) | ASReturnValue of 'r;;
let rec _arg_supply f_or_rval xs n =
if n = 0 then
f_or_rval
else
match f_or_rval with
| ASFunction func -> (
match xs with
| x :: r -> _arg_supply (func x) r (n - 1)
| _ -> failwith "too few arguments for f"
)
| ASReturnValue out -> out;;
</code></pre>
| 3 |
2016-09-10T16:20:40Z
| 39,428,421 |
<p>Your Python function <code>f</code> is being passed different numbers of arguments, depending on the value of <code>n</code>. This can't be expressed in OCaml. Functions take a statically fixed number of arguments (i.e., you can tell the number of arguments by reading the source code).</p>
<p>The way to pass different numbers of arguments to an OCaml function is to pass a list, corresponding to the Python code <code>f(l[:n])</code>.</p>
<p>(It's more accurate to say that an OCaml function takes one argument, but this is a discussion for another time.)</p>
<p><strong>Update</strong></p>
<p>If <code>n</code> is actually a constant, let's say it's 3. Then you can do something like the following:</p>
<pre><code> match l with
| a :: b :: c :: _ -> f a b c
| _ -> failwith "too few arguments for f"
</code></pre>
<p><strong>Update 2</strong></p>
<p>Here's another way to look at what you want to do. You want to write a function, let's call it <code>apply</code>, that works like this:</p>
<pre><code>let apply f xs =
. . .
</code></pre>
<p>The idea is that <code>apply</code> calls the function <code>f</code>, giving it arguments from the list <code>xs</code>.</p>
<p>OCaml is a strongly typed language, so we should be able to give a type for <code>f</code> and for <code>xs</code>. What is the type of <code>f</code>? You want it to be a function of <code>n</code> arguments, where <code>n</code> is the length of <code>xs</code>. I.e., <code>n</code> is not a constant! But there is no such type in OCaml. Any function type has a fixed, static number of parameters. Since there's no OCaml type for <code>f</code>, you can't write the function <code>apply</code>. You can write a series of functions <code>apply1</code>, <code>apply2</code>, and so on. Note that each of these functions has a different type. If you don't mind calling the correct one for each different function <code>f</code>, that would work.</p>
<p>It's fairly likely that you can restructure your problem to work with OCaml's typing rather than struggling with it. I stand by my comments on strong typing: once you get used to strong typing, it's very hard to give up the benefits and go back to languages with little (or no) typing support.</p>
| 3 |
2016-09-10T16:53:50Z
|
[
"python",
"ocaml"
] |
How to find and group similar permutations of 4 digits
| 39,428,151 |
<p>I am not good at these, but please bear with me. I have a set of numbers from my database / list, all are 4 digit numbers with the numbers between and include 0000 through 9999.</p>
<p>Say the list is:</p>
<pre><code>[1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]
</code></pre>
<p>Basically, I want to group them in such a way</p>
<pre><code>1234, 2134, 3214 is group A
6554, 5456 is group B
9911, 1199 is group C
4354 is group D
</code></pre>
<p>where the list items in each group all contain the same numbers - i.e, Group A are all made up of the numbers 1, 2, 3, and 4. Then I will find the len(group A), len(group B), len(group C), len(group D)...
and then sort them in decreasing manner.</p>
<p>How to do it?
And if list is huge, is the method still works ok?</p>
| -4 |
2016-09-10T16:24:40Z
| 39,429,226 |
<p>Here's a (tested in Python 2.7.10) solution:</p>
<pre><code>def index(number):
digits = list(str(number))
return ''.join(sorted(digits))
groups = {}
numbers = [1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]
for number in numbers:
key = index(number)
if key not in groups:
groups[key] = []
groups[key].append(number)
print groups.values() # [[1234, 2134, 3214], [4354], [6554, 5456], [9911, 1199]]
</code></pre>
<p>The key to this solution is to take the digits of each number and sort them, then use that result as the dictionary key. <code>index()</code> is just a succinct way of generating the digit-ordered form of each number.</p>
| 0 |
2016-09-10T18:22:56Z
|
[
"python",
"permutation"
] |
How to find and group similar permutations of 4 digits
| 39,428,151 |
<p>I am not good at these, but please bear with me. I have a set of numbers from my database / list, all are 4 digit numbers with the numbers between and include 0000 through 9999.</p>
<p>Say the list is:</p>
<pre><code>[1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]
</code></pre>
<p>Basically, I want to group them in such a way</p>
<pre><code>1234, 2134, 3214 is group A
6554, 5456 is group B
9911, 1199 is group C
4354 is group D
</code></pre>
<p>where the list items in each group all contain the same numbers - i.e, Group A are all made up of the numbers 1, 2, 3, and 4. Then I will find the len(group A), len(group B), len(group C), len(group D)...
and then sort them in decreasing manner.</p>
<p>How to do it?
And if list is huge, is the method still works ok?</p>
| -4 |
2016-09-10T16:24:40Z
| 39,429,263 |
<p>Not sure what you want to do about naming the groups, but you can use <code>itertools.groupby</code> after converting the ints to strings, and sorting those characters</p>
<pre><code>from itertools import groupby
l = [1234, 4354, 6554, 2134, 3214, 5456, 9911, 1199]
# ints to (int, sorted str)
s = map(lambda x: (x, ''.join(sorted(str(x)))), l)
# sort the list for groupby
s.sort(key=lambda kv: kv[1])
# print out just the ints of the groups
for _, g in groupby(s, lambda kv: kv[1]):
print map(lambda kv: kv[0], g)
</code></pre>
<p>Output </p>
<pre><code>[9911, 1199]
[1234, 2134, 3214]
[4354]
[6554, 5456]
</code></pre>
| 0 |
2016-09-10T18:26:12Z
|
[
"python",
"permutation"
] |
Why am I getting NameError?
| 39,428,155 |
<p>Here's a part of the the code I'm trying to run:</p>
<pre><code>def func1():
a = True
while a == True:
try:
guess = int(input("guess it: "))
a = False
except ValueError:
print("Not a valid number.")
import random
number = random.randint(0, 50)
print("Im thinking of a number between 0 and 50,")
func1()
if guess == number:
print("Perfect, you got it from the first try!")
</code></pre>
<p>I don't know why I get this: NameError: name 'guess' is not defined, even though I defined it in "func1" </p>
| 2 |
2016-09-10T16:24:58Z
| 39,428,221 |
<p>You're getting the error because <code>guess</code> only exists in the scope of <code>func1()</code>. You need to return the value <code>guess</code> from <code>func1()</code> to use it. </p>
<p>Like so:</p>
<pre><code>def func1():
a = True
while a == True:
try:
guess = int(input("guess it: "))
a = False
except ValueError:
print("Not a valid number.")
return guess # i'm returning the variable guess
import random
number = random.randint(0, 50)
print("Im thinking of a number between 0 and 50,")
guess = func1() # I'm assigning the value of guess to the global variable guess
if guess == number:
print("Perfect, you got it from the first try!")
</code></pre>
| 1 |
2016-09-10T16:33:25Z
|
[
"python",
"python-3.5"
] |
Determine list of all possible products from a list of integers in Python
| 39,428,179 |
<p>In Python 2.7 I need a method that returns all possible products of a <code>list or tuple of int</code>. Ie. if input is <code>(2, 2, 3, 4)</code>, then I'd want a output like</p>
<ul>
<li><code>(3, 4, 4)</code>, 2 * 2 = 4</li>
<li><code>(2, 4, 6)</code>, 2 * 3 = 6</li>
<li><code>(2, 3, 8)</code>, 2 * 4 = 8</li>
<li><code>(3, 4, 4)</code>, 2 * 2 = 4</li>
<li><code>(2, 2, 12)</code>, 3 * 4 = 12</li>
<li><code>(2, 24)</code>, 2 * 3 * 4 = 24</li>
<li><code>(3, 16)</code>, 2 * 2 * 4 = 16</li>
<li><code>(4, 12)</code>, 2 * 2 * 3 = 12</li>
<li><code>(48)</code>, 2 * 2 * 3 * 4 = 48</li>
</ul>
<p>wrapped up in a <code>list or tuple</code>. I figure that a nice implementation is probably possible using <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow">combinations</a> from <code>itertools</code>, but I'd appreciate any help. Note that I am only interested in distinct lists, where order of <code>int</code> plays no role.</p>
<p>EDIT</p>
<p>Some futher explanation for some clarification. Take the first output list. Input is <code>(2, 2, 3, 4)</code> (always). Then I take 2 and 2 <em>out</em> of the list and multiply them, so now I am left with a list <code>(3, 4, 4)</code>. 3 and 4 from the input and the last 4 from the product. </p>
<p>I haven't tried anything yet since I just can't spin my head around that kind of loop. But I can't stop thinking about the problem, so I'll add some code if I do get a suggestion.</p>
| -2 |
2016-09-10T16:27:38Z
| 39,428,545 |
<p>Your problem is basically one of find all subsets of a given set (multiset in your case). Once you have the subsets its straight forward to construct the output you've asked for.</p>
<p>For a set A find all the subsets [S0, S1, ..., Si]. For each subset Si, take <code>(A - Si) | product(Si)</code>, where <code>|</code> is union and <code>-</code> is a set difference. You might not be interested in subsets of size 0 and 1, so you can just exclude those.</p>
<p>Finding subsets is a well known problem so I'm sure you can find resources on how to do that. Keep in mind that there are 2**N setbsets of a set with N elements.</p>
| 0 |
2016-09-10T17:07:28Z
|
[
"python",
"algorithm",
"combinations",
"combinatorics"
] |
Determine list of all possible products from a list of integers in Python
| 39,428,179 |
<p>In Python 2.7 I need a method that returns all possible products of a <code>list or tuple of int</code>. Ie. if input is <code>(2, 2, 3, 4)</code>, then I'd want a output like</p>
<ul>
<li><code>(3, 4, 4)</code>, 2 * 2 = 4</li>
<li><code>(2, 4, 6)</code>, 2 * 3 = 6</li>
<li><code>(2, 3, 8)</code>, 2 * 4 = 8</li>
<li><code>(3, 4, 4)</code>, 2 * 2 = 4</li>
<li><code>(2, 2, 12)</code>, 3 * 4 = 12</li>
<li><code>(2, 24)</code>, 2 * 3 * 4 = 24</li>
<li><code>(3, 16)</code>, 2 * 2 * 4 = 16</li>
<li><code>(4, 12)</code>, 2 * 2 * 3 = 12</li>
<li><code>(48)</code>, 2 * 2 * 3 * 4 = 48</li>
</ul>
<p>wrapped up in a <code>list or tuple</code>. I figure that a nice implementation is probably possible using <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow">combinations</a> from <code>itertools</code>, but I'd appreciate any help. Note that I am only interested in distinct lists, where order of <code>int</code> plays no role.</p>
<p>EDIT</p>
<p>Some futher explanation for some clarification. Take the first output list. Input is <code>(2, 2, 3, 4)</code> (always). Then I take 2 and 2 <em>out</em> of the list and multiply them, so now I am left with a list <code>(3, 4, 4)</code>. 3 and 4 from the input and the last 4 from the product. </p>
<p>I haven't tried anything yet since I just can't spin my head around that kind of loop. But I can't stop thinking about the problem, so I'll add some code if I do get a suggestion.</p>
| -2 |
2016-09-10T16:27:38Z
| 39,428,550 |
<p>Suppose you have a vector of 4 numbers (for instance (2,2,3,4)).</p>
<p>You can generate a grid (as that one showed below):</p>
<pre><code>0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
</code></pre>
<p>Now remove the rows with all '0' and the rows with only one '1'.</p>
<pre><code>0 0 1 1
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
</code></pre>
<p>Now you can substitute the '1' with the respective element in the vector.
If your vector is (2,2,3,4) it becomes:</p>
<pre><code>0 0 3 4
0 2 0 4
0 2 3 0
0 2 3 4
2 0 0 4
2 0 3 0
2 0 3 4
2 2 0 0
2 2 0 4
2 2 3 0
2 2 3 4
</code></pre>
<p>Try to implement this in Python.
Below a pseudo code:</p>
<pre><code>for i from 0 to 2^VECTOR_LEN:
bin=convert_to_binary(i)
if sum_binary_digit(bin) > 1:
print(exec_moltiplication(bin,vector)
# if you want you can also use the bin vector as mask for the updating
# of your tuple of int with the result of the product and append it
# in a list (as in your example).
# For example if bin is (1 1 0 0) you can edit (2 2 3 4) in (4 3 4)
# and append (4 3 4) inside the list or if it is (1 0 1 0) you can
# update (2 2 3 4) in (6 2 4)
</code></pre>
<p>WHERE:</p>
<ul>
<li>vector: is the vector containing the numbers</li>
<li>VECTOR_LEN is the length of vector</li>
<li>convert_to_binary(num) is a function that convert an integer (num) to binary</li>
<li>sum_binary_digit(bin) is a function that sum the 1s in your binary number (bin)</li>
<li>exec_multiplication(vector,bin) take in input the vector (vector) and the binary (bin) and returns the value of the multiplication.</li>
</ul>
| 0 |
2016-09-10T17:08:05Z
|
[
"python",
"algorithm",
"combinations",
"combinatorics"
] |
Determine list of all possible products from a list of integers in Python
| 39,428,179 |
<p>In Python 2.7 I need a method that returns all possible products of a <code>list or tuple of int</code>. Ie. if input is <code>(2, 2, 3, 4)</code>, then I'd want a output like</p>
<ul>
<li><code>(3, 4, 4)</code>, 2 * 2 = 4</li>
<li><code>(2, 4, 6)</code>, 2 * 3 = 6</li>
<li><code>(2, 3, 8)</code>, 2 * 4 = 8</li>
<li><code>(3, 4, 4)</code>, 2 * 2 = 4</li>
<li><code>(2, 2, 12)</code>, 3 * 4 = 12</li>
<li><code>(2, 24)</code>, 2 * 3 * 4 = 24</li>
<li><code>(3, 16)</code>, 2 * 2 * 4 = 16</li>
<li><code>(4, 12)</code>, 2 * 2 * 3 = 12</li>
<li><code>(48)</code>, 2 * 2 * 3 * 4 = 48</li>
</ul>
<p>wrapped up in a <code>list or tuple</code>. I figure that a nice implementation is probably possible using <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow">combinations</a> from <code>itertools</code>, but I'd appreciate any help. Note that I am only interested in distinct lists, where order of <code>int</code> plays no role.</p>
<p>EDIT</p>
<p>Some futher explanation for some clarification. Take the first output list. Input is <code>(2, 2, 3, 4)</code> (always). Then I take 2 and 2 <em>out</em> of the list and multiply them, so now I am left with a list <code>(3, 4, 4)</code>. 3 and 4 from the input and the last 4 from the product. </p>
<p>I haven't tried anything yet since I just can't spin my head around that kind of loop. But I can't stop thinking about the problem, so I'll add some code if I do get a suggestion.</p>
| -2 |
2016-09-10T16:27:38Z
| 39,428,596 |
<p>You can break this down into three steps:</p>
<ul>
<li>get all the permutations of the list of numbers</li>
<li>for each of those permutations, create all the possible partitions</li>
<li>for each sublist in the partitions, calculate the product</li>
</ul>
<p>For the permutations, you can use <code>itertools.permutations</code>, but as far as I know, there is no builtin function for partitions, but that's not too difficult to write (or to find):</p>
<pre><code>def partitions(lst):
if lst:
for i in range(1, len(lst) + 1):
for p in partitions(lst[i:]):
yield [lst[:i]] + p
else:
yield []
</code></pre>
<p>For a list like <code>(1,2,3,4)</code>, this will generate <code>[(1),(2),(3),(4)]</code>, <code>[(1),(2),(3,4)]</code>, <code>[(1),(2,3),(4)]</code>, <code>[(1),(2,3,4)]</code>, and so on, but not, e.g. <code>[(1,3),(2),(4)]</code>; that's why we also need the permutations. However, for all the permutations, this will create many partitions that are effectively duplicates, like <code>[(1,2),(3,4)]</code> and <code>[(4,3),(1,2)]</code> (182 for your <code>data</code>), but unless your lists are particularly long, this should not be too much of a problem.</p>
<p>We can combine the second and third step; this way we can weed out all the duplicates as soon as they arise:</p>
<pre><code>data = (2, 2, 3, 4)
res = {tuple(sorted(reduce(operator.mul, lst) for lst in partition))
for permutation in itertools.permutations(data)
for partition in partitions(permutation)}
</code></pre>
<p>Afterwards, <code>res</code> is <code>{(6, 8), (2, 4, 6), (2, 2, 3, 4), (2, 2, 12), (48,), (3, 4, 4), (4, 12), (3, 16), (2, 24), (2, 3, 8)}</code></p>
<hr>
<p>Alternatively, you can combine it all in one, slightly more complex algorithm. This still generates <em>some</em> duplicates, due to the two <code>2</code> in your data set, that can again be removed by sorting and collecting in a set. The result is the same as above.</p>
<pre><code>def all_partitions(lst):
if lst:
x = lst[0]
for partition in all_partitions(lst[1:]):
# x can either be a partition itself...
yield [x] + partition
# ... or part of any of the other partitions
for i, _ in enumerate(partition):
partition[i] *= x
yield partition
partition[i] //= x
else:
yield []
res = set(tuple(sorted(x)) for x in all_partitions(list(data)))
</code></pre>
| -1 |
2016-09-10T17:13:42Z
|
[
"python",
"algorithm",
"combinations",
"combinatorics"
] |
Why does "".join() appear to be slower than +=
| 39,428,239 |
<p>Despite this question <a href="http://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python">Why is ''.join() faster than += in Python?</a> and it's answers and this great explanation of the code behind the curtain: <a href="https://paolobernardi.wordpress.com/2012/11/06/python-string-concatenation-vs-list-join/" rel="nofollow">https://paolobernardi.wordpress.com/2012/11/06/python-string-concatenation-vs-list-join/</a><br>
My tests suggest otherwise and I am baffled.<br>
Am I doing something simple, incorrectly? I'll admit that I'm fudging the creation of x a bit but I don't see how that would affect the outcome. </p>
<pre><code>import time
x="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
y=""
t1 = (time.time())
for i in range(10000):
y+=x
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473524757.681939, 1473524757.68521, '=', 0.0032711029052734375)</p>
<pre><code>import time
x="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
y=""
t1 = (time.time())
for i in range(10000):
y=y+x
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473524814.544177, 1473524814.547544, '=', 0.0033669471740722656)</p>
<pre><code>import time
x=10000*"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
y=""
t1 = (time.time())
y= "".join(x)
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473524861.949515, 1473524861.978755, '=', 0.029239892959594727)</p>
<p>As can be seen the <code>"".join()</code> is much slower and yet we're told that it's meant to be quicker.<br>
These values are very similar in both python2.7 and python3.4</p>
<p><strong>Edit:</strong>
Ok fair enough.</p>
<p>The "one huge string" thing is the kicker.</p>
<pre><code>import time
x=[]
for i in range(10000):
x.append("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
y=""
t1 = (time.time())
y= "".join(x)
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473526344.55748, 1473526344.558409, '=', 0.0009288787841796875)</p>
<p>An order of magnitude quicker.
Mea Culpa!</p>
| -5 |
2016-09-10T16:35:06Z
| 39,428,265 |
<p>You called <code>''.join()</code> on <strong>one huge string</strong>, not a list (multiplying a string produces a larger string). This forces <code>str.join()</code> to iterate over that huge string, joining 74k <em>individual <code>'x'</code> characters</em>. In other words, your second test does 74 times more work than your first.</p>
<p>To conduct a fair trial, you need to start with the same inputs for both, and use the <a href="https://docs.python.org/3/library/timeit.html" rel="nofollow"><code>timeit</code> module</a> to reduce the influence of garbage collection and other processes on your system.</p>
<p>That means both approaches need to work from a <em>list</em> of strings (your assignment examples rely on repeatedly adding a string literal, stored as a constant):</p>
<pre><code>from timeit import timeit
testlist = ['x' * 74 for _ in range(100)]
def strjoin(testlist):
return ''.join(testlist)
def inplace(testlist):
result = ''
for element in testlist:
result += element
return result
def concat(testlist):
result = ''
for element in testlist:
result = result + element
return result
for f in (strjoin, inplace, concat):
timing = timeit('f(testlist)', 'from __main__ import f, testlist',
number=100000)
print('{:>7}: {}'.format(f.__name__, timing))
</code></pre>
<p>On my Macbook Pro, on Python 3.5, this produces:</p>
<pre><code>strjoin: 0.09923043003072962
inplace: 1.0032496969797648
concat: 1.0027298880158924
</code></pre>
<p>On 2.7, I get:</p>
<pre><code>strjoin: 0.118290185928
inplace: 0.85814499855
concat: 0.867822885513
</code></pre>
<p><code>str.join()</code> is still the winner here.</p>
| 4 |
2016-09-10T16:38:00Z
|
[
"python"
] |
Why does "".join() appear to be slower than +=
| 39,428,239 |
<p>Despite this question <a href="http://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python">Why is ''.join() faster than += in Python?</a> and it's answers and this great explanation of the code behind the curtain: <a href="https://paolobernardi.wordpress.com/2012/11/06/python-string-concatenation-vs-list-join/" rel="nofollow">https://paolobernardi.wordpress.com/2012/11/06/python-string-concatenation-vs-list-join/</a><br>
My tests suggest otherwise and I am baffled.<br>
Am I doing something simple, incorrectly? I'll admit that I'm fudging the creation of x a bit but I don't see how that would affect the outcome. </p>
<pre><code>import time
x="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
y=""
t1 = (time.time())
for i in range(10000):
y+=x
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473524757.681939, 1473524757.68521, '=', 0.0032711029052734375)</p>
<pre><code>import time
x="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
y=""
t1 = (time.time())
for i in range(10000):
y=y+x
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473524814.544177, 1473524814.547544, '=', 0.0033669471740722656)</p>
<pre><code>import time
x=10000*"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
y=""
t1 = (time.time())
y= "".join(x)
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473524861.949515, 1473524861.978755, '=', 0.029239892959594727)</p>
<p>As can be seen the <code>"".join()</code> is much slower and yet we're told that it's meant to be quicker.<br>
These values are very similar in both python2.7 and python3.4</p>
<p><strong>Edit:</strong>
Ok fair enough.</p>
<p>The "one huge string" thing is the kicker.</p>
<pre><code>import time
x=[]
for i in range(10000):
x.append("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
y=""
t1 = (time.time())
y= "".join(x)
t2 = (time.time())
#print (y)
print (t1,t2,"=",t2-t1)
</code></pre>
<p>(1473526344.55748, 1473526344.558409, '=', 0.0009288787841796875)</p>
<p>An order of magnitude quicker.
Mea Culpa!</p>
| -5 |
2016-09-10T16:35:06Z
| 39,428,310 |
<p>You are not comparing the same operation because your first operation added the long string every iteration while join added every item of the string seperatly. (See also @MartijnPieters answer)</p>
<p>If I run a comparison I get completly different timings suggesting that <code>str.join</code> is much faster:</p>
<pre><code>x = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
def join_inplace_add(y, x, num):
for _ in range(num):
y += x
return y
def join_by_join(x, num):
return ''.join([x for _ in range(num)])
%timeit join_by_join('', x, 1000)
# 10000 loops, best of 3: 91 µs per loop
%timeit join_inplace_add(x, 1000)
# 1000 loops, best of 3: 325 µs per loop
</code></pre>
| 2 |
2016-09-10T16:42:27Z
|
[
"python"
] |
Simple way to use the google contacts API from a python script
| 39,428,290 |
<p>I'm currently trying to write a script and I would need to access my GMail contacts to finish it. I tried googling that a bit and it looks like there are a few libraries to do that, but some answers seems very old, and some others aren't that clear.</p>
<p>What is the correct way currently to access the contacts API from a script ? Using <a href="https://github.com/google/gdata-python-client" rel="nofollow">https://github.com/google/gdata-python-client</a> I assume ?</p>
<p>Any recent response seems to involve the user copying a link into his browser by hand, getting redirected to some non-existent URL and being asked to copy that URL back in the script to parse the code in it. That seems perfectly ridiculous, I do hope there is a proper way to access the API for non-web applications ?</p>
<p>I'll be the only user of that script so I don't mind having to put my full e-mail address and password in if that makes it easier, as long as I don't have to keep re-authenticating by hand. Just want to authorize it once and have it work forever. I'm just trying to find the contact's name from the phone number so I don't even need to access everything.</p>
| 0 |
2016-09-10T16:40:05Z
| 39,436,655 |
<p>Here is what I'm using in the end :</p>
<pre><code>if arg == "--init":
gflow = OAuth2WebServerFlow(client_id='<ID>', client_secret='<secret>',
scope='https://www.googleapis.com/auth/contacts.readonly',
redirect_uri='http://localhost');
gflow.params['access_type'] = 'offline';
auth_uri = gflow.step1_get_authorize_url();
weechat.prnt("", "Please go to " + auth_uri + " and come back here with the code. Run /gauth code");
else:
credentials = gflow.step2_exchange(arg);
storage.put(credentials);
http = httplib2.Http();
http = credentials.authorize(http);
people = build('people', 'v1', http=http);
</code></pre>
<p>Works fine with that. I do need to copy / paste the URL by hand and then get the code out of the redirection, but since I put the access_type to offline I have to do that only once.</p>
| 0 |
2016-09-11T13:35:55Z
|
[
"python",
"google-api",
"google-api-python-client"
] |
Django model form doesn't populate when instance=object is set
| 39,428,350 |
<p>I'm trying to populate a ModelForm with existing data if it exists or create a new instance if not. I've read the <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/" rel="nofollow">django docs</a> and several questions here on Stack Overflow but I can't figure out why my form doesn't populate with the existing data. I'm sure I'm missing something simple, any help would be appreciated.</p>
<p>In forms.py:</p>
<pre><code>from django.forms import ModelForm, Textarea
from .models import Batch
class BatchForm(ModelForm):
class Meta:
model = Batch
fields = ('recipe', 'date', 'original_gravity', 'final_gravity', 'gravity_units', 'notes')
widgets = {'notes': Textarea(attrs={'cols': 40, 'rows': 10})}
</code></pre>
<p>in views.py: (notice the instance=batch argument, this should pre-populate the form correct?)</p>
<pre><code>def batch_entry(request, batch_id):
if int(batch_id) > 0:
batch = get_object_or_404(Batch, id=batch_id)
form = BatchForm(request.POST, instance=batch)
context = {'BatchForm': form, 'batch': batch }
else:
form = BatchForm()
context = {'BatchForm': form, 'batch': None }
return render(request, 'logger/batch_entry.html', context)
</code></pre>
<p>the batch_entry.html template:</p>
<pre><code>{% if batch.id > 0 %}
<h1>{{batch.date}}</h1>
<h3>{{batch.recipe}}</h3>
<form action="{% url 'logger:batch_entry' batch.id %}" method="post">
{% csrf_token %}
<table>
{{BatchForm.as_table}}
</table>
<input type="submit" value="Submit">
</form>
{% else %}
<h1>New Batch</h1>
<form action="{% url 'logger:batch_entry' 0 %}" method="post">
{% csrf_token %}
<table>
{{BatchForm.as_table}}
</table>
<input type="submit" value="Submit">
</form>
{% endif %}
<form action="{% url 'logger:index' %}" method="post">
{% csrf_token %}
<input type="submit" value="Return to Index">
</form>
</code></pre>
| 0 |
2016-09-10T16:46:38Z
| 39,428,513 |
<p>Because you're <em>also</em> passing <code>request.POST</code>. That is supposed to contain the <em>submitted</em> data, which would naturally override the values already in the instance; but since you're doing that on a GET, the POST data is empty, so your form is displayed empty.</p>
<p>Only pass request.POST into the form when the request is actually a POST.</p>
| 1 |
2016-09-10T17:03:55Z
|
[
"python",
"django",
"modelform"
] |
Debugging TemplateNotFound postmortem django 1.9
| 39,428,395 |
<p>Been couple days of trying to get my template loaded in view - keep getting error in subj. Here is postmortem <a href="http://pastebin.com/JJCtPyYj" rel="nofollow">http://pastebin.com/JJCtPyYj</a> You can see in there TEMPLATE_DIRS being defined. Tried django 1.10, 1.9.9, 1.8.7. Any clues on how to further debug this annoyance would be greatly appreciated.</p>
| 0 |
2016-09-10T16:51:59Z
| 39,428,499 |
<p>TEMPLATE_DIRS is not relevant, and has not been since Django 1.8. As you can see from the traceback, the relevant setting is the DIRS part of TEMPLATES, and that is empty: you need to put the directories in there.</p>
| 0 |
2016-09-10T17:02:20Z
|
[
"python",
"django"
] |
Unknown layer type (crop) in Caffe for windows
| 39,428,481 |
<p>I want to use the following convolutional neural network:</p>
<p><a href="http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/" rel="nofollow">http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/</a></p>
<p>with caffe built from <a href="https://github.com/BVLC/caffe/tree/windows" rel="nofollow">https://github.com/BVLC/caffe/tree/windows</a></p>
<p>for windows 10 with visual studio 2013, CUDA 7.5, cudNN 4 and python support.</p>
<p>Now, when i call either of the two networks supplied with</p>
<pre><code>net = caffe.Net('xyz.prototxt', 'xyz.caffemodel', caffe.TEST)
</code></pre>
<p>I get the following error:</p>
<pre><code> Error parsing text-format caffe.NetParameter: 43:85: Unknown enumeration value of "CROP" for field "type".
</code></pre>
<p>Line 43 of the network looks as follows:</p>
<pre><code>layers { bottom: 'd3c' bottom: 'u3a' top: 'd3cc' name: 'crop_d3c-d3cc' type: CROP }
</code></pre>
<p>I have looked online and some people seem to encounter the same error message. I could not find any solutions, however.</p>
<p>My question now is: how do I get rid of this error?</p>
<p>Help is greatly appreciated!</p>
<p><strong>EDIT:</strong></p>
<p>Changing the .prototxt as suggested by <a href="http://stackoverflow.com/a/39432128/6281477">Dale Song</a> eliminated this error, but led to another one:</p>
<pre><code>[libprotobuf ERROR ..\src\google\protobuf\text_format.cc:274] Error parsing text-format caffe.NetParameter: 10:102: Message type "caffe.LayerParameter" has no field named "blobs_lr".
</code></pre>
<p>I fixed this by replacing </p>
<pre><code>blobs_lr: 1 weight_decay: 1 blobs_lr: 2 weight_decay: 0
</code></pre>
<p>with</p>
<pre><code> param {lr_mult: 1 decay_mult: 1} param {lr_mult: 2 decay_mult: 0}
</code></pre>
<p>in the .prototxt, as suggested <a href="https://groups.google.com/forum/#!topic/caffe-users/kEJzMjNmO_M" rel="nofollow">here</a>.</p>
<p>Thanks!</p>
| 2 |
2016-09-10T16:59:39Z
| 39,432,128 |
<p><strong>Solution:</strong></p>
<p>You should modify <code>net.prototxt</code> from:</p>
<p><code>layers { ... type: CROP }</code> to </p>
<p><code>layer { ... type: "Crop" }</code></p>
<p>and meanwhile, other layers' parameter in the prototxt should also be modified similarly to:</p>
<p><code>layer { ... type: "TypeString" }</code>,</p>
<p>and the <code>TypeString</code> can be found from:</p>
<ol>
<li>The line <code>REGISTER_LAYER_CLASS(some_layer_name)</code> in related <code>some_layer_name_layer.cpp</code> file. For example, <code>REGISTER_LAYER_CLASS(Data)</code> in <code>data_layer.cpp</code> means the <code>TypeString</code> should be <code>Data</code> when writing a data layer in <code>net.prototxt</code>.</li>
<li><code>REGISTER_LAYER_CREATOR(some_layer_name, GetSomeLayer)</code> in <code>layer_factory.cpp</code>. For example, <code>REGISTER_LAYER_CREATOR(Convolution, GetConvolutionLayer)</code> means the <code>TypeString</code> should be <code>Convolution</code> when writing a convolution layer in <code>net.prototxt</code>.</li>
</ol>
<p><strong>Reason:</strong></p>
<p>The reason for your problem is: you used an old layer parameter format</p>
<p><code>layers { ... type: SOMELAYERNAME }</code>. </p>
<p>and this format coming from <code>V1LayerParameter</code> in <a href="https://github.com/BVLC/caffe/blob/windows/src/caffe/proto/caffe.proto" rel="nofollow">caffe.proto</a> doesn't support some newer layer type including the <code>crop</code> layer.</p>
<p>You can confirm this by checking that <code>enum LayerType</code> of <code>V1LayerParameter</code> doesn't include layer type <code>CROP</code>. </p>
<p>To avoid this probelm, you can always use the newest format:</p>
<p><code>layer { ... type: "TypeString" }</code></p>
<p>in which the <code>TypeString</code> can be found in the 2 places mentioned above.</p>
<hr>
<p><strong>Edit 1</strong> </p>
<p><strong>A simple remark:</strong></p>
<p>In general, the error:</p>
<pre><code>Error parsing text-format caffe.xxxParameter: ...
</code></pre>
<p>can always be solved by checking that the <code>xxx.prototxt</code> files use the right field names declared in <a href="https://github.com/BVLC/caffe/blob/windows/src/caffe/proto/caffe.proto" rel="nofollow"><strong>caffe.proto</strong></a> and right values are assigned to them(by checking the field type and its value range).</p>
| 1 |
2016-09-11T01:44:56Z
|
[
"python",
"caffe"
] |
How to add a dimension to a numpy array in Python
| 39,428,496 |
<p>I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 stations that would be great (e.g. changing the dimension size from (428,288) to (214,144,2)) that would be great!</p>
| 0 |
2016-09-10T17:01:43Z
| 39,428,598 |
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow"><code>reshape</code></a>:</p>
<pre><code>>>> a = numpy.array([[1,2,3,4,5,6],[7,8,9,10,11,12]])
>>> a.shape
(2, 6)
>>> a.reshape((2, 6, 1))
array([[[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6]],
[[ 7],
[ 8],
[ 9],
[10],
[11],
[12]]])
>>> _.shape
(2, 6, 1)
</code></pre>
<p>Besides changing the shape from <code>(x, y)</code> to <code>(x, y, 1)</code>, you could use <code>(x, y/n, n)</code> as well, but you may want to specify the column order depending on the input:</p>
<pre><code>>>> a.reshape((2, 3, 2))
array([[[ 1, 2],
[ 3, 4],
[ 5, 6]],
[[ 7, 8],
[ 9, 10],
[11, 12]]])
>>> a.reshape((2, 3, 2), order='F')
array([[[ 1, 4],
[ 2, 5],
[ 3, 6]],
[[ 7, 10],
[ 8, 11],
[ 9, 12]]])
</code></pre>
| 4 |
2016-09-10T17:14:13Z
|
[
"python",
"arrays",
"numpy",
"dimensions"
] |
How to add a dimension to a numpy array in Python
| 39,428,496 |
<p>I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 stations that would be great (e.g. changing the dimension size from (428,288) to (214,144,2)) that would be great!</p>
| 0 |
2016-09-10T17:01:43Z
| 39,428,642 |
<p><strong>1)</strong> To add a dimension to an array <code>a</code> of arbitrary dimensionality:</p>
<pre><code>b = numpy.reshape (a, list (numpy.shape (a)) + [1])
</code></pre>
<p><strong>Explanation:</strong></p>
<p>You get the shape of <code>a</code>, turn it into a list, concatenate <code>1</code> to that list, and use that list as the new shape in a <code>reshape</code> operation.</p>
<p><strong>2)</strong> To specify subdivisions of the dimensions, and have the size of the last dimension calculated automatically, use <code>-1</code> for the size of the last dimension. e.g.:</p>
<pre><code>b = numpy.reshape(a, [numpy.size(a,0)/2, numpy.size(a,1)/2, -1])
</code></pre>
<p>The shape of <code>b</code> in this case will be <code>[214,144,4]</code>.</p>
<p><hr>
(obviously you could combine the two approaches if necessary):</p>
<pre><code>b = numpy.reshape (a, numpy.append (numpy.array (numpy.shape (a))/2, -1))
</code></pre>
| 0 |
2016-09-10T17:18:38Z
|
[
"python",
"arrays",
"numpy",
"dimensions"
] |
How to "flatten" a Panda Panel by summing up specific columns
| 39,428,505 |
<p>I am still familairizing myself with Pandas, and Python in general, so please excuse if this is a simple question. I'd also like to avoid one liners so I can understand the underlying actions if possible! :)</p>
<p>I've managed to pull data data which results in a Panel, with four items. The key of each item is a calendar quarter:</p>
<pre><code>Item '2015-03-31':
Type Quarterly Sales Ending Inventory
Shoes 123,456 50,000
Purses 33,222 10,000
Item '2015-06-30':
Type Quarterly Sales Ending Inventory
Shoes 12,744 56,000
Purses 15,123 9,000
Item '2015-9-30':
Type Quarterly Sales Ending Inventory
Shoes 15,998 35,000
Purses 11,222 15,000
Item '2015-12-31':
Type Quarterly Sales Ending Inventory
Shoes 12,000 45,000
Purses 9,551 7,000
</code></pre>
<p>Ultimately, I would like to "flatten" this by summing up the <strong>Quarterly Sales</strong>, but taking the <strong>Type</strong> and <strong>Ending Inventory</strong> from the most recent entry, and have this in a DataFrame. So my ending DataFrame would be something like this:</p>
<pre><code>Type Quarterly Sales Ending Inventory
Shoes 164,198 45,000
Purses 69,118 7,000
</code></pre>
<p>I tried using a function such as grouby (e.g. <code>mypanel.groupby('Type').sum()</code>), but that ended up summing both <strong>Quarterly Sales</strong> <em>and</em> <strong>Ending Inventory</strong>, whereas I want to take the "most recent" <strong>Ending Inventory</strong> instead. An easy "fix" for this would be to take the resulting DataFrame, and then subtract out the summation of the first three quarters for the <strong>Ending Inventory</strong> column, but that seems incredibly awkward.</p>
<p>Any suggestions?</p>
<p>Thanks!</p>
| 1 |
2016-09-10T17:02:53Z
| 39,433,840 |
<pre><code>agg_dict = {'Quarterly Sales': 'sum', 'Ending Inventory': 'last'}
pnl.to_frame().T.stack(0).groupby(level='Type').agg(agg_dict)
</code></pre>
<p><a href="http://i.stack.imgur.com/ztaiy.png" rel="nofollow"><img src="http://i.stack.imgur.com/ztaiy.png" alt="enter image description here"></a></p>
| 0 |
2016-09-11T07:30:12Z
|
[
"python",
"pandas"
] |
Best approach to make a reverse five-star calculator
| 39,428,609 |
<p>In the 5-star rating system, I have a known number of ratings.<br>
I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br>
I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s) which result in R. </p>
<p>How would I approach this problem?</p>
<p><strong>Example:</strong></p>
<p>N= 20 customers rated a product<br>
R = 3.85 is the average rating</p>
<p>Output I am looking for:</p>
<blockquote>
<p>10 five-stars, 4 four-stars, 1 three-stars, 3 two-stars, and 2 one-star </p>
</blockquote>
<p>is one combination which would give 3.85 by 20 customers.</p>
<p>How would I test if there are any more combinations which could result in the given R and print them out as well? </p>
| 2 |
2016-09-10T17:15:12Z
| 39,428,989 |
<p>(inefficient) Brute force solution. </p>
<p>Note: Can make more efficient by replacing <code>product(range(0, N+1), repeat=5)</code> with something else that can generate a list of 5 numbers that sum to N. </p>
<p>Find all lists of length 5 (for the ratings) up to N, then calculate the weighted average and compare against R. Print the lists as you go </p>
<pre><code>from itertools import product
def weighed_avergage(l, total):
if sum(l) != total:
return 0
return sum(rating * stars for rating, stars in zip(l, range(5, 0, -1))) / float(total)
N = 20
R = 3.85
for p in product(range(0, N+1), repeat=5):
w_avg = weighed_avergage(p, N)
if w_avg == R:
print p
</code></pre>
<p>Should see <code>(10, 4, 1, 3, 2)</code> in the output, which corresponds to your question of 10 five-stars, 4 four-stars, 1 three-stars, 3 two-stars, and 2 one-star</p>
| 0 |
2016-09-10T17:57:07Z
|
[
"python",
"algorithm"
] |
Best approach to make a reverse five-star calculator
| 39,428,609 |
<p>In the 5-star rating system, I have a known number of ratings.<br>
I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br>
I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s) which result in R. </p>
<p>How would I approach this problem?</p>
<p><strong>Example:</strong></p>
<p>N= 20 customers rated a product<br>
R = 3.85 is the average rating</p>
<p>Output I am looking for:</p>
<blockquote>
<p>10 five-stars, 4 four-stars, 1 three-stars, 3 two-stars, and 2 one-star </p>
</blockquote>
<p>is one combination which would give 3.85 by 20 customers.</p>
<p>How would I test if there are any more combinations which could result in the given R and print them out as well? </p>
| 2 |
2016-09-10T17:15:12Z
| 39,429,980 |
<p>You can enumerate all the distributions of votes using a recursive algorithm and then check which of those have correct weighted average. But note that the number of combinations grows quickly.</p>
<pre><code>def distributions(ratings, remaining):
if len(ratings) > 1:
# more than one rating: take some for first and distribute rest
for n in range(remaining+1):
for dist in distributions(ratings[1:], remaining - n):
yield [(ratings[0], n)] + dist
elif len(ratings) == 1:
# only one rating left -> all remaining go there
yield [(ratings[0], remaining)]
else:
# should never happen
raise ValueError("No more ratings left")
def weighted_avg(votes):
return sum(r * n for r, n in votes) / sum(n for r, n in votes)
for dist in distributions([1, 2, 3, 4, 5], 20):
if weighted_avg(dist) == 3.85:
print(dist)
</code></pre>
<p>In total there are <code>10626</code> distributions, and <code>146</code> of those yield the correct average. Output (some):</p>
<pre><code>[(1, 0), (2, 0), (3, 3), (4, 17), (5, 0)]
[(1, 0), (2, 0), (3, 4), (4, 15), (5, 1)]
...
[(1, 2), (2, 3), (3, 1), (4, 4), (5, 10)]
...
[(1, 5), (2, 0), (3, 1), (4, 1), (5, 13)]
[(1, 5), (2, 1), (3, 0), (4, 0), (5, 14)]
</code></pre>
| 0 |
2016-09-10T19:47:02Z
|
[
"python",
"algorithm"
] |
Best approach to make a reverse five-star calculator
| 39,428,609 |
<p>In the 5-star rating system, I have a known number of ratings.<br>
I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br>
I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s) which result in R. </p>
<p>How would I approach this problem?</p>
<p><strong>Example:</strong></p>
<p>N= 20 customers rated a product<br>
R = 3.85 is the average rating</p>
<p>Output I am looking for:</p>
<blockquote>
<p>10 five-stars, 4 four-stars, 1 three-stars, 3 two-stars, and 2 one-star </p>
</blockquote>
<p>is one combination which would give 3.85 by 20 customers.</p>
<p>How would I test if there are any more combinations which could result in the given R and print them out as well? </p>
| 2 |
2016-09-10T17:15:12Z
| 39,430,271 |
<p>The total number of stars is N*R (20 * 3.85 = 77 in your example). Now what you have similar to <a href="https://en.wikipedia.org/wiki/Change-making_problem" rel="nofollow">the change making problem</a> except that your total number of coins is fixed.</p>
<p>An efficient solution might be to start with as many large coins (5 star ratings) as would not exceed the total, and decrease until you have ratings that would not make the total. You still end up checking solutions that don't work, but it will be significantly faster than checking all solutions, especially for large problem sizes.</p>
<p>Here is my solution: (EDIT: Solution debugged. I don't think its the optimal solution, but its better than brute force. 1931 recursive calls for the sample case of N=20 R=3.85)</p>
<pre><code>def distribution(total, maxRating, N, solution):
if total == 0 and N == 0:
return [solution + [0] * maxRating] #we found a solution
if total == 0 or N == 0:
return [] # no solution possible
largestUpperLimit = min(total // maxRating, N) # an upper limit for the number of reviews with the largest rating
largestLowerLimit = max((total - N * (maxRating -1)) // maxRating, 0) # a lower limit for the number of reviews with the largest rating
if N < largestLowerLimit:
return [] # there aren't enough ratings to make any solutions
else:
solutions = []
for i in range(largestLowerLimit, largestUpperLimit + 1): # plus 1 to include the upper limit
solutions.extend(distribution(total - i * maxRating, maxRating - 1, N - i, solution + [i]))
return solutions
# Using the function example:
solutions = distribution(N * R, 5, N, [])
</code></pre>
| 0 |
2016-09-10T20:24:03Z
|
[
"python",
"algorithm"
] |
Best approach to make a reverse five-star calculator
| 39,428,609 |
<p>In the 5-star rating system, I have a known number of ratings.<br>
I have the final (weighted) average of all those N ratings, let's say it is R (float to two decimal places).<br>
I would like to write a python script which generates all possible combinations (Total of weighted averages) and print out only the one(s) which result in R. </p>
<p>How would I approach this problem?</p>
<p><strong>Example:</strong></p>
<p>N= 20 customers rated a product<br>
R = 3.85 is the average rating</p>
<p>Output I am looking for:</p>
<blockquote>
<p>10 five-stars, 4 four-stars, 1 three-stars, 3 two-stars, and 2 one-star </p>
</blockquote>
<p>is one combination which would give 3.85 by 20 customers.</p>
<p>How would I test if there are any more combinations which could result in the given R and print them out as well? </p>
| 2 |
2016-09-10T17:15:12Z
| 39,431,051 |
<p>Here is an algorithm that doesn't use brute force. The indented code shows an example.</p>
<p>You have the number of ratings N and their average R.<br>
Let <code>si</code> be the number of i-stars ratings (with <code>i in [1..5]</code>).<br>
We have <code>s1 + s2 + s3 + s4 + s5 = N</code>.<br>
We also have <code>s1 + 2*s2 + 3*s3 + 4*s4 + 5*s5 = R*N</code>.</p>
<pre><code> s1 + s2 + s3 + s4 + s5 = 20
s1 + 2*s2 + 3*s3 + 4*s4 + 5*s5 = 77
</code></pre>
<p>Hence <code>s2 + 2*s3 + 3*s4 + 4*s5 = R*N - N</code>.<br>
Now choose a value for <code>s1</code> and calculate <code>s2 + s3 + s4 + s5 = N - s1</code>.</p>
<pre><code> s2 + 2*s3 + 3*s4 + 4*s5 = 57
s1 = 4
s2 + s3 + s4 + s5 = 16
</code></pre>
<p>We can continue with <code>s3 + 2*s4 + 3*s5 = (R*N - N) - (N - s1)</code>.<br>
Choose a value for <code>s2</code> and calculate <code>s3 + s4 + s5 = N - s1 - s2</code>.</p>
<pre><code> s3 + 2*s4 + 3*s5 = 41
s2 = 2
s3 + s4 + s5 = 14
</code></pre>
<p>Repeat with <code>s3</code> and get the value for <code>s5</code> and <code>s4</code>.</p>
<pre><code> s4 + 2*s5 = 27
s3 = 9
s4 + s5 = 5
s5 = 22
s4 = -17
</code></pre>
<p>Now, obviously, this produces incorrect solutions (in the example, <code>s5 > 20</code> and <code>s4 < 0</code>). In order to avoid that, we can constrain the value choices each time.<br>
We need to choose <code>s3</code> so that <code>s4 + s5 >= (s4 + 2*s5)/2</code>, so that we end up with <code>s5 <= s4 + s5</code>.<br>
This is possible only if <code>s3 + s4 + s5 >= (s3 + 2*s4 + 3*s5)/3</code>, hence another constraint, this time for <code>s2</code>.<br>
And finally, the constraint for <code>s1</code> is <code>s2 + s3 + s4 + s5 >= (s2 + 2*s3 + 3*s4 + 4*s5)/4</code>.</p>
| 0 |
2016-09-10T22:12:11Z
|
[
"python",
"algorithm"
] |
python - print a csv row into a HTML column
| 39,428,639 |
<p>I'm trying to print the data of a CSV column into an HTML table</p>
<p>CSV file is like this (sample) </p>
<pre><code>firstname, surname
firstname, surname
firstname, surname
firstname, surname
firstname, surname
firstname, surname
firstname, surname
</code></pre>
<p>I can read this data in ok - and get it to print out into a table via the following:</p>
<pre><code>import csv
import sys
from fpdf import FPDF, HTMLMixin
#load in csv file
data = csv.reader(open(sys.argv[1]))
names = ""
#Read column names from first line of the file
fields = data.next()
for row in data:
names = row[0] + " " + row[1]
html_row = " <tr> "
html_col = " <td border=0 width=15%>" + names + "</td></tr>"
html_out = html_out + html_row + html_col
html = html_header + html_out + html_footer
print html
pdf.write_html(html)
pdf.output('test2.pdf', 'F')
</code></pre>
<p>this gives the following:</p>
<pre><code><tr><td border=0 width=15%>firstname surname</td></tr>
<tr><td border=0 width=15%>firstname surname</td></tr>
<tr><td border=0 width=15%>firstname surname</td></tr>
</code></pre>
<p>ie - every name is on a separate row - what i'd like to do is have every name as a cell column cell </p>
<pre><code><tr><td border=0 width=15%>firstname surname</td><td border=0 width=15%>firstname surname</td><td border=0 width=15%>firstname surname</td></tr>
</code></pre>
<p>thanks</p>
| 1 |
2016-09-10T17:18:27Z
| 39,428,709 |
<p>You only need one <code><tr></code> to make a single row.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, td {
border: solid 1px #CCC;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
<td>firstname surname</td>
<td>firstname surname</td>
<td>firstname surname</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<p>In order to make this work in your code, you need to create you row outside the loop:</p>
<pre><code>html_row = '<tr>' # open row
for row in data:
names = row[0] + " " + row[1]
# append columns to the row
html_row += "<td border=0 width=15%>" + names + "</td>"
html_row += '</tr>' # close row
html_out = html_row
</code></pre>
| -1 |
2016-09-10T17:26:49Z
|
[
"python",
"html"
] |
python - print a csv row into a HTML column
| 39,428,639 |
<p>I'm trying to print the data of a CSV column into an HTML table</p>
<p>CSV file is like this (sample) </p>
<pre><code>firstname, surname
firstname, surname
firstname, surname
firstname, surname
firstname, surname
firstname, surname
firstname, surname
</code></pre>
<p>I can read this data in ok - and get it to print out into a table via the following:</p>
<pre><code>import csv
import sys
from fpdf import FPDF, HTMLMixin
#load in csv file
data = csv.reader(open(sys.argv[1]))
names = ""
#Read column names from first line of the file
fields = data.next()
for row in data:
names = row[0] + " " + row[1]
html_row = " <tr> "
html_col = " <td border=0 width=15%>" + names + "</td></tr>"
html_out = html_out + html_row + html_col
html = html_header + html_out + html_footer
print html
pdf.write_html(html)
pdf.output('test2.pdf', 'F')
</code></pre>
<p>this gives the following:</p>
<pre><code><tr><td border=0 width=15%>firstname surname</td></tr>
<tr><td border=0 width=15%>firstname surname</td></tr>
<tr><td border=0 width=15%>firstname surname</td></tr>
</code></pre>
<p>ie - every name is on a separate row - what i'd like to do is have every name as a cell column cell </p>
<pre><code><tr><td border=0 width=15%>firstname surname</td><td border=0 width=15%>firstname surname</td><td border=0 width=15%>firstname surname</td></tr>
</code></pre>
<p>thanks</p>
| 1 |
2016-09-10T17:18:27Z
| 39,428,879 |
<p>Some variables in sample are not set, but this is due to reducing of sample to aminimal size I guess, so if you fill in these details, the following should work (suboptimal if more than 7 entries due to the hardcoded 15% width on the html td element.</p>
<pre><code>import csv
import sys
from fpdf import FPDF, HTMLMixin
# load in csv file
data = csv.reader(open(sys.argv[1]))
# Read column names from first line of the file to ignore them
fields = data.next()
</code></pre>
<p>Below the loop from question has been replaced by a list comprehension.
cell_att holds the given attributes of the table cell elements and it will be interpolated like row[0] and row[1] into the strings making up the html_out list.</p>
<pre><code>cell_att = " border=0 width=15%"
row_data = ["<td%s>%s %s</td>" % (cell_att, row[0], row[1]) for row in data]
</code></pre>
<p>Here one simply joins all cells and injects into a html table row element:</p>
<pre><code>html_out = "<tr>" + "".join(row_data) + "</tr>"
html = html_header + html_out + html_footer
print html
pdf.write_html(html)
pdf.output('test2.pdf', 'F')
</code></pre>
<p>The other answers also give IMO useful hints esp. on the styling level of the HTML. In case you later decide to digest / transform more than 7 names, the above code might be a good start to create rows with at most 7 cells or to adapt the width attribute value by minor modifications.</p>
| 0 |
2016-09-10T17:44:55Z
|
[
"python",
"html"
] |
Colouring in between two lines in 3D plot
| 39,428,656 |
<p>I am trying the fill the space between my lines in 3D. </p>
<p>I have the following code:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
import numpy as np
class plotting3D(object):
"""
Class to plot 3d
"""
def __init__(self):
pass
def cc(self, arg):
return colorConverter.to_rgba(arg, alpha=0.6)
def poly3d(self, df):
"""
Method to create depth of joints plot for GP regression.
"""
fig = plt.figure(figsize=(10,10))
ax = fig.gca(projection='3d')
which_joints = df.columns
dix = df.index.values
zs = [1,4]
verts = []
for j in which_joints:
verts.append(list(zip(dix,df[j])))
poly = PolyCollection(verts,facecolors=[self.cc('r'), self.cc('g')])
poly.set_alpha(0.6)
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_ylim([0, 5])
ax.set_zlim([0, 20])
ax.set_xlim([0,dix[-1]])
ax.grid(False)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
</code></pre>
<p>Some synthetic data:</p>
<pre><code>k= pd.DataFrame(20*np.random.rand(10,2),columns=['foot','other_foot'])
</code></pre>
<p>Produces this:</p>
<p><a href="http://i.stack.imgur.com/FxvNj.png" rel="nofollow"><img src="http://i.stack.imgur.com/FxvNj.png" alt="enter image description here"></a></p>
<p>Now I want to fill the space between the lines and say <code>z=-30</code> NOT <code>z=0</code> which is what I am trying to change.</p>
<p><code>df.index.values</code> take a values between <code>0</code> and say <code>1000</code>. And the <code>ang</code> dataframe has values ranging from <code>-30</code> to <code>10</code>.</p>
<p>Hence, I am trying to produce an offset version of this:</p>
<p><a href="http://i.stack.imgur.com/Widby.png" rel="nofollow"><img src="http://i.stack.imgur.com/Widby.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T17:20:43Z
| 39,429,621 |
<p>Another solution to my suggestion in the comments is to use <code>fill_between</code>; there you have the possibility to set the lower boundary. <code>fill_between</code> returns a <code>PolyCollection</code>, so you can add it to the <code>3d</code> figure similar to what you are doing now:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10,10))
ax = fig.gca(projection='3d')
# +/- your data:
z = [0,10,10,-20,10,0]
x = [0,1000,1500,2500,3000,3500]
ax.add_collection3d(plt.fill_between(x,z,0), zs=1, zdir='y') # lower boundary z=0
ax.add_collection3d(plt.fill_between(x,z,-30), zs=5, zdir='y') # lower boundary z=-30
ax.set_ylim([0, 5])
ax.set_zlim([-30, 20])
ax.set_xlim([0,3500])
</code></pre>
<p><a href="http://i.stack.imgur.com/Jo8j2.png" rel="nofollow"><img src="http://i.stack.imgur.com/Jo8j2.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T19:07:16Z
|
[
"python",
"matplotlib"
] |
Django INSTALLED_APPS not installed and preventing makemigrations
| 39,428,728 |
<p>I recently pulled a repo from GitHub to get a local copy on my machine. The backend uses Django, and I was working on updating some models. Since I changed some models I wanted to run <code>./manage.py makemigrations</code>. At first there was an issue with python2 vs python3, so I changed the <code>#!/usr/bin/env python</code> to <code>#!/usr/bin/env python3</code>. Then when I ran makemigrations, I get this:</p>
<pre><code> File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'autofixture'
</code></pre>
<p>Looking a bit further, I found out that this is because my <code>settings.py</code> file has <code>autofixture</code>, <code>bootstrap3</code>, and <code>formtools</code> in <code>INSTALLED_APPS</code>, but somehow my machine doesn't have those. I've tried to <code>pip install</code> all of them but the names autofixture, bootstrap3, and formtools aren't found in pip.</p>
| 0 |
2016-09-10T17:28:15Z
| 39,428,804 |
<p>They are in pip, albeit not in those names; they are <code>django-autofixture</code>, <code>django-bootstrap3</code> and <code>django-formtools</code> respectively.</p>
<p>So you can install them by typing:</p>
<pre><code>pip install django-autofixture django-bootstrap3 django-formtools
</code></pre>
<p><strong>Edit</strong>: Use <code>pip3</code> instead of <code>pip</code> when using python3</p>
<pre><code> pip3 install django-autofixture django-bootstrap3 django-formtools
</code></pre>
| 1 |
2016-09-10T17:36:17Z
|
[
"python",
"django",
"django-models",
"pip"
] |
Foreign key model in Django Admin
| 39,428,742 |
<p>I have two user roles in Django:</p>
<ul>
<li>Commercials</li>
<li>Sellers</li>
</ul>
<p>I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). When I register the models in admin I can create Commercials and related sellers using <code>StackedInline</code>, <code>TabularInline</code> etc.</p>
<p>The problem I have is I need to associate users to this models in order to authenticate, login, etc. In admin I need to create a user (in an inline way, not dropdown box)</p>
<p>This is my code:</p>
<p>In <strong>models.py</strong>:</p>
<pre><code>class Commercial(models.Model):
name = models.CharField(max_length=255, null=True)
user = models.OneToOneField(User, null=True)
class Seller(models.Model):
name = models.CharField(max_length=255, null=True)
commercial = models.ForeignKey('Commercial')
user = models.OneToOneField(User, null=True)
</code></pre>
<p>In <strong>admin.py</strong>:</p>
<pre><code>class SellerAdmin(admin.StackedInline):
model = Seller
extra = 1
class CommercialAdmin(admin.ModelAdmin):
inlines = [SellerAdmin]
admin.site.register(Commercial, CommercialAdmin)
</code></pre>
<p>I need to edit, create, users etc. related to this models inline not in a modal window, Is there any way?</p>
<p><a href="http://i.stack.imgur.com/w54tZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/w54tZ.png" alt="enter image description here"></a></p>
| 0 |
2016-09-10T17:29:19Z
| 39,430,137 |
<p>There is no way to make a reverse relation (so to say) in the form of Inlines. The Django admin panel doesn't have that ability by default.</p>
<p>What you could do is unregister the default UserAdmin, create a new Admin panel by inheriting the original one, and add this Seller as an Inline. There is still the issue that Django doesn't support multiple inlines, hence, you will not be able to use the Commercial model in the same admin page.</p>
<p>To fix that, you could refer to <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form" rel="nofollow">this information from the doc</a> which shows how to overwrite the automatically created ModelForm for a particular ModelAdmin. </p>
<p>This will however not be that helpful as they are a lot of work. I would rather suggest implementing a workaround in how your application is used, rather than complicating it this much. Depends on the needs of the project, whether you need to go through this much trouble</p>
| 0 |
2016-09-10T20:06:08Z
|
[
"python",
"django",
"django-models",
"django-admin"
] |
Foreign key model in Django Admin
| 39,428,742 |
<p>I have two user roles in Django:</p>
<ul>
<li>Commercials</li>
<li>Sellers</li>
</ul>
<p>I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). When I register the models in admin I can create Commercials and related sellers using <code>StackedInline</code>, <code>TabularInline</code> etc.</p>
<p>The problem I have is I need to associate users to this models in order to authenticate, login, etc. In admin I need to create a user (in an inline way, not dropdown box)</p>
<p>This is my code:</p>
<p>In <strong>models.py</strong>:</p>
<pre><code>class Commercial(models.Model):
name = models.CharField(max_length=255, null=True)
user = models.OneToOneField(User, null=True)
class Seller(models.Model):
name = models.CharField(max_length=255, null=True)
commercial = models.ForeignKey('Commercial')
user = models.OneToOneField(User, null=True)
</code></pre>
<p>In <strong>admin.py</strong>:</p>
<pre><code>class SellerAdmin(admin.StackedInline):
model = Seller
extra = 1
class CommercialAdmin(admin.ModelAdmin):
inlines = [SellerAdmin]
admin.site.register(Commercial, CommercialAdmin)
</code></pre>
<p>I need to edit, create, users etc. related to this models inline not in a modal window, Is there any way?</p>
<p><a href="http://i.stack.imgur.com/w54tZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/w54tZ.png" alt="enter image description here"></a></p>
| 0 |
2016-09-10T17:29:19Z
| 39,430,241 |
<p><a href="https://github.com/s-block/django-nested-inline" rel="nofollow">Django nested inlines</a> library might help you.</p>
| 1 |
2016-09-10T20:20:14Z
|
[
"python",
"django",
"django-models",
"django-admin"
] |
Unable to click invisible select python
| 39,428,763 |
<p>I am trying to retrieve all possible lists from <a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx" rel="nofollow">this website</a></p>
<p>Model will only open when year is selected. Similarly Make will only open when Model is selected. I want to store all combination of Year, Model and Make for learning purpose.</p>
<p>However I am not able to click year field only. It seems it is hidden and without this I can't go ahead with rest of code.</p>
<pre><code>from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx")
# Switch to new window opened
driver.switch_to.window(driver.window_handles[-1])
# Close the new window
driver.close()
# Switch back to original browser (first window)
driver.switch_to.window(driver.window_handles[0])
el = driver.find_element_by_id('sbToggle_27562807')
el.click()
</code></pre>
<p>It gives error :-</p>
<blockquote>
<p>Message: no such element: Unable to locate element: {"method":"id","selector":"sbToggle_27562807"}</p>
</blockquote>
| 1 |
2016-09-10T17:31:12Z
| 39,429,008 |
<p>The element IDs change on each reload of the page, you'll have to find a different way to find the dropdown.</p>
<p>You can always find the <code><a></code> link with the "-- Select Year --" text, for example. </p>
| 1 |
2016-09-10T17:59:53Z
|
[
"python",
"selenium",
"web-scraping"
] |
Unable to click invisible select python
| 39,428,763 |
<p>I am trying to retrieve all possible lists from <a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx" rel="nofollow">this website</a></p>
<p>Model will only open when year is selected. Similarly Make will only open when Model is selected. I want to store all combination of Year, Model and Make for learning purpose.</p>
<p>However I am not able to click year field only. It seems it is hidden and without this I can't go ahead with rest of code.</p>
<pre><code>from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx")
# Switch to new window opened
driver.switch_to.window(driver.window_handles[-1])
# Close the new window
driver.close()
# Switch back to original browser (first window)
driver.switch_to.window(driver.window_handles[0])
el = driver.find_element_by_id('sbToggle_27562807')
el.click()
</code></pre>
<p>It gives error :-</p>
<blockquote>
<p>Message: no such element: Unable to locate element: {"method":"id","selector":"sbToggle_27562807"}</p>
</blockquote>
| 1 |
2016-09-10T17:31:12Z
| 39,429,236 |
<p>Use this CSS selector to get to the arrow pointing downwards on the select year dropdown</p>
<pre><code>"div[id='fldYear'] > div[class='sbHolder'] > a[class='sbToggle']"
</code></pre>
<p>or this xpath</p>
<pre><code>"//div[@id='fldYear']/div[@class='sbHolder']/a[@class='sbToggle']"
</code></pre>
<p>Click on this to webelement to get the options</p>
| 1 |
2016-09-10T18:23:28Z
|
[
"python",
"selenium",
"web-scraping"
] |
Unable to click invisible select python
| 39,428,763 |
<p>I am trying to retrieve all possible lists from <a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx" rel="nofollow">this website</a></p>
<p>Model will only open when year is selected. Similarly Make will only open when Model is selected. I want to store all combination of Year, Model and Make for learning purpose.</p>
<p>However I am not able to click year field only. It seems it is hidden and without this I can't go ahead with rest of code.</p>
<pre><code>from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx")
# Switch to new window opened
driver.switch_to.window(driver.window_handles[-1])
# Close the new window
driver.close()
# Switch back to original browser (first window)
driver.switch_to.window(driver.window_handles[0])
el = driver.find_element_by_id('sbToggle_27562807')
el.click()
</code></pre>
<p>It gives error :-</p>
<blockquote>
<p>Message: no such element: Unable to locate element: {"method":"id","selector":"sbToggle_27562807"}</p>
</blockquote>
| 1 |
2016-09-10T17:31:12Z
| 39,429,410 |
<blockquote>
<p>Message: no such element: Unable to locate element: {"method":"id","selector":"sbToggle_27562807"}</p>
</blockquote>
<p><code>year</code> element is not hidden, actually your locator to locate element using <code>find_element_by_id('sbToggle_27562807')</code> is not correct. In this element <code>id</code> attribute value is dynamically changing that's why you're unable to locate this element.</p>
<p>Instead of <code>id</code> locator you should try using some different locator. I would suggest, for better way try using <code>find_element_by_css_selector()</code> as below :-</p>
<pre><code>el = driver.find_element_by_css_selector("div#fldYear a.sbToggle")
el.click()
</code></pre>
| 1 |
2016-09-10T18:43:17Z
|
[
"python",
"selenium",
"web-scraping"
] |
Resizing NVSS FITS format file in Python and operating on this file in astropy
| 39,428,799 |
<p>this questions is probably mainly for more or less advances astronomers.</p>
<p>Do you know how to transform NVSS fits file to the fits with only 2 (NOT 4!) axes? Or how to deal with the file which has 4 axis and generates the following errors in Python when I'm trying to overlapp nvss countours on optical DSS data, using astropy and other "astro" libraries for Python? (code below)</p>
<p>I've tried to do it and when there is thess 4 axes for NVSS FITS, there is error messages and warnings:</p>
<p>WARNING: FITSFixedWarning: The WCS transformation has more axes (4) than the image it is associated with (2) [astropy.wcs.wcs]
WARNING: FITSFixedWarning: 'datfix' made the change 'Invalid parameter value: invalid date '19970331''. [astropy.wcs.wcs]
<a href="http://stackoverflow.com/questions/33107224/re-sizing-a-fits-image-in-python">re-sizing a fits image in python</a></p>
<p>WARNING: FITSFixedWarning: 'datfix' made the change 'Invalid parameter value: invalid date '19970331''. [astropy.wcs.wcs]
Traceback (most recent call last):
File "p.py", line 118, in
cont2 = ax[Header2].contour(opt.data, [-8,-2,2,4], colors="r", linewidth = 10, zorder = 2)
File "/home/ela/anaconda2/lib/python2.7/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py", line 195, in contour
return self._contour("contour", *XYCL, **kwargs)
File "/home/ela/anaconda2/lib/python2.7/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py", line 167, in _contour
ny, nx = C.shape
ValueError: too many values to unpack</p>
<p>I've also tried to use the FITS_tools/match_images.py to resize the NVSS FITS first to the normal 2 axis size of the DSS file, and then to use the corrected file instead of the original one, but it only gives me an error:</p>
<p>Traceback (most recent call last):
File "p.py", line 64, in
im1,im2 = FITS_tools.match_fits(to_be_projected,reference_fits)
File "/home/ela/anaconda2/lib/python2.7/site-packages/FITS_tools/match_images.py", line 105, in match_fits
image1_projected = project_to_header(fitsfile1, header, **kwargs)
File "/home/ela/anaconda2/lib/python2.7/site-packages/FITS_tools/match_images.py", line 64, in project_to_header
**kwargs)
File "/home/ela/anaconda2/lib/python2.7/site-packages/FITS_tools/hcongrid.py", line 49, in hcongrid
grid1 = get_pixel_mapping(header1, header2)
File "/home/ela/anaconda2/lib/python2.7/site-packages/FITS_tools/hcongrid.py", line 128, in get_pixel_mapping
csys2 = _ctype_to_csys(wcs2.wcs)
File "/home/ela/anaconda2/lib/python2.7/site-packages/FITS_tools/hcongrid.py", line 169, in _ctype_to_csys
raise NotImplementedError("Non-fk4/fk5 equinoxes are not allowed")
NotImplementedError: Non-fk4/fk5 equinoxes are not allowed</p>
<p>I have no idea what to do. There is no similar problem with the FIRST.FITS files. Imsize in Python also tells me the NVSS is the only one who is 4 dimensional for example (1, 1, 250, 250). So it could not be overlaied properley. Do you have ANY idea? Please help me and I can donate your projects in revange. I spent few days trying to solve it and it's still not working, but I need it desperately.</p>
<p>CODE</p>
<pre><code># Import matplotlib modules
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from matplotlib.axes import Axes
import matplotlib.cm as cm
from matplotlib.patches import Ellipse
import linecache
import FITS_tools
# Import numpy and scipy for filtering
import scipy.ndimage as nd
import numpy as np
import pyfits
import matplotlib.pyplot
import pylab
#Import astronomical libraries
from astropy.io import fits
import astropy.units as u
#from astroquery.ned import Ned
import pywcsgrid2
# Read and prepare the data
file1=open('/home/ela/file')
count=len(open('file', 'rU').readlines())
print count
for i in xrange(count):
wiersz=file1.readline()
title=str(wiersz)
print title
title2=title.strip("\n")
print title2
path = '/home/ela/'
fitstitle = path+title2+'_DSS.FITS'
fitstitle2 = path+title2+'_FIRST.FITS'
fitstitle3 = path+title2+'_NVSS.FITS'
datafile = path+title2
outtitle = path+title2+'.png'
print outtitle
print datafile
nvss = fits.open(fitstitle)[0]
first = fits.open(fitstitle2)[0]
opt = fits.open(fitstitle3)[0]
try:
fsock = fits.open(fitstitle3) #(2)
except IOError:
print "Plik nie istnieje"
print "Ta linia zawsze zostanie wypisana" #(3)
opt.verify('fix')
first.verify('fix')
nvss.verify('fix')
Header = nvss.header
Header2 = first.header
Header3 = opt.header
to_be_projected = path+title2+'_NVSS.FITS'
reference_fits = path+title2+'_DSS.FITS'
im1,im2 = FITS_tools.match_fits(to_be_projected,reference_fits)
print(opt.shape)
print(first.shape)
print(nvss.shape)
print(im2.shape)
#We select the range we want to plot
minmax_image = [np.average(nvss.data)-6.*np.std(nvss.data), np.average(nvss.data)+5.*np.std(nvss.data)] #Min and max value for the image
minmax_PM = [-500., 500.]
# PREPARE PYWCSGRID2 AXES AND FIGURE
params = {'text.usetex': True,'font.family': 'serif', 'font.serif': 'Times New Roman'}
plt.rcParams.update(params)
#INITIALIZE FIGURE
fig = plt.figure(1)
ax = pywcsgrid2.subplot(111, header=Header)
#CREATE COLORBAR AXIS
divider = make_axes_locatable(ax)
cax = divider.new_horizontal("5%", pad=0.1, axes_class=Axes)
#fig.add_axes(cax)
#Configure axis
ax.grid() #Will plot a grid in the figure
# ax.set_ticklabel_type("arcmin", center_pixel=[Header['CRPIX1'],Header['CRPIX2']]) #Coordinates centered at the galaxy
ax.set_ticklabel_type("arcmin") #Coordinates centered at the galaxy
ax.set_display_coord_system("fk5")
# ax.add_compass(loc=3) #Add a compass at the bottom left of the image
#Plot the u filter image
i = ax.imshow(nvss.data, origin="lower", interpolation="nearest", cmap=cm.bone_r, vmin= minmax_image[0], vmax = minmax_image[1], zorder = 0)
#Plot contours from the infrared image
cont = ax[Header2].contour(nd.gaussian_filter(first.data,4),2 , colors="r", linewidth = 20, zorder = 2)
# cont = ax[Header2].contour(first.data, [-2,0,2], colors="r", linewidth = 20, zorder = 1)
# cont2 = ax[Header2].contour(opt.data, [-8,-2,2,4], colors="r", linewidth = 10, zorder = 2)
#Plot PN positions with color coded velocities
# Velocities = ax['fk5'].scatter(Close_to_M31_PNs['RA(deg)'], Close_to_M31_PNs['DEC(deg)'], c = Close_to_M31_PNs['Velocity'], s = 30, cmap=cm.RdBu, edgecolor = 'none',
# vmin = minmax_PM[0], vmax = minmax_PM[1], zorder = 2)
f2=open(datafile)
count2=len(open('f2', 'rU').readlines())
print count2
for i in xrange(count):
xx=f2.readline()
# print xx
yy=f2.readline()
xxx=float(xx)
print xxx
yyy=float(yy)
print yyy
Velocities = ax['fk5'].scatter(xxx, yyy ,c=40, s = 200, marker='x', edgecolor = 'red', vmin = minmax_PM[0], vmax = minmax_PM[1], zorder = 1)
it2 = ax.add_inner_title(title2, loc=1)
# Plot the colorbar, with the v_los of the PN
# cbar = plt.colorbar(Velocities, cax=cax)
# cbar.set_label(r'$v_{los}[$m s$^{-1}]$')
# set_label('4444')
plt.show()
plt.savefig(outtitle)
#plt.savefig("image1.png")
</code></pre>
| -1 |
2016-09-10T17:35:21Z
| 39,437,514 |
<p>To clarify for general use: this is a question about how to handle FITS files with degenerate axes, which are commonly produced by the <a href="https://casa.nrao.edu/" rel="nofollow">CASA data reduction program</a> and other radio data reduction tools; the degenerate axes are frequency/wavelength and stokes. Some of the astropy affiliated tools know how to handle these (e.g., <a href="https://aplpy.github.io/" rel="nofollow">aplpy</a>), but many do not.</p>
<p>The simplest answer is to just use <code>squeeze</code> to drop the degenerate axes in the data. However, if you want to preserve the metadata when doing this, there's a little more involved:</p>
<pre><code>from astropy.io import fits
from astropy import wcs
fh = fits.open('file.fits')
data = fh[0].data.squeeze() # drops the size-1 axes
header = fh[0].header
mywcs = wcs.WCS(header).celestial
new_header = mywcs.to_header()
new_fh = fits.PrimaryHDU(data=data, header=new_header)
new_fh.writeto('new_file.fits')
</code></pre>
<p>That approach will give you a file with a valid celestial (RA/Dec) header, but it will lose all of the other header information.</p>
<p>If you want to preserve the other header information, you can use the <a href="http://fits-tools.readthedocs.io/en/latest/fits_tools.html" rel="nofollow"><code>FITS_tools</code></a> tool <a href="https://github.com/keflavich/FITS_tools/blob/master/FITS_tools/strip_headers.py" rel="nofollow"><code>flatten_header</code></a> instead of using the WCS operations above:</p>
<pre><code>new_header = FITS_tools.strip_headers.flatten_header(header)
</code></pre>
| 1 |
2016-09-11T15:10:57Z
|
[
"python",
"astronomy",
"astropy",
"fits",
"pyfits"
] |
Is this a recursive or iterative function?
| 39,428,810 |
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p>
<p><em>1.11 A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.</em></p>
<p>A fully recursive function in Racket for this exercise is easy:</p>
<pre><code> (define (f n)
(cond ((< n 3) n)
(else (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))))))
</code></pre>
<p>It is tough to build an iterative one. Since I was not figuring it out, I tried with Python.</p>
<p>When I did it in python, it came out with the following code:</p>
<pre><code>def funcao_f(n):
count = 0
limite = n - 2
soma = 0
if n<3:
return n
else:
while count!=limite:
count = count + 1
soma = funcao_f(n-1)+2*funcao_f(n-2)+3*funcao_f(n-3)
return soma
</code></pre>
<p>I am in doubt about the nature of this python code.</p>
<p>Is this a recursive function? </p>
<p>(I called funcao_f inside funcao_f)</p>
<p>Is this an iterative function? </p>
<p>(I am using a while loop inside it)</p>
<p>Does Python accept a process to be both, iterative and recursive?</p>
<p>I think the answer to this question might clear my understanding of the concepts if iteration and recursion. </p>
| -1 |
2016-09-10T17:36:42Z
| 39,428,946 |
<p>The function that you reported is a recursive function.</p>
<p>The Wikipedia <em>Recursion</em> page sentences:</p>
<blockquote>
<p>Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration).</p>
</blockquote>
<p>Usually, in a recursive algorithm you have to provide:</p>
<ol>
<li>the base case, when your recursion will end and</li>
<li>the recursion call/step.</li>
</ol>
<p>In your function the base case is:</p>
<pre><code>if n<3:
return n
</code></pre>
<p>and the recursive step is contained in the <em>else</em> branch:</p>
<pre><code>soma = funcao_f(n-1)+2*funcao_f(n-2)+3*funcao_f(n-3)
</code></pre>
<p>In fact, in the recursive step you are splitting the problem in three sub-problems as suggested by the definition that I have cited at the beginning of the answer.</p>
| 2 |
2016-09-10T17:52:34Z
|
[
"python",
"recursion",
"iteration",
"racket",
"sicp"
] |
Is this a recursive or iterative function?
| 39,428,810 |
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p>
<p><em>1.11 A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.</em></p>
<p>A fully recursive function in Racket for this exercise is easy:</p>
<pre><code> (define (f n)
(cond ((< n 3) n)
(else (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))))))
</code></pre>
<p>It is tough to build an iterative one. Since I was not figuring it out, I tried with Python.</p>
<p>When I did it in python, it came out with the following code:</p>
<pre><code>def funcao_f(n):
count = 0
limite = n - 2
soma = 0
if n<3:
return n
else:
while count!=limite:
count = count + 1
soma = funcao_f(n-1)+2*funcao_f(n-2)+3*funcao_f(n-3)
return soma
</code></pre>
<p>I am in doubt about the nature of this python code.</p>
<p>Is this a recursive function? </p>
<p>(I called funcao_f inside funcao_f)</p>
<p>Is this an iterative function? </p>
<p>(I am using a while loop inside it)</p>
<p>Does Python accept a process to be both, iterative and recursive?</p>
<p>I think the answer to this question might clear my understanding of the concepts if iteration and recursion. </p>
| -1 |
2016-09-10T17:36:42Z
| 39,429,032 |
<p>Your <code>funcao_f</code> function is recursive.</p>
<p>The definition of <strong>recursive</strong> function can be:
<em>f</em> is recursive if it calls <em>f</em> directly or indirectly, eg.:</p>
<pre><code>def f(x):
if x <= 0:
return 0
else:
return g(x)
def g(y):
return 5 + f(x - 1)
</code></pre>
<p>The definition of <strong>iterative</strong> function is not so easy to write. I think we could define it like this: <em>f</em> is iterative if it is not recursive.</p>
<p>Your lisp function:</p>
<pre><code>(define (f n)
(cond ((< n 3) n)
(else (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))))))
</code></pre>
<p>Could be translated in Python like this:</p>
<pre><code>def f(n):
if n < 3:
return n
else:
return f(n - 1) + 2 * f(n - 2) + 3 * f(n - 3)
</code></pre>
<p>To convert this function to an iterative function, you need 3 local variable to keep the values of <em>f</em> for <em>n</em> - 1, <em>n</em> - 2 and <em>n</em> - 3. And use a loop, of course.</p>
| 1 |
2016-09-10T18:02:28Z
|
[
"python",
"recursion",
"iteration",
"racket",
"sicp"
] |
Is this a recursive or iterative function?
| 39,428,810 |
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p>
<p><em>1.11 A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.</em></p>
<p>A fully recursive function in Racket for this exercise is easy:</p>
<pre><code> (define (f n)
(cond ((< n 3) n)
(else (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))))))
</code></pre>
<p>It is tough to build an iterative one. Since I was not figuring it out, I tried with Python.</p>
<p>When I did it in python, it came out with the following code:</p>
<pre><code>def funcao_f(n):
count = 0
limite = n - 2
soma = 0
if n<3:
return n
else:
while count!=limite:
count = count + 1
soma = funcao_f(n-1)+2*funcao_f(n-2)+3*funcao_f(n-3)
return soma
</code></pre>
<p>I am in doubt about the nature of this python code.</p>
<p>Is this a recursive function? </p>
<p>(I called funcao_f inside funcao_f)</p>
<p>Is this an iterative function? </p>
<p>(I am using a while loop inside it)</p>
<p>Does Python accept a process to be both, iterative and recursive?</p>
<p>I think the answer to this question might clear my understanding of the concepts if iteration and recursion. </p>
| -1 |
2016-09-10T17:36:42Z
| 39,429,725 |
<p>Note that the question asks about recursive and iterative <em>processes</em>. In scheme, both will be implemented using a recursive <em>function</em> (or <em>procedure</em>, as used in SICP), but the evaluation will be quite different. Please make sure you understand the difference between a recursive function and a recursive process as described in that chapter in SICP. (As scheme has tail-call-optimization, the fact that a procedure is recursive is "the syntactic fact that the procedure refers (either directly or indirectly) to itself" [SICP, 1.2.1])</p>
<p>If you compare with the recursive and iterative fibonacci exmples in the beginning of 1.2.2 Tree recursion, you can come up with a function with an iterative process, like</p>
<pre><code>(define (f n)
(define (f-iter i n m1 m2 m3)
(if (= i n)
(+ m1 (* 2 m2) (* 3 m3))
(f-iter (+ i 1) n (+ m1 (* 2 m2) (* 3 m3)) m1 m2)))
(if (< n 3)
n
(f-iter 3 n 2 1 0)))
</code></pre>
| 0 |
2016-09-10T19:16:40Z
|
[
"python",
"recursion",
"iteration",
"racket",
"sicp"
] |
Is this a recursive or iterative function?
| 39,428,810 |
<p>I am using the SICP book which is build for Scheme/Racket (lisp family). In this exercise I had some problems:</p>
<p><em>1.11 A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.</em></p>
<p>A fully recursive function in Racket for this exercise is easy:</p>
<pre><code> (define (f n)
(cond ((< n 3) n)
(else (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))))))
</code></pre>
<p>It is tough to build an iterative one. Since I was not figuring it out, I tried with Python.</p>
<p>When I did it in python, it came out with the following code:</p>
<pre><code>def funcao_f(n):
count = 0
limite = n - 2
soma = 0
if n<3:
return n
else:
while count!=limite:
count = count + 1
soma = funcao_f(n-1)+2*funcao_f(n-2)+3*funcao_f(n-3)
return soma
</code></pre>
<p>I am in doubt about the nature of this python code.</p>
<p>Is this a recursive function? </p>
<p>(I called funcao_f inside funcao_f)</p>
<p>Is this an iterative function? </p>
<p>(I am using a while loop inside it)</p>
<p>Does Python accept a process to be both, iterative and recursive?</p>
<p>I think the answer to this question might clear my understanding of the concepts if iteration and recursion. </p>
| -1 |
2016-09-10T17:36:42Z
| 39,430,548 |
<p>Adapting an iterative fibonacci answer</p>
<p><a href="http://stackoverflow.com/a/15047141/901925">http://stackoverflow.com/a/15047141/901925</a></p>
<pre><code>def f(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a + b
return a
</code></pre>
<p>This problem is:</p>
<pre><code>def far(n):
a,b,c=0,1,2
for _ in range(n):
a,b,c = b, c, a+b+c
return a # ,b,c
</code></pre>
<p>The recursive code is:</p>
<pre><code>def foo(n):
if n<3: return n
return foo(n-1)+foo(n-2)+foo(n-3)
</code></pre>
<p>and testing:</p>
<pre><code>In [814]: for i in range(10):
...: print(foo(i), far(i))
...:
0 0
1 1
2 2
3 3
6 6
11 11
20 20
37 37
68 68
125 125
</code></pre>
<p>The iterative version is significantly faster, especially as numbers grow (20 and above).</p>
| 0 |
2016-09-10T21:04:08Z
|
[
"python",
"recursion",
"iteration",
"racket",
"sicp"
] |
Creating a unique list with beautiful soup from href attribute Python
| 39,428,834 |
<p>I am trying to crate a unique list of all the hrefs on my anchor tags</p>
<pre><code>from urllib2 import urlopen
from bs4 import BeautifulSoup
import pprint
url = 'http://barrowslandscaping.com/'
soup = BeautifulSoup(urlopen(url), "html.parser")
print soup
tag = soup.find_all('a', {"href": True})
set(tag)
for tags in tag:
print tags.get('href')
</code></pre>
<p>result:</p>
<pre><code>http://barrowslandscaping.com/
http://barrowslandscaping.com/services/
http://barrowslandscaping.com/design-consultation/
http://barrowslandscaping.com/hydroseeding-sodding/
http://barrowslandscaping.com/landscape-installation/
http://barrowslandscaping.com/full-service-maintenance/
http://barrowslandscaping.com/portfolio/
http://barrowslandscaping.com/about-us/
http://barrowslandscaping.com/contact/
http://barrowslandscaping.com/design-consultation/
http://barrowslandscaping.com/full-service-maintenance/
</code></pre>
<p>I have tried moving the set(tag) into the for loop but that didnt change my results. </p>
| 0 |
2016-09-10T17:39:39Z
| 39,428,883 |
<p>First, you can't call <code>set()</code> in place, it's a conversion that returns a value.</p>
<pre><code>tag_set = set(tags)
</code></pre>
<p>Second, <code>set</code> doesn't necessarily understand the difference between Tag objects in BeautifulSoup. As far as it's concerned, two separate tags were found in the HTML so they're not unique and should both remain in the set. It has no idea that they have the same href value.</p>
<p>Instead, you should first extract the href attributes into a list and convert those to a set instead.</p>
<pre><code>tags = soup.find_all('a', {"href": True})
# extract the href values to a new array using a list comprehension
hrefs = [tag.get('href') for tag in tags]
href_set = set(hrefs)
for href in href_set:
print href
</code></pre>
<p>This can be further simplified using a set comprehension:</p>
<pre><code>tags = soup.find_all('a', {"href": True})
href_set = {tag.get('href') for tag in tags}
for href in href_set:
print href
</code></pre>
| 3 |
2016-09-10T17:45:06Z
|
[
"python",
"beautifulsoup",
"unique",
"href"
] |
Templates doesnot exist
| 39,428,853 |
<p>I just start to learn Django and I stuck with a issue that i Can't solve. Me and My friend want to create a Web site, our project structure is like that <code>Projet
--home
----migrations
----static
----templates
------home
--------home.html
--Projet
--manage.py
--db.sqlite3</code></p>
<p>I get this error :</p>
<pre><code>TemplateDoesNotExist at /
home/home.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.10.1
Exception Type: TemplateDoesNotExist
Exception Value:
home/home.html
Exception Location: C:\Python27\lib\site-packages\django\template\loader.py in get_template, line 25
Python Executable: C:\Python27\python.exe
Python Version: 2.7.12
Python Path:
['C:\\Python27\\Lib\\site-packages\\Jobin.git\\trunk',
'C:\\Python27\\lib\\site-packages\\virtualenvwrapper_win-1.2.1-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\virtualenv-15.0.3-py2.7.egg',
'C:\\Python27\\Lib\\site-packages\\Jobin.git\\trunk',
'C:\\Windows\\SYSTEM32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages']
Server time: Sat, 10 Sep 2016 13:19:12 -0400
</code></pre>
<p>here is my setting.py</p>
<pre><code> import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/templates/'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
</code></pre>
<p>I've tried everything on the field 'DIR' , like </p>
<pre><code>'DIRS': [BASE_DIR+"/templates", ]
'DIRS': [os.path.join(BASE_DIR, "templates")],
'DIRS': [os.path.join(BASE_DIR, 'templates')],
</code></pre>
<p>My views.py </p>
<pre><code> template_name = 'home/home.html'
def get(self, request):
return render(request, self.template_name)
</code></pre>
<p>still get this error , I don't know what to do anymore anyone has an idea ?</p>
| 0 |
2016-09-10T17:42:00Z
| 39,428,914 |
<p>Put your <code>templates</code> folder in the same level of <code>manage.py</code></p>
<pre><code>--home
----migrations
----static
--Projet
--templates
----home
------home.html
--manage.py
--db.sqlite3
</code></pre>
| 0 |
2016-09-10T17:48:32Z
|
[
"python",
"django"
] |
Python: Searching a file for a specific string and outputting the total string count
| 39,428,907 |
<p>Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.</p>
<pre><code>if user_search_method == 1:
with open("file.txt", 'r') as searchfile:
for word in searchfile:
word = word.lower()
total = 0
if user_search_value in word.split():
total += word.count(user_search_value)
print total
</code></pre>
<p>When I run this though I get a line-by-line count displayed and not a total sum. When I add up those lines they are always 1 count short of the actual too.</p>
| 2 |
2016-09-10T17:47:49Z
| 39,428,960 |
<p>You are printing the <code>total</code> in each iteration, you have to put it out of <code>for</code> loop. Also you can do this job more pythonic, using one generator expression:</p>
<pre><code>if user_search_method == 1:
with open("file.txt") as searchfile:
total = sum(line.lower().split().count(user_search_value) for line in searchfile)
print total
</code></pre>
| 2 |
2016-09-10T17:54:31Z
|
[
"python",
"full-text-search"
] |
Python: Searching a file for a specific string and outputting the total string count
| 39,428,907 |
<p>Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.</p>
<pre><code>if user_search_method == 1:
with open("file.txt", 'r') as searchfile:
for word in searchfile:
word = word.lower()
total = 0
if user_search_value in word.split():
total += word.count(user_search_value)
print total
</code></pre>
<p>When I run this though I get a line-by-line count displayed and not a total sum. When I add up those lines they are always 1 count short of the actual too.</p>
| 2 |
2016-09-10T17:47:49Z
| 39,428,977 |
<pre><code>if user_search_method == 1:
total = 0
with open('file.txt') as f:
for line in f:
total += line.casefold().split().count(user_search_value.casefold())
print(total)
</code></pre>
<p>This is probably what you wanted doing.</p>
| -1 |
2016-09-10T17:56:18Z
|
[
"python",
"full-text-search"
] |
Python: Searching a file for a specific string and outputting the total string count
| 39,428,907 |
<p>Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.</p>
<pre><code>if user_search_method == 1:
with open("file.txt", 'r') as searchfile:
for word in searchfile:
word = word.lower()
total = 0
if user_search_value in word.split():
total += word.count(user_search_value)
print total
</code></pre>
<p>When I run this though I get a line-by-line count displayed and not a total sum. When I add up those lines they are always 1 count short of the actual too.</p>
| 2 |
2016-09-10T17:47:49Z
| 39,429,046 |
<p>It feels like there might be something missing from your question, but I will try to get you to where it seems you want to go...</p>
<pre><code>user_search_value = 'test' # adding this for completeness of
# this example
if user_search_method == 1:
with open("file.txt", 'r') as searchfile:
total = 0
for word in searchfile:
words = word.lower().split() # breaking the words out, upfront, seems
# more efficient
if user_search_value in words:
total += words.count(user_search_value)
print total # the print total statement should be outside the for loop
</code></pre>
| 0 |
2016-09-10T18:04:03Z
|
[
"python",
"full-text-search"
] |
Python Selenium - Timeout Exception
| 39,428,939 |
<p><br></p>
<p>I'm using selenium to get the html for this site: <br>
<code>http://timesofindia.indiatimes.com/world/us</code><br></p>
<p>I'm using selenium because this site only gives you all the html if you scroll down. However when I run this code: <br></p>
<pre><code> # Open the Driver
driver = webdriver.Chrome(chromedriver)
#create a list to store the htmls
master_lst = []
#looping through the times of india urls
for url in urls[:3]:
#make the driver the the url
driver.get(url)
#this is to scroll down twelve time
for i in range(12):
# wait 5 seconds
time.sleep(5)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
html_source = driver.page_source
data = Beautifulsoup(html_source, 'lxml')
master_lst.append(data)
</code></pre>
<p>I get this error: <br>
<code>TimeoutException: Message: timeout: Timed out receiving message from renderer: -0.004</code></p>
<p>I've tried to change the sleep times and the times I scroll down to no avail. <br>
I've seen similar question in here but none that address this kind of problem. <br>Let me know what you all think!<br> Thanks!</p>
| 1 |
2016-09-10T17:51:51Z
| 39,429,180 |
<p>You may need to <em>adjust the script timeout</em>:</p>
<pre><code>driver.set_script_timeout(10)
</code></pre>
| 0 |
2016-09-10T18:17:40Z
|
[
"python",
"selenium-webdriver",
"web-scraping",
"timeout"
] |
Insert items to lists within a list
| 39,428,982 |
<p>I want to create a list of multiple lists, considering one list in particular.</p>
<p>For example: I want to add items from <code>a</code>, <code>b</code>, <code>c</code> into <code>x</code> list, and then append <code>x</code> to one main list.</p>
<pre><code>mainlist = []
x = [1, 2, 3] # items will be added hear.
a = ['a1', 'b1', 'c1']
b = ['a2', 'b2', 'c2']
c = ['a3', 'b3', 'c3']
</code></pre>
<p>First I need to create a list of lists for <code>x</code>:</p>
<pre><code>x = [[i] for i in x]
</code></pre>
<p>It returns:</p>
<pre><code>out[1]: [[1], [2], [3]]
</code></pre>
<p>Now, I want to add items to those lists:</p>
<pre><code>for item in range(0, len(x)):
x[item].insert(1, a[item])
out[2]: [[1, 'a1'], [2, 'b1'], [3, 'c1']]
</code></pre>
<p>And then append to <code>mainlist</code>:</p>
<pre><code>mainlist.append(x)
out[3]: [[[1, 'a1'], [2, 'b1'], [3, 'c1']]]
</code></pre>
<p>My question is how can I add items from <code>b</code> and <code>c</code> as I did with <code>a</code> list, in order to get this output:</p>
<pre><code>[[[1, 'a1'], [2, 'b1'], [3, 'c1']], [1, 'a2'], [2, 'b2'], [3, 'c2']], [1, 'a3'], [2, 'b3'], [3, 'c3']]]
</code></pre>
<p>I tried this, and I got the result, however i think this code could be improved.</p>
<pre><code>item1 = [[i] for i in x]
item2 = [[i] for i in x]
item3 = [[i] for i in x]
for i in range(0, len(item1)):
item1[i].insert(1, a[i])
for i in range(0, len(item2)):
item2[i].insert(1, b[i])
for i in range(0, len(item3)):
item3[i].insert(1, c[i])
mainlist.append(item1)
mainlist.append(item2)
mainlist.append(item3)
</code></pre>
<p>Any suggestions to improve it are appreacited. Thanks!</p>
| 2 |
2016-09-10T17:56:27Z
| 39,428,996 |
<p>Just <em>zip</em> <em>x</em> with each of the lists <em>a,b,c</em> using a <em>list comp</em>:</p>
<pre><code>x = [1, 2, 3] # items will be added hear.
a = ['a1', 'b1', 'c1']
b = ['a2', 'b2', 'c2']
c = ['a3', 'b3', 'c3']
main_list = [zip(x, y) for y in a,b,c]
</code></pre>
<p>That will give you:</p>
<pre><code>[[(1, 'a1'), (2, 'b1'), (3, 'c1')], [(1, 'a2'), (2, 'b2'), (3, 'c2')], [(1, 'a3'), (2, 'b3'), (3, 'c3')]]
</code></pre>
<p>If you really want sublists instead of tuples you can call <em>map</em> to map the tuples to lists:</p>
<pre><code> [list(map(list, zip(x, y))) for y in a,b,c]
</code></pre>
<p>If you were going to use a regular loop without the <em>zip</em> logic, you would do something like:</p>
<pre><code>l = []
for y in a, b, c:
l.append([[x[i], ele] for i, ele in enumerate(y)])
print(l)
</code></pre>
<p>Or a list comp version of the same:</p>
<pre><code> [[[x[i], ele] for i, ele in enumerate(y) ] for y in a, b, c]
</code></pre>
<p>Presuming all are the same length as <code>x</code>, each <code>i</code> is the index of the current element in <code>y</code> and we match it up with the corresponding element from <code>x</code> which is also exactly what zip is doing.</p>
| 3 |
2016-09-10T17:58:36Z
|
[
"python",
"list",
"python-3.x"
] |
All Permutations of a String in Python using Recursion
| 39,429,055 |
<p>I have this following Python code which returns a list of all the permutations of a given string using recursion. I tried my best to understand the working of the code but I am failed to do so. Can anyone please give me a breakdown of the code mentioned below?</p>
<pre><code>def permute(s):
out = []
# Base Case
if len(s) == 1:
out = [s]
else:
# For every letter in string
for i, let in enumerate(s):
for perm in permute(s[:i] + s[i+1:]):
# Add it to output
out += [let + perm]
return out
permute('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
</code></pre>
| -1 |
2016-09-10T18:04:58Z
| 39,429,161 |
<p>If the length of the string is one, there is only on permutation, so it returns only that string in this case.</p>
<p>If there are more letters, however, it goes through every letter in the string, they are each treated as the first letter in the permutations that get added in <code>out</code> in that iteration. Then it goes through every permutation of the rest of the string, and adds each of those to <code>out</code>, with <code>let</code> being the first letter.</p>
<p>But as <code>permute('aab')</code> wouldn't yield <code>['aab', 'aba', 'baa']</code>; each entry would be in the returned list twice.</p>
<p>To avoid that, use sets instead. So <code>out = set()</code>, <code>out = {s}</code>, and <code>out.add(let + perm)</code> instead of <code>out = []</code>, <code>out = [s]</code> and <code>out.append(let + perm)</code>.</p>
| 0 |
2016-09-10T18:15:41Z
|
[
"python",
"recursion",
"data-structures",
"permutation"
] |
Simulate impulsive signal and plotting
| 39,429,058 |
<p>im trying to plot an impulsive signal (Taken from a scientific paper), the equation of the impulsive signal is:
<a href="http://i.stack.imgur.com/Zxhig.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zxhig.png" alt="Impact formula"></a></p>
<p>where:</p>
<p>Ar= Amplitude of the impulses and equals 1.5</p>
<p>fm= fault characteristic freq. equals to 50 Hz</p>
<p>f=resonant frequency equals to 2000 Hz</p>
<p>F=sampling freq. equals to 10 kHz</p>
<p>betha= decay parameter equals 500}</p>
<p>total of 20.000 samples are simulated for the signal</p>
<p>the corresponding plot of the simulated signal should look like:
<a href="http://i.stack.imgur.com/fNmH2.png" rel="nofollow"><img src="http://i.stack.imgur.com/fNmH2.png" alt="enter image description here"></a></p>
<p>what i did is is:</p>
<pre><code>#Constants:
A_r=1.5
f=2000
r=-0.01
F=10**3
f_m=50
b=500
y_plt=[]
def y(k):
return A_r*np.sin(2*pi*f*(k-r*F/f_m)/F)*np.exp(-b*(k-r*F/f_m))/F
x=np.linspace(0,0.2,20000)
for i in x:
y_plt.append(y(i))
fig=plt.figure(1)
ax=plt.subplot(111)
ax.plot(x,y_plt)
</code></pre>
<p>getting the next plot:</p>
<p><a href="http://i.stack.imgur.com/3KuZk.png" rel="nofollow"><img src="http://i.stack.imgur.com/3KuZk.png" alt="enter image description here"></a>plt.show()</p>
<p>(Wich is not similar to the plot needed xP)
So my question is if everyone knows what im doing wrong, also the r parameter is not given.
Greet.</p>
<p>--EDIT--</p>
<pre><code>#Constants:
A_r=1.5
f=2000
r0=2
F=10**4
f_m=50
b=500
y_plt=[]
y_sum=[]
def y(k,r):
t=(k- r*F/f_m)/F
return A_r*np.sin(2*pi*f*t)*np.exp(-b*t)
for j in np.linspace(0,20000,20000,endpoint=False): #k
for i in np.linspace(0,r0,r0,endpoint=False): #r
y_sum.append(y(j,i))
pene=np.sum(y_sum)
y_plt.append(pene)
plt.figure(1)
plt.plot(np.linspace(0,20000,20000,endpoint=False),y_plt)
plt.show()
</code></pre>
<p>Now, what i cant figure out is how to make it an periodic signal. I think it has relation to the r factor, but if i change it doesnt change the plot at all.</p>
<p><a href="http://i.stack.imgur.com/jyj05.png" rel="nofollow"><img src="http://i.stack.imgur.com/jyj05.png" alt="Simple Impulse"></a></p>
| 0 |
2016-09-10T18:05:16Z
| 39,429,260 |
<h1>1.</h1>
<blockquote>
<p>F=sampling freq. equals to 10 kHz</p>
</blockquote>
<p>But you wrote</p>
<pre><code>F = 10 ** 3
</code></pre>
<p>In Python <code>**</code> mean exponentiation, so this is just 10<sup>3</sup> = 1000. That is, you have used F = 1 kHz in your code.</p>
<p>If you want to express 10.0 × 10<sup>3</sup>, use:</p>
<pre><code>F = 10e3
# ^
</code></pre>
<h1>2.</h1>
<pre><code>A_r * np.sin(2*pi*f*(k-r*F/f_m)/F) * np.exp(-b*(k-r*F/f_m))/F
# ^~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>Compared with your equation</p>
<blockquote>
<p><img src="http://i.stack.imgur.com/Zxhig.png" alt=""></p>
</blockquote>
<p>Note that the <code>/ F</code> part should be <em>inside</em> the <code>np.exp</code>, but you have put it outside.</p>
<p>There are so many parenthesis in the same line which mistakes can easily happen. You should better factor out the intermediate variable to make it easier to read:</p>
<pre><code>def y(k):
t = (k - r*F/f_m) / F
return A_r * np.sin(2*pi*f*t) * np.exp(-b*t)
</code></pre>
<h1>3.</h1>
<p>Note that your equation has a ∑<sub>r</sub> — it is a summation of waves over many <em>r</em>. Are you sure A_r is just a single value?</p>
| 2 |
2016-09-10T18:25:23Z
|
[
"python",
"numpy",
"signal-processing"
] |
python find image with path in file
| 39,429,089 |
<p>I'd like to find svgs or pngs withing a file. The images are in a attribue v="..."</p>
<p>A part of the file looks like this:</p>
<pre><code><symbol alpha="1" type="marker" name="0">
<layer pass="0" class="SvgMarker" locked="0">
<prop k="angle" v="0"/>
<prop k="fill" v="#000000"/>
<prop k="name" v="../Downloads/Inkscape_vectorisation_test.svg"/>
<prop k="offset" v="0,0"/>
<prop k="offset_unit" v="MM"/>
<prop k="outline" v="#000000"/>
<prop k="outline-width" v="1"/>
<prop k="outline_width_unit" v="MM"/>
<prop k="size" v="hello.png"/>
<prop k="size_unit" v="MM"/>
</layer>
</code></pre>
<p>I'd like to get a list like:</p>
<p>['../Downloads/Inkscape_vectorisation_test.svg','hello.png']</p>
<p>My python code:</p>
<pre><code>import re
projectFile = open("project.xml", "r")
regex = re.compile(r'(?<=v\=").+(\.svg|\.png)(?="/>)')
for line in projectFile:
result = regex.findall(line)
for filename in result:
print filename
</code></pre>
<p>I've tested my regex with <a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a> which work fine but in python console the result is just <code>.svg</code> it seems the capturing group <code>(\.svg|\.png)</code> is interpreted differently. What am I doing wrong?</p>
| 2 |
2016-09-10T18:07:48Z
| 39,429,432 |
<p>Is using regex a requirement? In case it isn't, an easier and cleaner approach would be to use <a href="http://lxml.de/" rel="nofollow">lxml</a>.</p>
<p>As it seems that the URIs you want appear in <code>prop</code> elements where <code>k="name"</code>, you could use <a href="http://lxml.de/xpathxslt.html" rel="nofollow">xpath</a> to do something like:</p>
<pre><code>from lxml import etree
f = etree.parse(projectFile)
root = f.getroot()
# This will give you a list with all prop elements that contain the URIs you want in the v attribute
elements = root.xpath("//prop[@k='name']")
</code></pre>
| 1 |
2016-09-10T18:46:42Z
|
[
"python",
"regex"
] |
python find image with path in file
| 39,429,089 |
<p>I'd like to find svgs or pngs withing a file. The images are in a attribue v="..."</p>
<p>A part of the file looks like this:</p>
<pre><code><symbol alpha="1" type="marker" name="0">
<layer pass="0" class="SvgMarker" locked="0">
<prop k="angle" v="0"/>
<prop k="fill" v="#000000"/>
<prop k="name" v="../Downloads/Inkscape_vectorisation_test.svg"/>
<prop k="offset" v="0,0"/>
<prop k="offset_unit" v="MM"/>
<prop k="outline" v="#000000"/>
<prop k="outline-width" v="1"/>
<prop k="outline_width_unit" v="MM"/>
<prop k="size" v="hello.png"/>
<prop k="size_unit" v="MM"/>
</layer>
</code></pre>
<p>I'd like to get a list like:</p>
<p>['../Downloads/Inkscape_vectorisation_test.svg','hello.png']</p>
<p>My python code:</p>
<pre><code>import re
projectFile = open("project.xml", "r")
regex = re.compile(r'(?<=v\=").+(\.svg|\.png)(?="/>)')
for line in projectFile:
result = regex.findall(line)
for filename in result:
print filename
</code></pre>
<p>I've tested my regex with <a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a> which work fine but in python console the result is just <code>.svg</code> it seems the capturing group <code>(\.svg|\.png)</code> is interpreted differently. What am I doing wrong?</p>
| 2 |
2016-09-10T18:07:48Z
| 39,429,916 |
<p>This fails because you are using <code>regex.findall</code> and you have a group in your regex: <code>(\.svg|\.png)</code>. If you change that to non-capturing group <code>(?:\.svg|\.png)</code>, then <code>findall</code> will find the whole match.</p>
<p>See the <a href="https://docs.python.org/2/library/re.html#re.RegexObject.findall" rel="nofollow">re.findall doc</a>, which says:</p>
<blockquote>
<p>If one or more groups are present in the pattern, return a list of
groups; this will be a list of tuples if the pattern has more than one
group.</p>
</blockquote>
<pre><code>>>> line = '<prop k="name" v="../Downloads/Inkscape_vectorisation_test.svg"/>'
>>>
>>> regex = re.compile(r'(?<=v\=").+(\.svg|\.png)(?="/>)')
>>> regex.findall(line)
['.svg']
>>>
>>> regex2 = re.compile(r'(?<=v\=").+(?:\.svg|\.png)(?="/>)')
>>> regex2.findall(line)
['../Downloads/Inkscape_vectorisation_test.svg']
</code></pre>
<p>Or you could use <code>re.search</code>, which will return a Match object and give you more control:</p>
<pre><code>>>> match = regex.search(line)
>>>
>>> match.group(0)
'../Downloads/Inkscape_vectorisation_test.svg'
>>>
>>> match.group(1)
'.svg'
</code></pre>
<p><strong>On the other hand...</strong></p>
<p>Regex is only a half-solution. If you use an XML parser instead, it will take case of text encoding, escape sequences, multiline tags, different quoting styles. So, if you want a more robust solution, don't use regexes here at all.</p>
| 0 |
2016-09-10T19:38:13Z
|
[
"python",
"regex"
] |
Django admin - Inline with choices from database
| 39,429,127 |
<p>I need some basic help with the django admin site. What I basically want to do is to be able to populate an inline with choices from the database. For example consider the following models:</p>
<pre><code>class Item(models.Model):
description = models.CharField(max_length=100)
class Category(models.Model):
name = models.CharField(max_length=100)
item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, blank=True)
</code></pre>
<p>And in <strong>admin.py</strong> I have the following setup:</p>
<pre><code>class CategoryAdminForm(forms.ModelForm):
name = forms.ChoiceField(choices = category_service.get_all_categories())
class CategoryInline(admin.TabularInline):
model = Category
form = CategoryAdminForm
class ItemAdmin(admin.ModelAdmin):
inlines = [CategoryInline]
admin.site.register(Item, ItemAdmin)
admin.site.register(Category)
</code></pre>
<p>What I want to be able to do is to insert categories into db, and when I want to insert an item, the categories inline to be populated with categories from the db. </p>
<p>With the current setup it is not working. It says that category is not an iterable object. What am I missing here?</p>
| 0 |
2016-09-10T18:11:45Z
| 39,429,178 |
<p>You should replace your <code>ChoiceField</code> with a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a>. They allow you to specify a queryset to populate the choices.</p>
<pre><code>category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="(Nothing)")
</code></pre>
| 0 |
2016-09-10T18:17:27Z
|
[
"python",
"django",
"django-admin"
] |
String information not saving on calendar array Python
| 39,429,155 |
<p>I created a script that would let me choose a month, then a day and save the name of a student.But when it loops, all the information previously entered is erased(when choosing another day in the same month). I really don't know how to save the info on the array.
Here's my code, i use Python 3.0:</p>
<pre><code>def chooseDate(dateM, day, month):
month = [['January'], ['February'],['March'],['April'],['May'], ['June'],['July'],['August'],['September'],['October'],['November'],['December']]
for i in range(0,len(month)):
if dateM in month[i]:
print("OK")
indexM = i
month[indexM] = [[] for _ in range(31)]
indexD = day - 1
month[indexM][indexD] = [[str(day), name]]
print(month[indexM])
while True:
choice = str(input("Y or N: "))
if choice == 'y':
dateM = str(input("Month: "))
day = int(input("Day :"))
name = str(input("Which Student? "))
chooseDate(dateM, day, name)
if choice == 'n':
print(month[indexM])
break
</code></pre>
| 0 |
2016-09-10T18:15:15Z
| 39,429,529 |
<p>Keeping each new student name could get unwieldy quickly using arrays. Instead of the list comprehension making a 2d array for each month, you could try creating a <a href="https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a> for each month instead using <code>day</code> as your key and a list of <code>name</code> as your values. </p>
<pre><code>january = {}
january[1] = ['Student1']
january[2] = ['Student2']
</code></pre>
<p>After a day already has a student in it, use <code>append</code> to add another name to the list:</p>
<pre><code>if 1 in january.keys():
january[1].append('Student3')
print(january[1])
# ['Student1', 'Student3']
</code></pre>
| 0 |
2016-09-10T18:57:08Z
|
[
"python",
"arrays",
"calendar",
"sublist"
] |
pandas.DataFrame: mappings a column of a list of keys to a column of the list of values
| 39,429,189 |
<p>Here is the input:</p>
<pre><code>df = pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
'A': ['A0', 'A1']})
lookup_df = pd.DataFrame({'val': ['V1', 'V2', 'V3']},
index = ['K0', 'K1', 'K2'])
</code></pre>
<p>After some "join" operation, I'd like a new column be added to <code>df</code>, which maps the key in <code>keys</code> in <code>df</code> to the <code>val</code> in <code>lookup_df</code>.</p>
<p>The output should be:</p>
<pre><code>pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
'val': [('V0', 'V1'), ('V1', 'V2')],
'A': ['A0', 'A1']})
</code></pre>
<p>One way I can think of is:</p>
<pre><code>df['val'] = df['keys'].apply(lambda ks:
list(map(lambda k: lookup_df.loc[k].val, ks)))
</code></pre>
<p>Is there other better ways to achieve this?</p>
| 2 |
2016-09-10T18:18:37Z
| 39,430,871 |
<p>you can do it this way:</p>
<pre><code>In [83]: df['val'] = df['keys'].str.join(',').str.split(',', expand=True).stack().map(lookup_df.val).unstack().apply(tuple)
In [84]: df
Out[84]:
A keys val
0 A0 (K0, K1) (V1, V2)
1 A1 (K1, K2) (V2, V3)
In [85]: lookup_df
Out[85]:
val
K0 V1
K1 V2
K2 V3
</code></pre>
<p>or a bit nicer, but slower method (thanks to <a href="http://stackoverflow.com/questions/39429189/pandas-dataframe-mappings-a-column-of-a-list-of-keys-to-a-column-of-the-list-of#comment66188610_39430871">@Boud</a>):</p>
<pre><code>In [5]: df['val'] = df['keys'].apply(pd.Series).stack().map(lookup_df.val).unstack().apply(tuple)
In [6]: df
Out[6]:
A keys val
0 A0 (K0, K1) (V1, V2)
1 A1 (K1, K2) (V2, V3)
</code></pre>
<p><strong>Timings against 10K rows DF:</strong></p>
<pre><code>In [18]: big = pd.concat([df] * 10**5, ignore_index=True)
In [19]: x = big.head(10**4)
In [20]: x.shape
Out[20]: (10000, 2)
In [21]: %timeit x['keys'].str.join(',').str.split(',', expand=True).stack().map(lookup_df.val).unstack().apply(tuple)
10 loops, best of 3: 75.1 ms per loop
In [22]: %timeit x['keys'].apply(pd.Series).stack().map(lookup_df.val).unstack().apply(tuple)
1 loop, best of 3: 5.5 s per loop
In [23]: %timeit x['keys'].apply(pd.Series).replace(lookup_df.val).apply(tuple)
1 loop, best of 3: 5.52 s per loop
In [24]: %%timeit
....: dk = pd.DataFrame(x['keys'].tolist()).applymap(lambda x: lookup_df.val[x])
....: x['val'] = zip(dk[0], dk[1])
....:
1 loop, best of 3: 1.66 s per loop
</code></pre>
<p><strong>Conclusion:</strong> the ugliest method is currently the fastest one</p>
| 2 |
2016-09-10T21:44:57Z
|
[
"python",
"pandas",
"dataframe"
] |
pandas.DataFrame: mappings a column of a list of keys to a column of the list of values
| 39,429,189 |
<p>Here is the input:</p>
<pre><code>df = pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
'A': ['A0', 'A1']})
lookup_df = pd.DataFrame({'val': ['V1', 'V2', 'V3']},
index = ['K0', 'K1', 'K2'])
</code></pre>
<p>After some "join" operation, I'd like a new column be added to <code>df</code>, which maps the key in <code>keys</code> in <code>df</code> to the <code>val</code> in <code>lookup_df</code>.</p>
<p>The output should be:</p>
<pre><code>pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
'val': [('V0', 'V1'), ('V1', 'V2')],
'A': ['A0', 'A1']})
</code></pre>
<p>One way I can think of is:</p>
<pre><code>df['val'] = df['keys'].apply(lambda ks:
list(map(lambda k: lookup_df.loc[k].val, ks)))
</code></pre>
<p>Is there other better ways to achieve this?</p>
| 2 |
2016-09-10T18:18:37Z
| 39,432,808 |
<p>Shorter and avoid string manipulation:</p>
<pre><code>df['val'] = df['keys'].apply(pd.Series).replace(lookup_df.val).apply(tuple)
</code></pre>
| 2 |
2016-09-11T04:19:06Z
|
[
"python",
"pandas",
"dataframe"
] |
pandas.DataFrame: mappings a column of a list of keys to a column of the list of values
| 39,429,189 |
<p>Here is the input:</p>
<pre><code>df = pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
'A': ['A0', 'A1']})
lookup_df = pd.DataFrame({'val': ['V1', 'V2', 'V3']},
index = ['K0', 'K1', 'K2'])
</code></pre>
<p>After some "join" operation, I'd like a new column be added to <code>df</code>, which maps the key in <code>keys</code> in <code>df</code> to the <code>val</code> in <code>lookup_df</code>.</p>
<p>The output should be:</p>
<pre><code>pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
'val': [('V0', 'V1'), ('V1', 'V2')],
'A': ['A0', 'A1']})
</code></pre>
<p>One way I can think of is:</p>
<pre><code>df['val'] = df['keys'].apply(lambda ks:
list(map(lambda k: lookup_df.loc[k].val, ks)))
</code></pre>
<p>Is there other better ways to achieve this?</p>
| 2 |
2016-09-10T18:18:37Z
| 39,433,605 |
<p>This isn't meant to be pretty.</p>
<pre><code>dk = pd.DataFrame(df['keys'].tolist()).applymap(lambda x: lookup_df.val[x])
df['val'] = zip(dk[0], dk[1])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/A5L1H.png" rel="nofollow"><img src="http://i.stack.imgur.com/A5L1H.png" alt="enter image description here"></a></p>
| 2 |
2016-09-11T06:55:44Z
|
[
"python",
"pandas",
"dataframe"
] |
Turtle Graphics Python, .mainloop()
| 39,429,227 |
<p>I am programming in Python and I have a few questions that I can't find the answer to anywhere(please read all questions as they build up to my last question):</p>
<p>1.What Does the .mainloop() really do?I read the all the answers in Stack Overflow, I also checked the documentations explanation.</p>
<p>2.Does the .mainloop() always have to be at the end of a turtle program?</p>
<p>3.Okay...I have used mainloop() before. My question is, if I have the f.f.g code:</p>
<pre><code>import turtle
screen = turtle.Screen()
alex = turtle.Turtle()
tess = turtle.Turtle()
def yes(x, y):
alex.onclick(yes)
print("Hello World")
tess.onclick(yes)
turtle.mainloop()
</code></pre>
<p>Why does alex get an action event when the function yes() is run, I know because the function is called, but what is actually happening? I mean the statement turtle.mainloop() is run before tess is clicked, and tess's action event is waited for in the event loop, so how does alex's event get in the event loop since its statement is run after turtle.mainloop() is run.</p>
| 0 |
2016-09-10T18:22:56Z
| 39,429,408 |
<p>So mainloop() is an infinite loop that basically blocks the execution of your code at a certain point. You call it once (and only once). </p>
<p>so lets say:</p>
<pre><code>while true:
circle.draw()
sumden.mainloop()
print "circle is being drawn"
time.sleep(0.1)
</code></pre>
<p>You will never see the output and print statement because there is no loop.</p>
| 0 |
2016-09-10T18:43:12Z
|
[
"python",
"user-interface",
"events",
"turtle-graphics",
"event-loop"
] |
Python Multiprocessing, Pool map - cancel all running processes if one, returns the desired result
| 39,429,243 |
<p>given the following Python code:</p>
<pre><code>import multiprocessing
def unique(somelist):
return len(set(somelist)) == len(somelist)
if __name__ == '__main__':
somelist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,2], [1,2,3,4,5], [1,2,3,4,5,6,7,8,9,1], [0,1,5,1]]
pool = multiprocessing.Pool()
reslist = pool.map(unique, somelist)
pool.close()
pool.join()
print "Done!"
print reslist
</code></pre>
<p>Now imagine, that the lists with integers in this toy example are extremely long, and what I'd like to achieve here is the following: if one of the lists in somelist returns True, kill all running processes. </p>
<p>This leads to two questions (and probably more which I haven't come up with):</p>
<ul>
<li><p>How can I 'read'/'listen' from a finished process the result, while other processes are running? If e.g. a process is dealing with [1,2,3,4,5] from somelist, and is finished before all other processes, how can I read out the result from that process in this very moment?</p></li>
<li><p>Given the case that it is possible to 'read' out the result of a finished process while other are running: how can I use this result as a condition to terminate all other running processes?</p></li>
</ul>
<p>e.g. if one process has finished and returned True, how I can use this as a condition to terminate all other (still) running processes?</p>
<p>Thank you in advance for any hints
Dan</p>
| 3 |
2016-09-10T18:24:14Z
| 39,429,590 |
<p>Use <code>pool.imap_unordered</code> to view the results in any order they come up.</p>
<pre><code>reslist = pool.imap_unordered(unique, somelist)
pool.close()
for res in reslist:
if res: # or set other condition here
pool.terminate()
break
pool.join()
</code></pre>
<p>You can iterate over an <code>imap</code> reslist in your main process while the pool processes are still generating results.</p>
| 4 |
2016-09-10T19:04:08Z
|
[
"python",
"dictionary",
"multiprocessing",
"pool"
] |
Python Multiprocessing, Pool map - cancel all running processes if one, returns the desired result
| 39,429,243 |
<p>given the following Python code:</p>
<pre><code>import multiprocessing
def unique(somelist):
return len(set(somelist)) == len(somelist)
if __name__ == '__main__':
somelist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,2], [1,2,3,4,5], [1,2,3,4,5,6,7,8,9,1], [0,1,5,1]]
pool = multiprocessing.Pool()
reslist = pool.map(unique, somelist)
pool.close()
pool.join()
print "Done!"
print reslist
</code></pre>
<p>Now imagine, that the lists with integers in this toy example are extremely long, and what I'd like to achieve here is the following: if one of the lists in somelist returns True, kill all running processes. </p>
<p>This leads to two questions (and probably more which I haven't come up with):</p>
<ul>
<li><p>How can I 'read'/'listen' from a finished process the result, while other processes are running? If e.g. a process is dealing with [1,2,3,4,5] from somelist, and is finished before all other processes, how can I read out the result from that process in this very moment?</p></li>
<li><p>Given the case that it is possible to 'read' out the result of a finished process while other are running: how can I use this result as a condition to terminate all other running processes?</p></li>
</ul>
<p>e.g. if one process has finished and returned True, how I can use this as a condition to terminate all other (still) running processes?</p>
<p>Thank you in advance for any hints
Dan</p>
| 3 |
2016-09-10T18:24:14Z
| 39,429,604 |
<p>Without fancy IPC (inter-process communication) tricks, easiest is to use a <code>Pool</code> method with a callback function instead. The callback runs in the main program (in a thread created by <code>multiprocessing</code>), and consumes each result as it becomes available. When the callback sees a result you like, it can terminate the <code>Pool</code>. For example,</p>
<pre><code>import multiprocessing as mp
def worker(i):
from time import sleep
sleep(i)
return i, (i == 5)
def callback(t):
i, quit = t
result[i] = quit
if quit:
pool.terminate()
if __name__ == "__main__":
N = 50
pool = mp.Pool()
result = [None] * N
for i in range(N):
pool.apply_async(func=worker, args=(i,), callback=callback)
pool.close()
pool.join()
print(result)
</code></pre>
<p>Which will almost certainly display the following (OS scheduling vagaries <em>may</em> allow another input or two to be consumed):</p>
<pre><code>[False, False, False, False, False, True, None, None, None, None,
None, None, None, None, None, None, None, None, None, None,
None, None, None, None, None, None, None, None, None, None,
None, None, None, None, None, None, None, None, None, None,
None, None, None, None, None, None, None, None, None, None]
</code></pre>
| 1 |
2016-09-10T19:05:26Z
|
[
"python",
"dictionary",
"multiprocessing",
"pool"
] |
Statsmodels fit distribution among 0 and 1
| 39,429,297 |
<p>I am trying to fit a beta distribution that should be defined between 0 and 1 on a data set that only has samples in a subrange. My problem is that using the <code>fit()</code> function will cause the fitted PDF to be defined only between my smallest and largest values.
For instance, if my dataset has samples between 0.2 and 0.3, what I get is a PDF defined between 0.2 and 0.3, instead of between 0 and 1, as it should be. The code I am using is:</p>
<pre><code>ps1 = beta.fit(selected, loc=0, scale=1)
</code></pre>
<p>Am I missing something?
Thanks in advance!</p>
| 2 |
2016-09-10T18:29:37Z
| 39,435,822 |
<p>I came up with a partial solution that does the trick for me: I replicate my samples (for the datasets that are too small) and add dummy samples at 0 and 1. Although that increases the fit error, it is low enough for my purpose.
Also, I asked in Google groups and got <a href="https://groups.google.com/d/msg/pystatsmodels/p3LMyERf6C4/8eE6J08-AgAJ" rel="nofollow">this answer</a> that works fine, but its giving me some errors occasionally. I hope this helps anyone with that problem. </p>
| 0 |
2016-09-11T11:58:12Z
|
[
"python",
"numpy",
"statistics",
"statsmodels"
] |
Python regular expression. Find a sentence in a sentence
| 39,429,345 |
<p>I'm trying to find an expression "K others" in a sentence "Chris and 34K others"</p>
<p>I tried with regular expression, but it doesn't work :(</p>
<pre><code>import re
value = "Chris and 34K others"
m = re.search("(.K.others.)", value)
if m:
print "it is true"
else:
print "it is not"
</code></pre>
| 1 |
2016-09-10T18:34:40Z
| 39,429,374 |
<p>You should use <code>search</code> rather than <code>match</code> unless you expect your regular expression to match at the beginning. The help string for <code>re.match</code> mentions that the pattern is applied at the start of the string.</p>
| 2 |
2016-09-10T18:38:57Z
|
[
"python",
"regex",
"python-2.7"
] |
Python regular expression. Find a sentence in a sentence
| 39,429,345 |
<p>I'm trying to find an expression "K others" in a sentence "Chris and 34K others"</p>
<p>I tried with regular expression, but it doesn't work :(</p>
<pre><code>import re
value = "Chris and 34K others"
m = re.search("(.K.others.)", value)
if m:
print "it is true"
else:
print "it is not"
</code></pre>
| 1 |
2016-09-10T18:34:40Z
| 39,429,396 |
<p>If you want to match something <em>within</em> the string, use <code>re.search</code>. <code>re.match</code> starts at the beginning, Also, change your RegEx to: <code>(K.others)</code>, the last <code>.</code> ruins the RegEx as there is nothing after, and the first <code>.</code> matches any character before. I removed those:</p>
<pre><code>>>> bool(re.search("(K.others)", "Chris and 34K others"))
True
</code></pre>
<p>The RegEx <code>(K.others)</code> matches:</p>
<pre><code>Chris and 34K others
^^^^^^^^
</code></pre>
<p>Opposed to <code>(.K.others.)</code>, which matches nothing. You can use <code>(.K.others)</code> as well, which matches the character before:</p>
<pre><code>Chris and 34K others
^^^^^^^^^
</code></pre>
<p>Also, you can use <code>\s</code> to escape space and match only whitespace characters: <code>(K\sothers)</code>. This will literally match K, a whitespace character, and others.</p>
<p>Now, if you want to match all preceding and all following, try: <code>(.+)?(K\sothers)(\s.+)?</code>. Here's a link to <a href="https://repl.it/D2mD/1" rel="nofollow">repl.it</a>. You can get the number with <a href="https://repl.it/D2mD/2" rel="nofollow">this</a>.</p>
| 2 |
2016-09-10T18:41:45Z
|
[
"python",
"regex",
"python-2.7"
] |
Python regular expression. Find a sentence in a sentence
| 39,429,345 |
<p>I'm trying to find an expression "K others" in a sentence "Chris and 34K others"</p>
<p>I tried with regular expression, but it doesn't work :(</p>
<pre><code>import re
value = "Chris and 34K others"
m = re.search("(.K.others.)", value)
if m:
print "it is true"
else:
print "it is not"
</code></pre>
| 1 |
2016-09-10T18:34:40Z
| 39,429,525 |
<p>Guessing that you're web-page scraping "<em>you and 34k others liked this on Facebook</em>", and you're wrapping "K others" in a capture group, I'll jump straight to how to get the number:</p>
<pre><code>import re
value = "Chris and 34K others blah blah"
# regex describes
# a leading space, one or more characters (to catch punctuation)
# , and optional space, trailing 'K others' in any capitalisation
m = re.search("\s(\w+?)\s*K others", value, re.IGNORECASE)
if m:
captured_values = m.groups()
print "Number of others:", captured_values[0], "K"
else:
print "it is not"
</code></pre>
<p><a href="https://repl.it/D2ke/4" rel="nofollow">Try this code on repl.it</a></p>
<p>This should also cover uppercase/lowercase K, numbers with commas (1,100K people), spaces between the number and the K, and work if there's text after 'others' or if there isn't.</p>
| 3 |
2016-09-10T18:56:45Z
|
[
"python",
"regex",
"python-2.7"
] |
Python basic spanning tree algorithm
| 39,429,376 |
<p>I cannot figure out how to implement a basic spanning tree in Python; an un-weighted spanning tree.</p>
<p>I've learned how to implement an adjacency list:</p>
<pre><code>for edge in adj1:
x, y = edge[int(0)], edge[int(1)]
if x not in adj2: adj2[x] = set()
if y not in adj2: adj2[y] = set()
adj2[x].add(y)
adj2[y].add(x)
print(adj2)
</code></pre>
<p>But I don't know how to implement "finding nearest unconnected vertex".</p>
| 0 |
2016-09-10T18:39:00Z
| 39,430,850 |
<p>You don't say which spanning-tree algorithm you need to use. DFS? BFS? Prim's with constant weights? Kruskal's with constant weights? Also, what do you mean by "nearest" unconnected vertex, since the graph is unweighted? All the vertices adjacent to a given vertex v will be at the same distance from v. Finally, are you supposed to start at an arbitrary vertex? at 0? at a user-specified vertex? I'll assume 0 and try to push you in the right direction.</p>
<p>You need to have some way to represent which vertices are already in the spanning tree, so that you don't re-add them to the tree along another edge. That would form a cycle, which can't happen in a tree. Since you definitely need a way to represent the tree, like the [ [1], [0,2,3], [1], [1] ] example you gave, one way to start things out is with [ [], [], [], [] ].</p>
<p>You also need to make sure that you eventually connect everything to a single tree, rather than, for example, finishing with two trees that, taken together, cover all the vertices, but that aren't connected to each other via any edge. There are two ways to do this: (1) Start with a single vertex and grow the tree incrementally until it covers all the nodes, so that you never have more than one tree. (2) Add edges in some other way, keeping track of the connected components, so that you can make sure eventually to connect all the components. Unless you know you need (2), I suggest sticking with (1).</p>
<p>Getting around to your specific question: If you have the input inputgraph = [[1,2],[0,2,3],[0,1],[1]], and you start with currtree = [ [], [], [], [] ], and you start at vertex 0, then you look at inputgraph[0], discover that 0 is adjacent to 1 and 2, and pick either (0,1) or (0,2) to be an edge in the tree. Let's say the algorithm you are using tells you to pick (0,1). Then you update currtree to be [ [1], [0], [], [] ]. Your algorithm then directs you either to pick another edge at 0, which in this inputgraph would have to be (0,2), or directs you to pick an edge at 1, which could be (1,2) or (1,3). Note that your algorithm has to keep track of the fact that (1,0) is not an acceptable choice at 1, since (0,1) is already in the tree.</p>
<p>You need to use one of the algorithms I listed above, or some other spanning-tree algorithm, to be systematic about which vertex to examine next, and which edge to pick next.</p>
<p>I hope that gave you an idea of the issues you have to consider and how you can map an abstract algorithm description to running code. I leave learning the algorithm to you!</p>
| 0 |
2016-09-10T21:41:58Z
|
[
"python",
"spanning-tree"
] |
Loop to print name, removing one character at a time
| 39,429,397 |
<p>I'm having a little trouble creating a program which prints out the name of the user downwards that always removes the first character each row then when it's at the last letter go up again.</p>
<p>This is what i have so far: </p>
<pre><code>name = input("Put in a name: ")
name_length = len(name)
for counter in range(name_length,0, -1):
print(counter)
</code></pre>
<p>Below Is what it is supposed to end like</p>
<p><a href="http://i.stack.imgur.com/5rPWa.png" rel="nofollow"><img src="http://i.stack.imgur.com/5rPWa.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T18:41:46Z
| 39,429,486 |
<p>I think it will work:</p>
<pre><code>name = input("Put in a name: ")
for i in range(len(name)): # for 1st half
print(name[i:])
for i in range(len(name)-2,-1,-1): # for 2nd half
print(name[i:])
</code></pre>
<p><strong>Input:</strong></p>
<pre><code>stack
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>stack
tack
ack
ck
k
ck
ack
tack
stack
</code></pre>
<p>I Split output into two halfs:</p>
<p>1st half:</p>
<pre><code>stack
tack
ack
ck
k
</code></pre>
<p>Which will be achieved by 1st <code>for</code> loop using Slice (check to understand more <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">Explain Python's slice notation</a>)</p>
<p>And 2nd half:</p>
<pre><code>ck
ack
tack
stack
</code></pre>
<p><strong>Note:</strong> You can print single character in this example <code>k</code> in 1st <code>for</code> loop like i do or in 2nd <code>for</code> loop, it up to you.</p>
<p>Hope this helps.</p>
<p>Although I think you should use solution suggested by @Andrew it's pretty cool if you <code>print a</code> in his solution you get the sequence <code>[0, 1, 2, 3, 4, 3, 2, 1, 0]</code> for slice the string so can be done in single <code>for</code> loop</p>
| 1 |
2016-09-10T18:52:33Z
|
[
"python",
"for-loop"
] |
Loop to print name, removing one character at a time
| 39,429,397 |
<p>I'm having a little trouble creating a program which prints out the name of the user downwards that always removes the first character each row then when it's at the last letter go up again.</p>
<p>This is what i have so far: </p>
<pre><code>name = input("Put in a name: ")
name_length = len(name)
for counter in range(name_length,0, -1):
print(counter)
</code></pre>
<p>Below Is what it is supposed to end like</p>
<p><a href="http://i.stack.imgur.com/5rPWa.png" rel="nofollow"><img src="http://i.stack.imgur.com/5rPWa.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T18:41:46Z
| 39,429,568 |
<p>This is an approach that just uses a single loop and slicing to achieve the same end. It creates a list of the indices at which the slice should begin, and then steps through that list printing as it goes.</p>
<pre><code>name = "Bilbo"
a = range(len(name))
a = a[:-1] + a[::-1]
for idx in a:
print name[idx:]
</code></pre>
| 0 |
2016-09-10T19:02:14Z
|
[
"python",
"for-loop"
] |
Loop to print name, removing one character at a time
| 39,429,397 |
<p>I'm having a little trouble creating a program which prints out the name of the user downwards that always removes the first character each row then when it's at the last letter go up again.</p>
<p>This is what i have so far: </p>
<pre><code>name = input("Put in a name: ")
name_length = len(name)
for counter in range(name_length,0, -1):
print(counter)
</code></pre>
<p>Below Is what it is supposed to end like</p>
<p><a href="http://i.stack.imgur.com/5rPWa.png" rel="nofollow"><img src="http://i.stack.imgur.com/5rPWa.png" alt="enter image description here"></a></p>
| 1 |
2016-09-10T18:41:46Z
| 39,429,572 |
<p>Recursive answer</p>
<p>Essentially, print the same string twice, but in-between call the function again, but with the first character removed. When the start index is greater than the length of the string - 1, then you have one character left. </p>
<pre><code>def printer(str, start=0):
s = str[start:]
if len(str) - 1 <= start:
print s
return
print s
printer(str, start + 1)
print s
</code></pre>
<p>Output </p>
<pre><code>Put in a name: cricket_007
cricket_007
ricket_007
icket_007
cket_007
ket_007
et_007
t_007
_007
007
07
7
07
007
_007
t_007
et_007
ket_007
cket_007
icket_007
ricket_007
cricket_007
</code></pre>
| 0 |
2016-09-10T19:02:44Z
|
[
"python",
"for-loop"
] |
How to debug "IndexError: string index out of range" in Python?
| 39,429,442 |
<p>I am trying to solve Ex. 9.6 Think Python 3.</p>
<blockquote>
<p>Question: Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there?</p>
</blockquote>
<p>What I have written:</p>
<pre><code>fin= open('words.txt')
for line in fin:
line=fin.readline()
word=line.strip()
c=0
index=0
for letter in word:
if ord(letter)<ord(word[index+1]):
c=c+1
index=index+1
if c==len(word):
print(word)
</code></pre>
<p>My approach is to convert letters to numeric value and match them with the next letter in the word by increasing the index by 1 each time loop ends and count each time. If count comes to be equal to the length of word that means all the times the previous letter was lesser in value than next. So print the word. </p>
<p>Error:</p>
<pre><code>Traceback (most recent call last): File "C:\Users\KARAN\Desktop\Python\Programs\practice.py", line 8, in <module> if ord(letter)<ord(word[index+1]): IndexError: string index out of range
</code></pre>
<p>I am getting 'IndexError' but I don't think index that is 0+1=1 should be out of range? I tried to search it up but couldn't get my answer.</p>
| -1 |
2016-09-10T18:47:15Z
| 39,458,632 |
<p><em>(Posted on behalf of the OP)</em>.</p>
<p>Final solution:</p>
<pre><code>fin= open('words.txt')
for line in fin:
line=fin.readline()
word=line.strip()
c=0
index=0
while index!=(len(word)-1):
i=(word[index])
j=(word[index+1])
index=index+1
if ord(j)>=ord(i):
c=c+1
if c==(len(word)-1):
print(word)
</code></pre>
| 1 |
2016-09-12T20:53:14Z
|
[
"python",
"python-3.x"
] |
Loading construct library causes error - no viable alternative
| 39,429,472 |
<p>When I try to load the construct library v 2.5.4, in python 2.5.4 it is causing this error. Any idea how to resolve? Is there something I can adapt/edit in the library to fix this</p>
<pre><code>SyntaxError: ('no viable alternative at input \'""\'', ('/Users/blahblah/Documents/lib/java-classes/lib/Lib/construct/lib/binary.py', 66, 16, ' return
b"".join(_char_to_bin[int(ch)] for ch in data)\n'))
</code></pre>
| -1 |
2016-09-10T18:50:55Z
| 39,430,076 |
<p>You are running in some environment that suppresses a proper traceback printing and instead gives you the raw representation of the exception object. It says that the error is in line 66, column 16 and then gives the line.</p>
<pre><code> return b"".join(_char_to_bin[int(ch)] for ch in data)
</code></pre>
<p>The error, when running in 2.5, is <code>b"</code>. The <code>b</code> string prefix is not valid until 2.7 (or perhaps 2.6), and even then, it has no effect. It is only recognized to aid compatibility with 3.x. The use of the prefix indicates that the library is not intended to run with 2.5. It might or might not be intended to work with 2.7. You need to either find a version (likely older) that works with 2.5 or use a newer version of python.</p>
<p>You could fix this error by removing the <code>b</code>, but you will likely run into others.</p>
| 0 |
2016-09-10T19:58:13Z
|
[
"python",
"python-module",
"construct"
] |
How to specify "nullable" return type with type hints
| 39,429,526 |
<p>Suppose I have a function:</p>
<pre><code>def get_some_date(some_argument: int=None) -> %datetime_or_None%:
if some_argument is not None and some_argument == 1:
return datetime.utcnow()
else:
return None
</code></pre>
<p>How do I specify the return type for something that can be <code>None</code>?</p>
| 6 |
2016-09-10T18:56:49Z
| 39,429,578 |
<p>Since your return type can be <code>datetime</code> (as returned from <code>datetime.utcnow()</code>) or <code>None</code> you should use <code>Optional[datetime]</code>:</p>
<pre><code>from typing import Optional
def get_some_date(some_argument: int=None) -> Optional[datetime]:
# as defined
</code></pre>
<p>From the documentation, <a href="https://docs.python.org/3/library/typing.html#typing.Optional" rel="nofollow"><code>Optional</code></a> is shorthand for:</p>
<blockquote>
<p><code>Optional[X]</code> is equivalent to <code>Union[X, None]</code>.</p>
</blockquote>
<p>where <code>Union[X, Y]</code> means a value of type <code>X</code> or <code>Y</code>.</p>
<hr>
<p>If you want to be explicit due to concerns that others might stumble on <code>Optional</code> and not realize it's meaning, you could always use <code>Union</code>:</p>
<pre><code>from typing import Union
def get_some_date(some_argument: int=None) -> Union[datetime, None]:
</code></pre>
<p><sub>As pointed out in the comments by @Michael0x2a <code>Union[T, None]</code> is tranformed to <code>Union[T, type(None)]</code> so no need to use <code>type</code> here.</sub></p>
<p>Visually these might differ but programmatically in both cases the result is <em>exactly the same</em>; <code>Union[datetime.datetime, NoneType]</code> will be the type stored in <code>get_some_date.__annotations__</code>:</p>
<pre><code>{'return': typing.Union[datetime.datetime, NoneType], 'some_argument': int}
</code></pre>
| 10 |
2016-09-10T19:03:06Z
|
[
"python",
"python-3.x",
"python-3.5",
"type-hinting"
] |
TypeError: int() argument must be a string, a bytes-like object or a number, not datetime.datetime
| 39,429,579 |
<p>TypeError: int() argument must be a string, a bytes-like object or a number, not datetime.datetime</p>
<p>Okay.. I deleted complete database. EVEN Restarted My PC.</p>
<p>Models.py</p>
<pre><code>from django.db import models
from django.core.urlresolvers import reverse
class Register(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
confirm_password = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
position = models.CharField(max_length=50)
def get_absolute_url(self):
return reverse('user:register', kwargs={'pk': self.pk})
class Login(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
def __str__(self):
login = {'username': self.username, 'password': self.password}
return login
</code></pre>
<p>I am not setting primary key nor foreign key but still it's bugging me.
I searched and tried other options but can't still figure out problem and solution.
makemigrations doesn't give an error but migrate command gives.</p>
<p>Full Stack :</p>
<pre><code>D:\Python Projects\Project_Management>python manage.py makemigrations user
No changes detected in app 'user'
D:\Python Projects\Project_Management>python manage.py migrate
Operations to perform:
Apply all migrations: contenttypes, admin, sessions, auth, user
Running migrations:
Rendering model states... DONE
Applying user.0003_auto_20160911_0013...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 349, in execute_from_command_line
utility.execute()
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 290, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 339, in execute
output = self.handle(*args, **options)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", line 177, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\operations\fields.py", line 62, in database_forwards
field,
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\schema.py", line 382, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\schema.py", line 145, in column_sql
default_value = self.effective_default(field)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\schema.py", line 210, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related.py", line 904, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", line 736, in get_db_prep_save
prepared=False)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", line 979, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Vic\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", line 987, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'
</code></pre>
<p>settings.py</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'Project',
'USER': 'postgres',
'PASSWORD': 'vikram',
'HOST': '127.0.0.1',
'PORT': '5433',
}
}
</code></pre>
<p>manage.py</p>
<pre><code>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project_Management.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
</code></pre>
<p>0003_auto_20160911_0013.py</p>
<pre><code># -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-10 18:43
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('user', '0002_auto_20160910_1740'),
]
operations = [
migrations.RemoveField(
model_name='login',
name='id',
),
migrations.RemoveField(
model_name='register',
name='id',
),
migrations.AddField(
model_name='login',
name='user_id',
field=models.ForeignKey(default=datetime.datetime(2016, 9, 10, 18, 43, 28, 263522, tzinfo=utc), on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='login_id', serialize=False, to='user.Register'),
preserve_default=False,
),
migrations.AddField(
model_name='register',
name='user_id',
field=models.IntegerField(default=1, primary_key=True, serialize=False),
preserve_default=False,
),
migrations.AlterField(
model_name='login',
name='password',
field=models.CharField(max_length=50),
),
migrations.AlterField(
model_name='login',
name='username',
field=models.CharField(max_length=50),
),
migrations.AlterField(
model_name='register',
name='username',
field=models.CharField(max_length=50),
),
]
</code></pre>
<p>I created whole new database..
Please help..
Thanks in advance.</p>
| -2 |
2016-09-10T19:03:08Z
| 39,430,715 |
<p>You are defining a <strong>default</strong> value of a <code>ForeignKey</code> to be a <code>datetime</code> object. A <code>ForeignKey</code> should be an <code>Integer</code> representing the ID of some other table.</p>
<p>The problem is in this piece of code</p>
<pre><code>migrations.AddField(
model_name='login',
name='user_id',
field=models.ForeignKey(default=datetime.datetime(2016, 9, 10, 18, 43, 28, 263522, tzinfo=utc), on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='login_id', serialize=False, to='user.Register'),
preserve_default=False,
),
</code></pre>
<p>More specifically, </p>
<pre><code>field=models.ForeignKey(default=datetime.datetime(2016, 9, 10, 18, 43, 28, 263522, tzinfo=utc), on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='login_id', serialize=False, to='user.Register')
</code></pre>
<p>change the <code>default</code> argument to be the value of the <code>ID</code> of the row represented by that <code>datetime</code> you referenced.</p>
| 2 |
2016-09-10T21:27:13Z
|
[
"python",
"django",
"datetime",
"typeerror"
] |
Using stack in python gives NoneType error
| 39,429,582 |
<p>I am trying to push an item on to stack in Python. Below is the code for trying to push the item :</p>
<pre><code>class Search
def generalGraphSearch(problem,fringe):
closed=set()
#If no nodes
if problem.isGoalState(problem.getStartState()):
return problem.getStartState()
#Create object of Stack class
stackOb = util.Stack()
"""Push the starting node into the stack. The parameter is the state"""
stackOb.push(problem.getStartState())
print stackOb.push(problem.getStartState())
The stack implementation is as below :
class Stack:
"A container with a last-in-first-out (LIFO) queuing policy."
def __init__(self):
self.list = []
def push(self,item):
"Push 'item' onto the stack"
self.list.append(item)
</code></pre>
<p>The print statement in the Search class gives type as none</p>
<p>Any suggestions how to overcome this problem ?
Thanks</p>
| -2 |
2016-09-10T19:03:22Z
| 39,429,648 |
<p>You are trying to print the result of <code>push()</code> method call, but the method <em>does not return anything</em> - that's why you see <code>None</code> printed.</p>
<p>Instead, you meant to either explore the contents of the <code>list</code> attribute:</p>
<pre><code>stackOb.push(problem.getStartState())
print(stackOb.list)
</code></pre>
<p>or, implement and use the <code>pop()</code> method to get the element from the top of the stack:</p>
<pre><code>class Stack:
# ...
def pop(self):
return self.list.pop()
</code></pre>
<p>You can also have a <code>peek()</code> method that would simply return the top element from the stack without removing it:</p>
<pre><code>class Stack:
# ...
def peek(self):
return self.list[-1]
</code></pre>
| 0 |
2016-09-10T19:09:30Z
|
[
"python",
"python-2.7",
"stack"
] |
converting chr() / ord() with multi characters
| 39,429,601 |
<p>beginner programming in python (3.4)<br>
is it possible to pass multiple values inside chr() and ord()?
what i tried is the following:</p>
<pre><code>userInput = input('Please write your input: ')
> Hello
result = ord(userInput) #here is the error because i put multiple values instead of just one
print(result)
</code></pre>
<p>this is the output i am looking for: <code>72 101 108 108 111</code> (hello) but instead i get an error telling me i can only pass 1 character/value inside chr() / ord()
is this possible? if not can you provide me in the right direction? thank you</p>
| 1 |
2016-09-10T19:05:20Z
| 39,429,634 |
<p>You can use <code>map</code> to apply the function to each element:</p>
<pre><code>>>> for n in map(ord, 'Hello'):
... print(n, end=' ')
...
72 101 108 108 111
</code></pre>
| 0 |
2016-09-10T19:08:34Z
|
[
"python"
] |
converting chr() / ord() with multi characters
| 39,429,601 |
<p>beginner programming in python (3.4)<br>
is it possible to pass multiple values inside chr() and ord()?
what i tried is the following:</p>
<pre><code>userInput = input('Please write your input: ')
> Hello
result = ord(userInput) #here is the error because i put multiple values instead of just one
print(result)
</code></pre>
<p>this is the output i am looking for: <code>72 101 108 108 111</code> (hello) but instead i get an error telling me i can only pass 1 character/value inside chr() / ord()
is this possible? if not can you provide me in the right direction? thank you</p>
| 1 |
2016-09-10T19:05:20Z
| 39,429,635 |
<p>You can use <code>map</code> function, in order to apply the <code>ord</code> on all characters separately:</p>
<pre><code>In [18]: list(map(ord, 'example'))
Out[18]: [101, 120, 97, 109, 112, 108, 101]
</code></pre>
<p>Or use <code>bytearray</code> directly on string:</p>
<pre><code>In [23]: list(bytearray('example', 'utf8'))
Out[23]: [101, 120, 97, 109, 112, 108, 101]
</code></pre>
<p>But note that when you are dealing with unicodes <code>bytearray</code> doesn't return a number like <code>ord</code> but an array of bytes values based on the passed encoding (a number between 0 and 256):</p>
<pre><code>In [27]: list(bytearray('â¬', 'utf8'))
Out[27]: [226, 130, 172]
In [25]: ord('â¬')
Out[25]: 8364
</code></pre>
| 0 |
2016-09-10T19:08:34Z
|
[
"python"
] |
converting chr() / ord() with multi characters
| 39,429,601 |
<p>beginner programming in python (3.4)<br>
is it possible to pass multiple values inside chr() and ord()?
what i tried is the following:</p>
<pre><code>userInput = input('Please write your input: ')
> Hello
result = ord(userInput) #here is the error because i put multiple values instead of just one
print(result)
</code></pre>
<p>this is the output i am looking for: <code>72 101 108 108 111</code> (hello) but instead i get an error telling me i can only pass 1 character/value inside chr() / ord()
is this possible? if not can you provide me in the right direction? thank you</p>
| 1 |
2016-09-10T19:05:20Z
| 39,429,650 |
<p>Use a list comprehension - apply <code>ord</code> to each character in the string.</p>
<pre><code>In [777]: [ord(i) for i in 'hello']
Out[777]: [104, 101, 108, 108, 111]
</code></pre>
| 0 |
2016-09-10T19:09:32Z
|
[
"python"
] |
converting chr() / ord() with multi characters
| 39,429,601 |
<p>beginner programming in python (3.4)<br>
is it possible to pass multiple values inside chr() and ord()?
what i tried is the following:</p>
<pre><code>userInput = input('Please write your input: ')
> Hello
result = ord(userInput) #here is the error because i put multiple values instead of just one
print(result)
</code></pre>
<p>this is the output i am looking for: <code>72 101 108 108 111</code> (hello) but instead i get an error telling me i can only pass 1 character/value inside chr() / ord()
is this possible? if not can you provide me in the right direction? thank you</p>
| 1 |
2016-09-10T19:05:20Z
| 39,429,656 |
<p>You could use a list comprehension to apply <code>ord</code> to every character of the string, and then join them to get the result you're looking for:</p>
<pre><code>result = " ".join([str(ord(x)) for x in userInput])
</code></pre>
| 0 |
2016-09-10T19:10:21Z
|
[
"python"
] |
Pydrive deleting file from Google Drive
| 39,429,627 |
<p>I´m writing a small script in python 3.5.2 with pydrive 1.2.1 and I need to be able to delete a file which is not stored locally in my computer, but in my account of Google Drive. The <a href="http://pythonhosted.org/PyDrive/filemanagement.html#delete-trash-and-un-trash-files" rel="nofollow">docs</a> only show how to delete a file you previously created, not one which is already stored on the drive. Is deleting an existing file actually possible with pydrive? if so, how? </p>
| 1 |
2016-09-10T19:07:50Z
| 39,429,783 |
<p>From the docs seems that <code>drive.CreateFile()</code> create only a reference to a file, this can be local or remote.
As you can se <a href="http://pythonhosted.org/PyDrive/filemanagement.html#download-file-content" rel="nofollow">here</a> <code>drive.CreateFile()</code> is used to download a remote file.</p>
<p>I believe that something like this should do the job:</p>
<pre><code># Initialize GoogleDriveFile instance with file id.
file1 = drive.CreateFile({'id': <file-id>})
file1.Trash() # Move file to trash.
file1.UnTrash() # Move file out of trash.
file1.Delete() # Permanently delete the file.
</code></pre>
| 1 |
2016-09-10T19:23:03Z
|
[
"python",
"pydrive"
] |
Pandas selecting duplicates that occur n times
| 39,429,671 |
<p>I have a dataframe how would I select duplicates that occur two times only</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'Name':['Two','Twice','Twice','three','three','three','one', 'Two'],
'key':[2,2,2,1,1,3,1,1,],
'Last':['Foo','Macy','Gayson','Simpson','Diablo','Niggah','Simpson', 'Mortimer']
})
r=df[df.duplicated(subset=['Name'], keep =False)]
print(r)
</code></pre>
<p>so I would get:</p>
<pre><code> Last Name key
0 Foo Two 2
1 Macy Twice 2
2 Gayson Twice 2
7 Mortimer Two 1
</code></pre>
| 0 |
2016-09-10T19:11:23Z
| 39,429,788 |
<p>try this:</p>
<pre><code>In [80]: df.groupby('Name').filter(lambda x: len(x) == 2)
Out[80]:
Last Name key
0 Foo Two 2
1 Macy Twice 2
2 Gayson Twice 2
7 Mortimer Two 1
</code></pre>
| 0 |
2016-09-10T19:23:31Z
|
[
"python",
"pandas",
"dataframe",
"duplicates"
] |
Python paramiko: redirecting stderr is affected by get_pty = True
| 39,429,680 |
<p>I am trying to implement an ssh agent that will allow me later, among other things, to execute commands in blocking mode, where output is being read from the channel as soon as it is available.<br>
Here's what I have so far: </p>
<pre><code>from paramiko import client
class SSH_Agent:
def __init__(self, server_name, username = getpass.getuser(), password = None, connection_timeout = CONNECTION_TIMEOUT):
self.ssh_agent = client.SSHClient()
self.ssh_agent.set_missing_host_key_policy(client.AutoAddPolicy())
self.ssh_agent.connect(server_name, username = username, password = password if password is not None else username, timeout = connection_timeout)
def execute_command(self, command, out_streams = [sys.stdout], err_streams = [sys.stderr], poll_intervals = POLL_INTERVALS):
stdin, stdout, stderr = self.ssh_agent.exec_command(command)
channel = stdout.channel
stdin.close()
channel.shutdown_write()
while not channel.closed or channel.recv_ready() or channel.recv_stderr_ready():
got_data = False
output_channels = select.select([channel], [], [], poll_intervals)[0]
if output_channels:
channel = output_channels[0]
if channel.recv_ready():
for stream in out_streams:
stream.write(channel.recv(len(channel.in_buffer)))
stream.flush()
got_data = True
if channel.recv_stderr_ready():
for stream in err_streams:
stream.write(channel.recv_stderr(len(channel.in_stderr_buffer)))
stream.flush()
got_data = True
if not got_data \
and channel.exit_status_ready() \
and not channel.recv_ready() \
and not channel.recv_stderr_ready():
channel.shutdown_read()
channel.close()
break
return channel.recv_exit_status()
</code></pre>
<p>(this implementation is based on one I found somewhere here in SO)<br>
When I test it, it works fine, except that I get this when executing commands: </p>
<pre><code>tput: No value for $TERM and no -T specified
</code></pre>
<p>I read a bit online, and found out that happens because there's no actual terminal behind the <code>ssh</code> session.<br>
So, I tried to call <code>paramiko</code>'s <code>exec_command()</code> with <code>get_pty = True</code>: </p>
<pre><code>stdin, stdout, stderr = self.ssh_agent.exec_command(command, get_pty = True)
</code></pre>
<p>But then I found out that I'm losing the ability to get data to <code>stderr</code> on the channel (everything goes to <code>stdout</code> for some reason, i.e. <code>channel.recv_stderr_ready()</code> is never <code>True</code>). Indeed, I found in the doc the following: </p>
<blockquote>
<p>recv_stderr_ready()</p>
<p>Returns true if data is buffered and ready to be read from this channelâs stderr stream. <strong>Only channels using exec_command or
invoke_shell without a pty will ever have data on the stderr stream</strong>.<br>
Returns: True if a recv_stderr call on this channel would immediately return at least one byte; False otherwise.</p>
</blockquote>
<p>How can I have both?<br>
In other words, how can I get rid of this: </p>
<pre><code>tput: No value for $TERM and no -T specified
</code></pre>
<p>while still having the ability to direct <code>stderr</code> to wherever I choose?</p>
<p><strong>EDIT</strong>:<br>
I Just had an idea...<br>
Can I somehow define this <code>TERM</code> variable in the remote shell to get rid of that error? Is this a common approach or is it a bad workaround that only hides the problem?</p>
| 0 |
2016-09-10T19:11:58Z
| 39,526,279 |
<p>Assuming you're running on a *nix system, you could try setting <code>TERM</code> in your command environment instead of creating a pty.</p>
<p>For example:</p>
<pre><code>def execute_command(self, command, out_streams = [sys.stdout], err_streams = [sys.stderr], poll_intervals = POLL_INTERVALS):
# Pre-pend required environment here
command = "TERM=xterm " + command
stdin, stdout, stderr = self.ssh_agent.exec_command(command)
channel = stdout.channel
stdin.close()
channel.shutdown_write()
...
</code></pre>
<p>This should still allow you access to the separate streams using your existing code.</p>
| 1 |
2016-09-16T07:46:57Z
|
[
"python",
"ssh",
"paramiko",
"stderr",
"io-redirection"
] |
How to use nameFilters with QDirIterator?
| 39,429,800 |
<p>In PySide, when I use <code>QDirIterator</code>, how I can filter on files by name?</p>
<p>In the documentation, it talks about the parameter <code>nameFilters</code>:</p>
<ul>
<li><a href="https://srinikom.github.io/pyside-docs/PySide/QtCore/QDirIterator.html" rel="nofollow">https://srinikom.github.io/pyside-docs/PySide/QtCore/QDirIterator.html</a></li>
</ul>
<p>But when I try it, it doesn't filter the files by extension:</p>
<pre><code>from PySide import QtCore
it = QtCore.QDirIterator('.', nameFilters=['*.py'])
while it.hasNext():
print it.next()
>> ./.
>> ./..
>> my_script.py
>> another_file.txt
</code></pre>
<p>With this code, I expected to get only the files with the extension <code>.py</code>.</p>
| 1 |
2016-09-10T19:24:26Z
| 39,430,301 |
<p>The <code>nameFilters</code> parameter is not a keyword argument.</p>
<p>Unfortunately, PySide never raises an error if you pass keyword arguments that don't exist, which is a very poor design. APIs should never fail silently when given invalid inputs.</p>
<p>Anyway, your code will work correctly if you use a positional argument:</p>
<pre><code>it = QtCore.QDirIterator('.', ['*.py'])
</code></pre>
| 0 |
2016-09-10T20:27:33Z
|
[
"python",
"iterator",
"pyside",
"qdir"
] |
No Reverse Match with Django Auth Views
| 39,429,807 |
<p>I created a custom User model following the example in the Django documentation, now I'm trying to use Django auth views but I keep getting <code>NoReverseMatch at /accounts/login/</code></p>
<pre><code>Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
</code></pre>
<p>This is the url conf:</p>
<pre><code>from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html',
'authentication_form': LoginForm}),
url(r'^logout/$', auth_views.logout, {'next_page': '/accounts/login'}),
url(r'^$', home, name="home"),
]
</code></pre>
<p>And I have this line in my template:</p>
<pre><code><form method="post" action="{% url 'django.contrib.auth.views.login' %}">
</code></pre>
| 0 |
2016-09-10T19:24:55Z
| 39,429,835 |
<pre><code>{% url 'django.contrib.auth.views.login' %}
</code></pre>
<p>This is incorrect. We put the name given to the url here instead of the location of the view.</p>
<p>Please see <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url</a>. You need to provide a name for login like you have for home and then use that.</p>
<p>Correct way is:
urls.py -></p>
<pre><code>url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html','authentication_form': LoginForm}, name="login") ,
</code></pre>
<p>template -></p>
<pre><code><form method="post" action="{% url 'login' %}">
</code></pre>
| 2 |
2016-09-10T19:27:56Z
|
[
"python",
"django"
] |
When filtering content of 2 models together getting - 'tuple' object has no attribute '_meta'?
| 39,429,823 |
<p>I usually display filter options by one model.But now I have to allow to filter by the content of 2 models.</p>
<pre><code>class Lease(CommonInfo):
version = IntegerVersionField( )
amount = models.DecimalField(max_digits=7, decimal_places=2)
is_notrenewed = models.BooleanField(default=False)
unit = models.ForeignKey(Unit)
is_terminated = models.BooleanField(default=False)
class LeaseConditions(CommonInfo):
version = IntegerVersionField( )
start_date = models.DateTimeField()
end_date = models.DateTimeField()
lease = models.ForeignKey(Lease)
increase = models.DecimalField(max_digits=7, decimal_places=2)
amount = models.DecimalField(max_digits=7, decimal_places=2)
is_terminated = models.BooleanField(default=False)
not_terminated_active_objects = NotTerminatedActiveManager()
</code></pre>
<p>So I added 2nd model to my filter</p>
<pre><code>class LeaseFilter(django_filters.FilterSet):
class Meta:
model = Lease,LeaseConditions
fields = ['is_notrenewed', 'unit',
'is_terminated', 'start_date']
</code></pre>
<p>but getting error now </p>
<blockquote>
<p>'tuple' object has no attribute '_meta'</p>
</blockquote>
<p>What could be the problem?</p>
<p>Trace:</p>
<pre><code>Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/lease/list/?is_notrenewed=1&unit=&is_terminated=1
Django Version: 1.8
Python Version: 2.7.11
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'concurrency',
'registration',
'crispy_forms',
'django_filters',
'common',
'client',
'lease',
'unit')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\core\handlers\base.py" in get_response
119. resolver_match = resolver.resolve(request.path_info)
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\core\urlresolvers.py" in resolve
366. for pattern in self.url_patterns:
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\core\urlresolvers.py" in url_patterns
402. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\core\urlresolvers.py" in urlconf_module
396. self._urlconf_module = import_module(self.urlconf_name)
File "c:\python27\Lib\importlib\__init__.py" in import_module
37. __import__(name)
File "C:\Users\Boris\dev\rentout\rentout\rentout\urls.py" in <module>
11. url(r'^lease/', include('lease.urls')),
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django\conf\urls\__init__.py" in include
33. urlconf_module = import_module(urlconf_module)
File "c:\python27\Lib\importlib\__init__.py" in import_module
37. __import__(name)
File "C:\Users\Boris\dev\rentout\rentout\lease\urls.py" in <module>
2. from lease import views
File "C:\Users\Boris\dev\rentout\rentout\lease\views.py" in <module>
59. class LeaseFilter(django_filters.FilterSet):
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django_filters\filterset.py" in __new__
181. filters = new_class.filters_for_model(opts.model, opts)
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django_filters\filterset.py" in filters_for_model
456. cls.filter_for_reverse_field
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django_filters\filterset.py" in filters_for_model
78. field = get_model_field(model, f)
File "C:\Users\Boris\dev\rentout\virtrentout\lib\site-packages\django_filters\utils.py" in get_model_field
72. opts = model._meta
Exception Type: AttributeError at /lease/list/
Exception Value: 'tuple' object has no attribute '_meta'
</code></pre>
| 0 |
2016-09-10T19:26:37Z
| 39,430,112 |
<p><code>model</code> property must be a model, not a tuple of models - you are specifying two models for an object that accepts only one. For filtering based on related objects, you can do it like this: </p>
<pre><code>class LeaseFilter(django_filters.FilterSet):
class Meta:
model = LeaseConditions
fields = ['lease__is_notrenewed', 'lease__unit', 'is_terminated', 'start_date']
</code></pre>
| 1 |
2016-09-10T20:02:50Z
|
[
"python",
"django-filter"
] |
Putting pixels with PIL gives error
| 39,429,886 |
<p>Newbie here.
i tried to put some number of pixel with random RGB-colors (like adding noise):</p>
<pre><code>from PIL import Image
import random
img=Image.open('pic.bmp')
randomenter=int(input('Enter numpix: '))
for numpix in range(0, randomenter):
x=random.randint(0,int(img.size[0]))
y=random.randint(0,int(img.size[1]))
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
img.putpixel((x,y),(r,g,b))
img.show()
</code></pre>
<p>with <code>randomenter=100</code> it works sometimes. with higher values it gets me an error:</p>
<pre><code>Traceback (most recent call last):
File "D:\study\7sem\GiMS\labs\1laba\123.py", line 11, in <module>
img.putpixel((x,y),(r,g,b))
File "C:\Python34\lib\site-packages\pillow-3.3.1-py3.4-win-amd64.egg\PIL\Image.py", line 1512, in putpixel
return self.im.putpixel(xy, value)
IndexError: image index out of range
</code></pre>
<p>What am I doing wrong?
pic with <code>(800, 500)</code> values</p>
| 0 |
2016-09-10T19:34:06Z
| 39,430,146 |
<p>How posted @ÅukaszRogalsk, it solves by editing <code>x</code> and <code>y</code> to <code>img.size[0]-1</code> and <code>img.size[1]-1</code></p>
| 0 |
2016-09-10T20:07:25Z
|
[
"python",
"python-imaging-library"
] |
measure progress (time left) while os.listdir is generating a list (Python)
| 39,429,978 |
<p>In Python 2.7, I am using <code>os.listdir</code> to generate a list of files in a folder. There are lots of files and my connection to the folder is slow so it can take up to 30 seconds to complete. Here is an example:</p>
<pre><code>import os
import time
start_time = time.time()
dir_path = r'C:\Users\my_name\Documents\data_directory' #example path
file_list = os.listdir(dir_path)
print 'it took', time.time() - start_time, 'seconds'
</code></pre>
<p>This is for a Tkinter GUI I'm working on and I would like make a status bar showing how much time or percentage is left for this step that takes a long time (about 30 seconds).</p>
<p>Is there a way to show the time left or percentage left to complete the <code>file_list = os.listdir(dir_path)</code> step???</p>
| 2 |
2016-09-10T19:46:55Z
| 39,430,021 |
<p>You ought to use <code>scandir</code> which is only available with Python 3. </p>
<p>But there is a <a href="https://pypi.python.org/pypi/scandir" rel="nofollow">back port.</a> </p>
<p>To understand the problem, read <a href="https://www.python.org/dev/peps/pep-0471/" rel="nofollow">PEP 471</a>. </p>
| 0 |
2016-09-10T19:51:50Z
|
[
"python",
"tkinter",
"operating-system",
"listdir"
] |
Python Encode Spaces are incorrectly encoded
| 39,430,032 |
<p>I have a dictionary as follows </p>
<pre><code>params = {
'response_type': 'token',
'client_id': o_auth_client_id,
'redirect_url': call_back_url,
'scope': 'activity heartrate location'
}
print urllib.urlencode(params)
</code></pre>
<p>and um encoding it </p>
<p>but in results </p>
<blockquote>
<p>redirect_url=http%3A%2F%2F127.0.0.1%3A8084%2Fagile_healtg%2Faccess_token%2F&response_type=token&client_id=xxxxxx&scope=activity+heartrate+location</p>
</blockquote>
<p>um getting something like above
Unfortunately spaces are encoded as + signs </p>
<p>but the results should be </p>
<blockquote>
<p>scope=activity%20nutrition%20heartrate</p>
</blockquote>
<p>how may I achieve the correct encode for spaces in python ?</p>
| 0 |
2016-09-10T19:52:59Z
| 39,430,218 |
<p>Check the documentation for the <a href="https://docs.python.org/2/library/urllib.html#urllib.urlencode" rel="nofollow">urlencode</a>.</p>
<p>The <code>quote_plus</code> method is used to change the spaces to plus symbol when it comes to passing key values. You can use <code>unquote_plus</code> method to remove the plus symbols and then <code>quote</code> to encode it in the format you want.</p>
<p><strong>You basically need to use the <code>quote</code> method for your parameters</strong></p>
| 1 |
2016-09-10T20:17:55Z
|
[
"python",
"encoding",
"urlencode"
] |
Python Encode Spaces are incorrectly encoded
| 39,430,032 |
<p>I have a dictionary as follows </p>
<pre><code>params = {
'response_type': 'token',
'client_id': o_auth_client_id,
'redirect_url': call_back_url,
'scope': 'activity heartrate location'
}
print urllib.urlencode(params)
</code></pre>
<p>and um encoding it </p>
<p>but in results </p>
<blockquote>
<p>redirect_url=http%3A%2F%2F127.0.0.1%3A8084%2Fagile_healtg%2Faccess_token%2F&response_type=token&client_id=xxxxxx&scope=activity+heartrate+location</p>
</blockquote>
<p>um getting something like above
Unfortunately spaces are encoded as + signs </p>
<p>but the results should be </p>
<blockquote>
<p>scope=activity%20nutrition%20heartrate</p>
</blockquote>
<p>how may I achieve the correct encode for spaces in python ?</p>
| 0 |
2016-09-10T19:52:59Z
| 39,430,347 |
<p>This program might do what you ask for. </p>
<pre><code>import urllib
def my_special_urlencode(params):
return '&'.join('{}={}'.format(urllib.quote(k, ''), urllib.quote(v, '')) for k,v in params.items())
params = {
'response_type': 'token',
'client_id': 'xxxxxx',
'redirect_url': 'http://example.com/callback',
'scope': 'activity heartrate location'
}
print my_special_urlencode(params)
</code></pre>
<p>Result:</p>
<pre><code>redirect_url=http%3A%2F%2Fexample.com%2Fcallback&response_type=token&client_id=xxxxxx&scope=activity%20heartrate%20location
</code></pre>
| 1 |
2016-09-10T20:34:03Z
|
[
"python",
"encoding",
"urlencode"
] |
Extracting images from excel sheet by row with python
| 39,430,039 |
<p>I am trying to extract images from excel sheet. The excel sheet is basically a list of products with images and details of products.</p>
<p>with</p>
<pre><code>EmbeddedFiles = zipfile.ZipFile(path).namelist()
ImageFiles = [F for F in EmbeddedFiles if F.count('.jpg') or F.count('.jpeg')]
</code></pre>
<p>I can extract all images at once but i cannot figure out a way to get images by row so that i could save products into database and add images to respective products.</p>
<p>I was using openpyxl to read from excel but that does not provide a way to get images. I can shift to other libraries.</p>
<p>What would be the best way to do this.</p>
| 1 |
2016-09-10T19:54:09Z
| 39,430,329 |
<p>The <code>xlsx</code> file is indeed in compressed format, but that does not mean that you have to expand it to work with it. Let <code>openpyxl</code> do that for you. The library in its documentation mentions that it can handle this format pretty well.</p>
<p>So try opening the file and reading line by line using <a href="https://openpyxl.readthedocs.io/en/default/tutorial.html#loading-from-a-file" rel="nofollow">this</a>, <a href="https://openpyxl.readthedocs.io/en/default/tutorial.html#accessing-many-cells" rel="nofollow">this</a> and <a href="https://openpyxl.readthedocs.io/en/default/usage.html#read-an-existing-workbook" rel="nofollow">this</a> example found in the documentation</p>
| 0 |
2016-09-10T20:30:39Z
|
[
"python",
"excel",
"image"
] |
Raising exception from within except clause
| 39,430,157 |
<p>I'm wondering if we can do something like the following:<br>
We catch socket error and if the message is different than some value,<br>
raise the exception forward to be caught on the next general except clause below? </p>
<pre><code>try:
some logic to connect to a server..
except socket.error as se:
if se.messsage != '123':
raise Exception(se.message)
except exception as ex:
log.error('write something')
</code></pre>
| 1 |
2016-09-10T20:09:12Z
| 39,430,304 |
<p>You can simply re-raise the exception with <code>raise</code> without arguments:</p>
<pre><code>try:
# some code
except:
if condition:
raise
</code></pre>
| 0 |
2016-09-10T20:27:44Z
|
[
"python",
"exception-handling"
] |
Raising exception from within except clause
| 39,430,157 |
<p>I'm wondering if we can do something like the following:<br>
We catch socket error and if the message is different than some value,<br>
raise the exception forward to be caught on the next general except clause below? </p>
<pre><code>try:
some logic to connect to a server..
except socket.error as se:
if se.messsage != '123':
raise Exception(se.message)
except exception as ex:
log.error('write something')
</code></pre>
| 1 |
2016-09-10T20:09:12Z
| 39,430,332 |
<p>To do this, you need a set of try-catch blocks. Once, an exception has been caught, re-throwing the exception results in it being caught at the outer level. Try if else inside the blocks or simply nest try-except block in another one like this:</p>
<pre><code>try:
try:
#...
except:
raise
except:
pass
</code></pre>
| 2 |
2016-09-10T20:31:02Z
|
[
"python",
"exception-handling"
] |
Raising exception from within except clause
| 39,430,157 |
<p>I'm wondering if we can do something like the following:<br>
We catch socket error and if the message is different than some value,<br>
raise the exception forward to be caught on the next general except clause below? </p>
<pre><code>try:
some logic to connect to a server..
except socket.error as se:
if se.messsage != '123':
raise Exception(se.message)
except exception as ex:
log.error('write something')
</code></pre>
| 1 |
2016-09-10T20:09:12Z
| 39,450,876 |
<p>Here is an example:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
num = 10
while True:
denum = int(raw_input("> "))
res = num/denum
print str(res)
except ZeroDivisionError:
print "ZeroDivisionError"
exit(0)
except KeyboardInterrupt:
print "\nGoodbye!"
exit(0)
except Exception, error:
print "An error encoutered"
exit(0)
</code></pre>
<p>If you try to run that program you will see that as long you provide
input-a number it will return to you a result till the <strong>KeyboardInterrupt</strong>
exception occurs.
But in the meantime if it happen to occur another exception(for example if you enter a letter) it will be caught by the last <strong>general exception</strong> handler unless
a <strong>ZeroDivisionError</strong> occurs, where it will be caught by the corresponding exception and not by the others. </p>
<p>A more relevant-closer approach to what you posted would be to write the above program like that:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
num = 10
while True:
denum = int(raw_input("> "))
res = num/denum
print str(res)
except KeyboardInterrupt:
print "\nGoodbye!"
exit(0)
except Exception, error:
if "division" in str(error):
raise error
else:
print "Unknown error"
exit(0)
</code></pre>
<p>Well, in this case we are catching a general exception, but this time
we use an <strong><em>if-else</em></strong> statement to define our code behaviour!</p>
<p>So in your example I don't
know if it would behave the same but you could give it a try.
Hope it helps!</p>
| 0 |
2016-09-12T12:58:07Z
|
[
"python",
"exception-handling"
] |
Get UTC timestamp from time zone aware datetime object in Python
| 39,430,161 |
<p>I have a datetime object that I created with<code>datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific'))</code>.
Please correct me if I'm wrong, but I believe that my datetime object is NOT naïve. How do I convert this datetime object to a UTC timestamp?</p>
| 2 |
2016-09-10T20:09:27Z
| 39,430,248 |
<pre><code>non_naive_datetime_obj.astimezone(pytz.utc).timestamp()
</code></pre>
| 0 |
2016-09-10T20:20:56Z
|
[
"python",
"datetime",
"utc"
] |
Get UTC timestamp from time zone aware datetime object in Python
| 39,430,161 |
<p>I have a datetime object that I created with<code>datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific'))</code>.
Please correct me if I'm wrong, but I believe that my datetime object is NOT naïve. How do I convert this datetime object to a UTC timestamp?</p>
| 2 |
2016-09-10T20:09:27Z
| 39,430,270 |
<p>Use <code>datetime.astimezone</code> to get the same datetime in UTC (or any other timezone).</p>
<pre><code>dt = datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific'))
dt_utc = dt.astimezone(pytz.timezone('UTC'))
</code></pre>
| 2 |
2016-09-10T20:23:59Z
|
[
"python",
"datetime",
"utc"
] |
python: efficient way to check only a couple of rows in a csvreader iterator?
| 39,430,351 |
<p>I have a (very large) CSV file that looks something like this:</p>
<pre><code>header1,header2,header3
name0,rank0,serial0
name1,rank1,serial1
name2,rank2,serial2
</code></pre>
<p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute appended to the end of each row:</p>
<pre><code>header1,header2,header3,new_hdr4,new_hdr5
name0,rank0,serial0,salary0,base0
name1,rank1,serial1,salary1,base1
name2,rank2,serial2,salary2,base2
</code></pre>
<p>What I'm trying to do is structure the script so that it auto-detects whether or not the CSV file it's reading has <strong><em>already been processed</em></strong>. If it has been processed, I can skip a lot of expensive calculations later. I'm trying to understand whether there is a reasonable way of doing this within the reader loop. I <em>could</em> just open the file once, read in enough to do the detection, and then close and reopen it with a flag set, but this seems hackish.</p>
<p>Is there a way to do this within the same reader? The logic is something like:</p>
<pre><code>read first N lines ###(N is small)
if (some condition)
already_processed = TRUE
read_all_csv_without_processing
else
read_all_csv_WITH_processing
</code></pre>
<p>I can't just use the iterator that reader gives me, because by the time I've gotten enough lines to do my conditional check, I don't have any good way to go back to the beginning of the CSV. Is closing and reopening it really the most elegant way to do this?</p>
| 2 |
2016-09-10T20:34:22Z
| 39,430,444 |
<p>If you're using the usual python method to read the file (<code>with open("file.csv","r") as f:</code> or equivalent), you can "reset" the file reading by calling <code>f.seek(0)</code>. </p>
<p>Here is a piece of code that should (I guess) look a bit more like the way you're reading your file. It demonstate that reseting <code>csvfile</code> with <code>csvfile.seek(0)</code> will also reset <code>csvreader</code>:</p>
<pre><code>with open('so.txt', 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
for row in csvreader:
print('Checking if processed')
print(', '.join(row))
#if condition:
if True:
print('File already processed')
already_processed = True
print('Reseting the file')
csvfile.seek(0)
for row in csvreader:
print(', '.join(row))
break
</code></pre>
| 1 |
2016-09-10T20:46:52Z
|
[
"python",
"csv"
] |
python: efficient way to check only a couple of rows in a csvreader iterator?
| 39,430,351 |
<p>I have a (very large) CSV file that looks something like this:</p>
<pre><code>header1,header2,header3
name0,rank0,serial0
name1,rank1,serial1
name2,rank2,serial2
</code></pre>
<p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute appended to the end of each row:</p>
<pre><code>header1,header2,header3,new_hdr4,new_hdr5
name0,rank0,serial0,salary0,base0
name1,rank1,serial1,salary1,base1
name2,rank2,serial2,salary2,base2
</code></pre>
<p>What I'm trying to do is structure the script so that it auto-detects whether or not the CSV file it's reading has <strong><em>already been processed</em></strong>. If it has been processed, I can skip a lot of expensive calculations later. I'm trying to understand whether there is a reasonable way of doing this within the reader loop. I <em>could</em> just open the file once, read in enough to do the detection, and then close and reopen it with a flag set, but this seems hackish.</p>
<p>Is there a way to do this within the same reader? The logic is something like:</p>
<pre><code>read first N lines ###(N is small)
if (some condition)
already_processed = TRUE
read_all_csv_without_processing
else
read_all_csv_WITH_processing
</code></pre>
<p>I can't just use the iterator that reader gives me, because by the time I've gotten enough lines to do my conditional check, I don't have any good way to go back to the beginning of the CSV. Is closing and reopening it really the most elegant way to do this?</p>
| 2 |
2016-09-10T20:34:22Z
| 39,430,632 |
<p>I suppose if you do not want to just test the first few lines of the file, you could create a single iterator from a list and then the continuation of the csv reader.</p>
<p>Given:</p>
<pre><code>header1,header2,header3
name0,rank0,serial0
name1,rank1,serial1
name2,rank2,serial2
</code></pre>
<p>You can do:</p>
<pre><code>import csv
from itertools import chain
with open(fn) as f:
reader=csv.reader(f)
header=next(reader)
N=2
p_list=[]
for i in range(N): # N is however many you need to set processed flag
p_list.append(next(reader))
print("p_list:", p_list)
# now use p_list to determine if processed however processed=check(p_list)
for row in chain(iter(p_list), reader): # chain creates a single csv reader...
# handler processed or not here from the stream of rows...
# if not processed:
# process
# else:
# handle already processed...
# print row just to show csv data is complete:
print(row)
</code></pre>
<p>Prints:</p>
<pre><code>p_list: [['name0', 'rank0', 'serial0'], ['name1', 'rank1', 'serial1']]
['name0', 'rank0', 'serial0']
['name1', 'rank1', 'serial1']
['name2', 'rank2', 'serial2']
</code></pre>
| 1 |
2016-09-10T21:15:19Z
|
[
"python",
"csv"
] |
python: efficient way to check only a couple of rows in a csvreader iterator?
| 39,430,351 |
<p>I have a (very large) CSV file that looks something like this:</p>
<pre><code>header1,header2,header3
name0,rank0,serial0
name1,rank1,serial1
name2,rank2,serial2
</code></pre>
<p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute appended to the end of each row:</p>
<pre><code>header1,header2,header3,new_hdr4,new_hdr5
name0,rank0,serial0,salary0,base0
name1,rank1,serial1,salary1,base1
name2,rank2,serial2,salary2,base2
</code></pre>
<p>What I'm trying to do is structure the script so that it auto-detects whether or not the CSV file it's reading has <strong><em>already been processed</em></strong>. If it has been processed, I can skip a lot of expensive calculations later. I'm trying to understand whether there is a reasonable way of doing this within the reader loop. I <em>could</em> just open the file once, read in enough to do the detection, and then close and reopen it with a flag set, but this seems hackish.</p>
<p>Is there a way to do this within the same reader? The logic is something like:</p>
<pre><code>read first N lines ###(N is small)
if (some condition)
already_processed = TRUE
read_all_csv_without_processing
else
read_all_csv_WITH_processing
</code></pre>
<p>I can't just use the iterator that reader gives me, because by the time I've gotten enough lines to do my conditional check, I don't have any good way to go back to the beginning of the CSV. Is closing and reopening it really the most elegant way to do this?</p>
| 2 |
2016-09-10T20:34:22Z
| 39,430,654 |
<p>I think what you're trying to achieve is to use the first lines to decide between the type of processing, then re-use those lines for your read_all_csv_WITH_processing or read_all_csv_without_processing, while still not loading the full csv file in-memory. To achieve that you can load the first lines in a list and concatenate that with the rest of the file with itertools.chain, like this:</p>
<pre><code>import itertools
top_lines = []
reader_iterator = csv.reader(fil)
do_heavy_processing = True
while True:
# Can't use "for line in reader_iterator" directly, otherwise we're
# going to close the iterator when going out of the loop after the first
# N iterations
line = reader_iterator.__next__()
top_lines.append(line)
if some_condition(line):
do_heavy_processing = False
break
elif not_worth_going_further(line)
break
full_file = itertools.chain(top_lines, reader_iterator)
if do_heavy_processing:
read_all_csv_WITH_processing(full_file)
else:
read_all_csv_without_processing(full_file)
</code></pre>
| 0 |
2016-09-10T21:18:29Z
|
[
"python",
"csv"
] |
python: efficient way to check only a couple of rows in a csvreader iterator?
| 39,430,351 |
<p>I have a (very large) CSV file that looks something like this:</p>
<pre><code>header1,header2,header3
name0,rank0,serial0
name1,rank1,serial1
name2,rank2,serial2
</code></pre>
<p>I've written some code that processes the file, and writes it out (using csvwriter) modified as such, with some information I compute appended to the end of each row:</p>
<pre><code>header1,header2,header3,new_hdr4,new_hdr5
name0,rank0,serial0,salary0,base0
name1,rank1,serial1,salary1,base1
name2,rank2,serial2,salary2,base2
</code></pre>
<p>What I'm trying to do is structure the script so that it auto-detects whether or not the CSV file it's reading has <strong><em>already been processed</em></strong>. If it has been processed, I can skip a lot of expensive calculations later. I'm trying to understand whether there is a reasonable way of doing this within the reader loop. I <em>could</em> just open the file once, read in enough to do the detection, and then close and reopen it with a flag set, but this seems hackish.</p>
<p>Is there a way to do this within the same reader? The logic is something like:</p>
<pre><code>read first N lines ###(N is small)
if (some condition)
already_processed = TRUE
read_all_csv_without_processing
else
read_all_csv_WITH_processing
</code></pre>
<p>I can't just use the iterator that reader gives me, because by the time I've gotten enough lines to do my conditional check, I don't have any good way to go back to the beginning of the CSV. Is closing and reopening it really the most elegant way to do this?</p>
| 2 |
2016-09-10T20:34:22Z
| 39,431,018 |
<p>I will outline what I consider a much better approach. I presume this is happening over various runs. What you need to do is persist the files seen between runs and only process what has not been seen:</p>
<pre><code>import pickle
import glob
def process(fle):
# read_all_csv_with_processing
def already_process(fle):
# read_all_csv_without_processing
try:
# if it exists, we ran the code previously.
with open("seen.pkl", "rb") as f:
seen = pickle.load(f)
except IOError as e:
# Else first run, so just create the set.
print(e)
seen = set()
for file in glob.iglob("path_where_files_are/*.csv"):
# if not seen before, just process
if file not in seen:
process(file)
else:
# already processed so just do whatever
already_process(file)
seen.add(file)
# persist the set.
with open("seen.pkl", "w") as f:
pickle.dumps(seen, f)
</code></pre>
<p>Even if for some strange reason you somehow process the same files in the same run, all you need to do then is implement the seen set logic.</p>
<p>Another alternative would be to use a unique marker in the file that you add at the start if processed. </p>
<pre><code># something here
header1,header2,header3,new_hdr4,new_hdr5
name0,rank0,serial0,salary0,base0
name1,rank1,serial1,salary1,base1
name2,rank2,serial2,salary2,base2
</code></pre>
<p>Then all you would need to process is the very first line. Also if you want to get the first n lines from a file even if you wanted to <a href="http://stackoverflow.com/questions/38064374/iterate-from-a-certain-row-of-a-csv-file-in-python/38064407#38064407">start from a certain row</a>, use <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow">itertools.islce</a></p>
<p>To be robust you might want to wrap your code in a try/finally in case it errors so you don't end up going over the same files already processed on the next run:</p>
<pre><code>try:
for file in glob.iglob("path_where_files_are/*.csv"):
# if not seen before, just process
if file not in seen:
process(file)
else:
# already processed so just do whatever
already_process(file)
seen.add(file)
finally:
# persist the set.
with open("seen.pkl", "wb") as f:
pickle.dump(seen, f)
</code></pre>
| -1 |
2016-09-10T22:05:23Z
|
[
"python",
"csv"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.