title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
python write cell to matrix in wrong way | 39,009,805 | <p>I have a simple code for testing, my code supposed to only write matrix at (1,1) and (2,2), these two cells.</p>
<pre><code>grid = [
[1,1,1,2,],
[1,9,1,2,],
[1,8,9,2,],
[1,2,3,4,]
]
n = 4
duplicate = [[0]*n]*n
for i in range(1,n-1):
for j in range(1,n-1):
cur = grid[i][j]
if (cur > grid[i-1][j]) and (cur > grid[i][j-1]) and (cur > grid[i+1][j]) and (cur > grid[i][j+1]):
print(i,j)
duplicate[i][j]="X"
print(duplicate)
</code></pre>
<p>My output:</p>
<pre><code>1 1
2 2
[[0, 'X', 'X', 0], [0, 'X', 'X', 0], [0, 'X', 'X', 0], [0, 'X', 'X', 0]]
</code></pre>
<p>However, the output is supposed to be like this:</p>
<pre><code>1 1
2 2
[[0, 0, 0, 0], [0, 'X', 0, 0], [0, 0, 'X', 0], [0, 0, 0, 0]]
</code></pre>
<p>What is wrong with my code?
Thanks a lot!</p>
| 0 | 2016-08-18T04:03:18Z | 39,009,850 | <p>Usual mistake: <code>[[0]*n]*n</code> creates a list of <code>n</code> references to the same list <code>[0]*n</code>. You need do this to create <code>n</code> different lists: <code>[[0]*n for _ in range(n)]</code> so you can update each one of them independently.</p>
| 1 | 2016-08-18T04:09:39Z | [
"python"
] |
python write cell to matrix in wrong way | 39,009,805 | <p>I have a simple code for testing, my code supposed to only write matrix at (1,1) and (2,2), these two cells.</p>
<pre><code>grid = [
[1,1,1,2,],
[1,9,1,2,],
[1,8,9,2,],
[1,2,3,4,]
]
n = 4
duplicate = [[0]*n]*n
for i in range(1,n-1):
for j in range(1,n-1):
cur = grid[i][j]
if (cur > grid[i-1][j]) and (cur > grid[i][j-1]) and (cur > grid[i+1][j]) and (cur > grid[i][j+1]):
print(i,j)
duplicate[i][j]="X"
print(duplicate)
</code></pre>
<p>My output:</p>
<pre><code>1 1
2 2
[[0, 'X', 'X', 0], [0, 'X', 'X', 0], [0, 'X', 'X', 0], [0, 'X', 'X', 0]]
</code></pre>
<p>However, the output is supposed to be like this:</p>
<pre><code>1 1
2 2
[[0, 0, 0, 0], [0, 'X', 0, 0], [0, 0, 'X', 0], [0, 0, 0, 0]]
</code></pre>
<p>What is wrong with my code?
Thanks a lot!</p>
| 0 | 2016-08-18T04:03:18Z | 39,009,947 | <p>The list your create use [[0]*n]*n is the same, You can prove by</p>
<pre><code>duplicate = [[0]*4]*4
duplicate[1][1] = 1
</code></pre>
<p>You may understand more by look at this problem</p>
<pre><code>def extendList(val, list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']
</code></pre>
| 0 | 2016-08-18T04:20:15Z | [
"python"
] |
Python - How to display a single data point on a scatter plot? | 39,009,872 | <p>I'm trying to display a 3D scatter plots. The code below works but it displays the current and old data points. I would like to display only one at a time. I've tried different options but I can't get it to work properly. Any suggestions?</p>
<p>Thanks!</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim(0, 1.5)
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
data = [[-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 0.0, 1.0]]
def animate(data):
x = data[0]
y = data[1]
z = data[2]
scat = ax.scatter3D(x, y, z, c='r', marker='o')
return
ani = animation.FuncAnimation(fig, animate, data, interval=1000, blit=False, repeat=False)
plt.show()
</code></pre>
| 0 | 2016-08-18T04:11:58Z | 39,017,438 | <p>You can clear the axes in each iteration in the <code>for</code> loop. Note that you need to take care of the axes limits as well.</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim(0, 1.5)
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
data = [[-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 0.0, 1.0]]
def animate(data):
x = data[0]
y = data[1]
z = data[2]
plt.cla()
ax.set_xlim([-1.5,1.5])
ax.set_ylim([-1.5,1.5])
ax.set_zlim([-1.5,1.5])
scat = ax.scatter3D(x, y, z, c='r', marker='o')
return
ani = animation.FuncAnimation(fig, animate, data, interval=1000, blit=False, repeat=False)
plt.show()
</code></pre>
| 0 | 2016-08-18T11:48:12Z | [
"python",
"animation",
"matplotlib"
] |
How to do a math equation using y = x^2 with range to print multiple outputs | 39,009,897 | <p>Hi this is my first question. I want this program to output y = x^2 y = 1-1000 and x = 1-1000 and it runs through each. This is what happens. Below source. </p>
<pre><code>y = range(0,1000)
x = range(0,1000)
stuff = x ** 2 / y
print stuff
</code></pre>
<blockquote>
<pre><code>Traceback (most recent call last):
File "testingsci.py", line 3, in <module>
stuff = int(x ** 2 / y)
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
</code></pre>
</blockquote>
<p>I have tried a few different things for example:</p>
<pre><code>y = int(range(0,1000))
x = int(range(0,1000))
stuff = int(x ** 2 / y)
print stuff
</code></pre>
| 0 | 2016-08-18T04:14:46Z | 39,009,985 | <p><code>range(0,1000)</code> runs from 0 to 999. You want to use <code>range(1,1001)</code>.</p>
<p>Try this:</p>
<pre><code>for x in range(1, 1001): # from 1 to 1000
for y in range(1, 1001):
stuff = (x ** 2)/y
print stuff
</code></pre>
| 0 | 2016-08-18T04:24:09Z | [
"python",
"python-2.7"
] |
How to do a math equation using y = x^2 with range to print multiple outputs | 39,009,897 | <p>Hi this is my first question. I want this program to output y = x^2 y = 1-1000 and x = 1-1000 and it runs through each. This is what happens. Below source. </p>
<pre><code>y = range(0,1000)
x = range(0,1000)
stuff = x ** 2 / y
print stuff
</code></pre>
<blockquote>
<pre><code>Traceback (most recent call last):
File "testingsci.py", line 3, in <module>
stuff = int(x ** 2 / y)
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
</code></pre>
</blockquote>
<p>I have tried a few different things for example:</p>
<pre><code>y = int(range(0,1000))
x = int(range(0,1000))
stuff = int(x ** 2 / y)
print stuff
</code></pre>
| 0 | 2016-08-18T04:14:46Z | 39,010,744 | <p>As a list comprehension:</p>
<pre><code>print [(x ** 2)/y for x in xrange(1, 1001) for y in xrange(1, 1001)]
</code></pre>
| 1 | 2016-08-18T05:48:49Z | [
"python",
"python-2.7"
] |
How to do a math equation using y = x^2 with range to print multiple outputs | 39,009,897 | <p>Hi this is my first question. I want this program to output y = x^2 y = 1-1000 and x = 1-1000 and it runs through each. This is what happens. Below source. </p>
<pre><code>y = range(0,1000)
x = range(0,1000)
stuff = x ** 2 / y
print stuff
</code></pre>
<blockquote>
<pre><code>Traceback (most recent call last):
File "testingsci.py", line 3, in <module>
stuff = int(x ** 2 / y)
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
</code></pre>
</blockquote>
<p>I have tried a few different things for example:</p>
<pre><code>y = int(range(0,1000))
x = int(range(0,1000))
stuff = int(x ** 2 / y)
print stuff
</code></pre>
| 0 | 2016-08-18T04:14:46Z | 39,012,047 | <p>Using <code>map</code>:</p>
<pre><code>>>> map(lambda x, y: (x ** 2)/y, xrange(1, 1001), xrange(1, 1001))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]
</code></pre>
<p>Using <code>itertools.imap</code>, build a generator:</p>
<pre><code>>>> import itertools
>>> list(itertools.imap(lambda x, y: (x ** 2)/y, xrange(1, 1001), xrange(1, 1001)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]
</code></pre>
| 0 | 2016-08-18T07:15:33Z | [
"python",
"python-2.7"
] |
How to replace an re match with a transformation of that match? | 39,009,967 | <p>For example, I have a string:</p>
<pre class="lang-none prettyprint-override"><code>The struct-of-application and struct-of-world
</code></pre>
<p>With <code>re.sub</code>, it will replace the matched with a predefined string. How can I replace the match with a transformation of the matched content? To get, for example:</p>
<pre class="lang-none prettyprint-override"><code>The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct)
</code></pre>
<p>If I write a simple regex <code>((\w+-)+\w+)</code> and try to use <code>re.sub</code>, it seems I can't use what I matched as part of the replacement, let alone edit the matched content:</p>
<pre class="lang-none prettyprint-override"><code>In [10]: p.sub('struct','The struct-of-application and struct-of-world')
Out[10]: 'The struct and struct'
</code></pre>
| 1 | 2016-08-18T04:22:28Z | 39,010,075 | <p>Try this:</p>
<pre><code>>>> p = re.compile(r"((\w+-)+\w+)")
>>> p.sub('[\\1](http://\\1)','The struct-of-application and struct-of-world')
'The [struct-of-application](http://struct-of-application) and [struct-of-world](http://struct-of-world)'
</code></pre>
| 1 | 2016-08-18T04:34:43Z | [
"python",
"regex"
] |
How to replace an re match with a transformation of that match? | 39,009,967 | <p>For example, I have a string:</p>
<pre class="lang-none prettyprint-override"><code>The struct-of-application and struct-of-world
</code></pre>
<p>With <code>re.sub</code>, it will replace the matched with a predefined string. How can I replace the match with a transformation of the matched content? To get, for example:</p>
<pre class="lang-none prettyprint-override"><code>The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct)
</code></pre>
<p>If I write a simple regex <code>((\w+-)+\w+)</code> and try to use <code>re.sub</code>, it seems I can't use what I matched as part of the replacement, let alone edit the matched content:</p>
<pre class="lang-none prettyprint-override"><code>In [10]: p.sub('struct','The struct-of-application and struct-of-world')
Out[10]: 'The struct and struct'
</code></pre>
| 1 | 2016-08-18T04:22:28Z | 39,010,137 | <p>Use a <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow">function for the replacement</a></p>
<pre><code>s = 'The struct-of-application and struct-of-world'
p = re.compile('((\w+-)+\w+)')
def replace(match):
return 'http://{}'.format(match.group())
>>> p.sub(replace, s)
'The http://struct-of-application and http://struct-of-world'
>>>
</code></pre>
| 2 | 2016-08-18T04:41:50Z | [
"python",
"regex"
] |
How to speed up math operations in Python? | 39,009,986 | <p>I am writing a code in Python in which I am doing a lot of matrix multiplications on huge matrices. For the performance as well as the speed I am using numpy.einsum. Anyways, that einum is optimized very well, my code works very slowly. This is a reason that I'm looking for a solution to speed it up. I thought that PyCuda might have been helpful, but after doing some research on the Internet, I figured out that I was mistaken.
Do you have any tips how to improve performance of math operations Python?</p>
<p>For example I have a bunch of this kind of following multiplications:</p>
<pre><code>NewMatrix_krls = np.einsum('kK,krls->Krls', C, Matrx_krls)
</code></pre>
<p>where C is a matrix 1000 by 1000 and a Matrx_krls is 1000 by 1000 by 1000 by 1000.</p>
| -3 | 2016-08-18T04:24:19Z | 39,011,812 | <p><code>einsum</code> constructs an iterator (<code>ndinter</code>) that loops (in C) over the problem space. With the dimensions and indexes in your expression that space is <code>1000**5</code> (5 variables, each of size 1000). That's <code>10**15</code> operations.</p>
<p>If the problem involved multiplying 3 or 4 arrays, you might speed things up by splitting it into a couple of <code>einsum</code> calls (or a mix of <code>einsum</code> and <code>dot</code>). But there's not enough information in your description to suggest that kind of partitioning.</p>
<p>Actually you might be able to cast this in a form that uses <code>np.dot</code>. <code>Matrx_krls</code> can be reshaped to a 2d array, combining the <code>rls</code> dimensions into one <code>1000**3</code> in size.</p>
<p>E.g. (not tested)</p>
<pre><code>np.dot(C.T, Matrx_krls.reshape(1000,-1))
</code></pre>
<p>For a product of 2 2d arrays, <code>np.dot</code> is faster than <code>einsum</code>.</p>
<p>(Note I changed your tags to include <code>numpy</code> - that will bring it to the attention of more knowledgeable posters).</p>
| 0 | 2016-08-18T07:01:29Z | [
"python",
"performance",
"numpy"
] |
How to speed up math operations in Python? | 39,009,986 | <p>I am writing a code in Python in which I am doing a lot of matrix multiplications on huge matrices. For the performance as well as the speed I am using numpy.einsum. Anyways, that einum is optimized very well, my code works very slowly. This is a reason that I'm looking for a solution to speed it up. I thought that PyCuda might have been helpful, but after doing some research on the Internet, I figured out that I was mistaken.
Do you have any tips how to improve performance of math operations Python?</p>
<p>For example I have a bunch of this kind of following multiplications:</p>
<pre><code>NewMatrix_krls = np.einsum('kK,krls->Krls', C, Matrx_krls)
</code></pre>
<p>where C is a matrix 1000 by 1000 and a Matrx_krls is 1000 by 1000 by 1000 by 1000.</p>
| -3 | 2016-08-18T04:24:19Z | 39,013,856 | <blockquote>
<p>'Matrx_krls is 1000 by 1000 by 1000 by 1000'</p>
</blockquote>
<p>So thats a 4-terabyte array, assuming 4-byte floats... I think you are better off investing time in Hadoop than in GPGPU. Even if you stream that data to a GPU, you will see little benefit because of limited PCIE bandwidth.</p>
<p>That, or perhaps explaining why you think you need this kind of operation might help on a higher level.</p>
| 0 | 2016-08-18T08:54:24Z | [
"python",
"performance",
"numpy"
] |
finding maximum value form csv column | 39,010,023 | <pre><code>dataset=[]
f= open('auto-mpg-data.csv')
csv_f=csv.reader(f)
for row in csv_f:
dataset.append(row)
#reading column
mpg=[]
for row in dataset:
mpg.append(row[0])
print(mpg)
print(max(mpg))
</code></pre>
<p>this is the <a href="http://i.stack.imgur.com/RcGgV.png" rel="nofollow">data</a>. When I try to find the maximum value from this list it show 9 instead of 46.6. How can I get this value?</p>
| 0 | 2016-08-18T04:28:26Z | 39,010,408 | <p>The problem is that the items of the list <code>mpg</code> are strings, so the result is true as '9' is greater than '46.6' when comparing strings. You should convert the items in the list <code>mpg</code> to float numbers first:</p>
<pre><code>mpg = [float(row[0]) for row in dataset]
</code></pre>
| 0 | 2016-08-18T05:12:52Z | [
"python",
"csv"
] |
ValueError: invalid literal for int() with base 10: 'False' | 39,010,059 | <p>Any idea how to fix this issue?</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 1, in <module>
from punchstarter import manager
File "/app/punchstarter/__init__.py", line 29, in <module>
mail = Mail(app)
File "/app/.heroku/python/lib/python2.7/site-packages/flask_mail.py", line 539, in __init__
self.state = self.init_app(app)
File "/app/.heroku/python/lib/python2.7/site-packages/flask_mail.py", line 566, in init_app
state = self.init_mail(app.config, app.debug, app.testing)
File "/app/.heroku/python/lib/python2.7/site-packages/flask_mail.py", line 552, in init_mail
int(config.get('MAIL_DEBUG', debug)),
ValueError: invalid literal for int() with base 10: 'False'
</code></pre>
<p>from my <code>__init__.py</code> line 29:</p>
<pre><code>mail = Mail(app)
</code></pre>
<p>I am running python and I think there is some trouble with the <code>flask_mail</code> configs, but I'm not sure where the problem lies.</p>
| -1 | 2016-08-18T04:33:11Z | 39,492,066 | <p>Set</p>
<pre><code>app.debug = 0
</code></pre>
<p>This worked for me</p>
<pre><code>mail = Mail()
app.debug = 0
mail.init_app(app)
</code></pre>
| 0 | 2016-09-14T13:42:32Z | [
"python",
"flask-mail"
] |
pandas calculate the strangeness of the topic | 39,010,111 | <p>Here is a very short description of my task. I have a dataframe that looks like this: <code>df = pd.DataFrame([[2, 0], [2, 1], [1, 0], [1, 0], [1, 1], [3, 0]], columns=['topic', 'strange'])</code></p>
<p>For every topic, I need to caclulate the percentage of rows that are 'strange'. So the result will be like this <code>1 - 1/3, 2 - 1/2, 3 - 0</code>.</p>
<p>The most efficient solution I have come up with is:</p>
<pre><code>a = df['topic'].value_counts()
b = df[df['strange'] == 1]['topic'].value_counts()
res = (b / a).fillna(0)
</code></pre>
<hr>
<p>Also this is most probably reasonably performant and not that ugly, I believe that this can be achieved easier with a smart groupby operation. </p>
<p>Does anyone have other suggestions? Looking for a shorter or faster alternative.</p>
| 1 | 2016-08-18T04:38:18Z | 39,010,250 | <p>If <code>strange</code> is guaranteed to be 0 or 1 only, you can just take the mean:</p>
<pre><code>In [7]: df.groupby("topic").mean()
Out[7]:
strange
topic
1 0.333333
2 0.500000
3 0.000000
</code></pre>
| 2 | 2016-08-18T04:54:42Z | [
"python",
"pandas"
] |
How to compare multiple files in python and show all the name variations associated with SSN's | 39,010,226 | <p>Filter/sort files to list all names variations associated with each SSN.</p>
<pre><code>Input File1:
SSN, First Name, Last Name
333-22-9898, Tom, Tillman
556-11-7484, Mak, Burhan
333-22-9898, Tom, B Tillman
Input File2:
SSN, First Name, Last Name
857-87-9899, Si, H
Input File 3....
Output File:
333-22-9898, Tom, Tillman
333-22-9898, Tom, B Tillman
556-11-7484, Mak, Burhan
556-11-7484, Mak, Bo
.......and so on....
</code></pre>
| -1 | 2016-08-18T04:51:24Z | 39,050,550 | <p>Solution:</p>
<pre><code>f = open('out.txt', 'w')
# sample data in f1.txt (111-23-9999)
filenames = ["f1.txt", "f2.txt", "f3.txt", "f4.txt"]
files = [open(name) for name in filenames]
sets = [set(line.strip() for line in file)
for file in files]
common = set.union(*sets)
my_list = list(common)
my_list.sort()
print (my_list)
for file in files: file.close()
for line in my_list:
f.write(line+'\n')
f.close()
</code></pre>
| 0 | 2016-08-20T04:42:18Z | [
"python",
"python-3.x"
] |
How to remove the brackets from the list in python | 39,010,420 | <p>I have a list:</p>
<pre><code>list1 = ['field1','field2','field3']
</code></pre>
<p>i have used different methods but i is of no help.</p>
<pre><code>list1= ( " ".join( repr(e) for e in list1) )
</code></pre>
<p>but it is printing each character in the string as seperate word like </p>
<pre><code>"f","i","e","l","d".
</code></pre>
<p>But i want the output like:</p>
<pre><code>list1='field1','field2','field3'
</code></pre>
<p>So how can i remove only the brackets from the list without modifying the strings.</p>
| -3 | 2016-08-18T05:14:06Z | 39,010,545 | <p>I <em>imagine</em> (the question isn't very clear as noted in the comments) you are looking for:</p>
<pre><code>print ",".join(list1)
</code></pre>
<p>Produces:</p>
<pre><code>field1,field2,field3
</code></pre>
<blockquote>
<p>So how can i remove only the brackets from the list without modifying
the strings.</p>
</blockquote>
<p>The variable <code>list1</code> is a list and the <code>[]</code> brackets are included when a list is rendered as a String. You can provide your own string representation as you have here using <code>join</code>. If you really want to product a string output with the quotes around the strings you could do:</p>
<pre><code>print "'" + "','".join(list1) + "'"
</code></pre>
| 0 | 2016-08-18T05:28:03Z | [
"python"
] |
How to remove the brackets from the list in python | 39,010,420 | <p>I have a list:</p>
<pre><code>list1 = ['field1','field2','field3']
</code></pre>
<p>i have used different methods but i is of no help.</p>
<pre><code>list1= ( " ".join( repr(e) for e in list1) )
</code></pre>
<p>but it is printing each character in the string as seperate word like </p>
<pre><code>"f","i","e","l","d".
</code></pre>
<p>But i want the output like:</p>
<pre><code>list1='field1','field2','field3'
</code></pre>
<p>So how can i remove only the brackets from the list without modifying the strings.</p>
| -3 | 2016-08-18T05:14:06Z | 39,010,626 | <p>Tada! <code>str(list1).strip('[').strip(']')</code></p>
<p>Not sure if it is possible to get python to output:</p>
<blockquote>
<p>list1='field1','field2','field3'</p>
</blockquote>
<p>That is not valid python syntax... (unless defining a tuple):</p>
<pre><code>>>>list1='field1','field2','field3'
('field1', 'field2', 'field3')
</code></pre>
<p>This is the closest you can get:</p>
<pre><code>>>>list1 = ['field1','field2','field3']
# convert list to string
>>>foo = str(list1)
# strip the '[ ]'
>>>print(foo.strip('[').strip(']'))
'field1', 'field2', 'field3'
>>>print("list1=%s" % foo.strip('[').strip(']'))
list1='field1', 'field2', 'field3'
</code></pre>
| 0 | 2016-08-18T05:36:07Z | [
"python"
] |
How to remove the brackets from the list in python | 39,010,420 | <p>I have a list:</p>
<pre><code>list1 = ['field1','field2','field3']
</code></pre>
<p>i have used different methods but i is of no help.</p>
<pre><code>list1= ( " ".join( repr(e) for e in list1) )
</code></pre>
<p>but it is printing each character in the string as seperate word like </p>
<pre><code>"f","i","e","l","d".
</code></pre>
<p>But i want the output like:</p>
<pre><code>list1='field1','field2','field3'
</code></pre>
<p>So how can i remove only the brackets from the list without modifying the strings.</p>
| -3 | 2016-08-18T05:14:06Z | 39,010,699 | <p>It sounds like you want to print your list in a specific format. You can do this using the <code>print()</code> function in python3 or the <code>print</code> statement in python2.</p>
<p>First, make a string which represents how you want to output your list:</p>
<pre><code>output = ",".join("'" + item + "'" for item in list1)
</code></pre>
<p>There are two steps in this approach. Firstly, we add quotes to the outside of each item in the list, as per your desired output. Secondly, we join the items in the list around a comma.</p>
<p>If you want to have the string 'list1=' at the beginning of the output you can simply prepend it like this:</p>
<pre><code>output = 'list1=' + output
</code></pre>
<p>Then, can simply print this string using <code>print output</code> in python2 or <code>print(output)</code> in python3.</p>
<p>This should print the following line:</p>
<p><code>list1='field1','field2','field3'</code></p>
| 0 | 2016-08-18T05:43:56Z | [
"python"
] |
How to remove the brackets from the list in python | 39,010,420 | <p>I have a list:</p>
<pre><code>list1 = ['field1','field2','field3']
</code></pre>
<p>i have used different methods but i is of no help.</p>
<pre><code>list1= ( " ".join( repr(e) for e in list1) )
</code></pre>
<p>but it is printing each character in the string as seperate word like </p>
<pre><code>"f","i","e","l","d".
</code></pre>
<p>But i want the output like:</p>
<pre><code>list1='field1','field2','field3'
</code></pre>
<p>So how can i remove only the brackets from the list without modifying the strings.</p>
| -3 | 2016-08-18T05:14:06Z | 39,010,919 | <p>most of the previous answers would work, but perhaps the most simplest one is using a for loop:</p>
<pre><code>mylist = ['1','2','3','4']
print('list=',end='')
for myvar in mylist:
print(myvar,end='')
print('')
</code></pre>
<p>output:</p>
<pre><code>list=1234
</code></pre>
<p>however, this will only work in python 3.4, since you have to use the print function and cannot use a print statement</p>
| 0 | 2016-08-18T06:02:32Z | [
"python"
] |
How to remove the brackets from the list in python | 39,010,420 | <p>I have a list:</p>
<pre><code>list1 = ['field1','field2','field3']
</code></pre>
<p>i have used different methods but i is of no help.</p>
<pre><code>list1= ( " ".join( repr(e) for e in list1) )
</code></pre>
<p>but it is printing each character in the string as seperate word like </p>
<pre><code>"f","i","e","l","d".
</code></pre>
<p>But i want the output like:</p>
<pre><code>list1='field1','field2','field3'
</code></pre>
<p>So how can i remove only the brackets from the list without modifying the strings.</p>
| -3 | 2016-08-18T05:14:06Z | 39,014,945 | <p>Try this :
<code>list1 = "'" + "','".join(list1) + "'"</code></p>
| 0 | 2016-08-18T09:44:53Z | [
"python"
] |
Counting the number of times button is clicked during my program | 39,010,447 | <p>I am doing a program on a class list counter. I have one program, in frame 5 underneath "Population Count" and where it says 0, it is meant to increase by one for every time the button "Add to classlist" is clicked every time. I tried many different methods but all of those I tried never seem to work. It would be appreciative if anyone can help.</p>
<p>Here is my coding so far, the rest I have done for my class list counter </p>
<pre><code>import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation():
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
population = 0
def population(label):
population = 0
def mbutton():
global population
population +=1
label.config(text=str(population))
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
</code></pre>
| 1 | 2016-08-18T05:17:26Z | 39,010,520 | <p>Rather than using a <strong>global</strong> <code>population</code> you need to declare <code>self.population = 0</code> in your <code>__init__</code> method and to increment <code>self.population</code> in your button click handler. It is normally also considered good practice to have a class method to get the value.</p>
| 3 | 2016-08-18T05:24:28Z | [
"python",
"python-3.x",
"tkinter"
] |
Counting the number of times button is clicked during my program | 39,010,447 | <p>I am doing a program on a class list counter. I have one program, in frame 5 underneath "Population Count" and where it says 0, it is meant to increase by one for every time the button "Add to classlist" is clicked every time. I tried many different methods but all of those I tried never seem to work. It would be appreciative if anyone can help.</p>
<p>Here is my coding so far, the rest I have done for my class list counter </p>
<pre><code>import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation():
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
population = 0
def population(label):
population = 0
def mbutton():
global population
population +=1
label.config(text=str(population))
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
</code></pre>
| 1 | 2016-08-18T05:17:26Z | 39,016,244 | <p><strong>Possible solution</strong>: if all you want to do is, have the population count, and increment it on each button click:</p>
<pre><code>import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation():
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
# population = 0
self.population = 0 # made it a class attr
# def population(label):
# population = 0
def add_population(self):
# having it separate can help in modification or enhancement
self.population +=1
def mbutton():
# global population
# population +=1
self.add_population() # increment
label.config(text=str(population))
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
</code></pre>
<hr>
<p><strong>Edit 1</strong>: I have added the complete code, with my suggested changes - previous statements are commented, so you know the changes.</p>
| 1 | 2016-08-18T10:47:58Z | [
"python",
"python-3.x",
"tkinter"
] |
How to share raw input given in one file with another file in python | 39,010,472 | <p>I want raw input given in one file to be used in another file.
For this I defined all variables in a <code>global_dec.py</code> file . Then modified the value of these variables in <code>main_file.py</code> and when I got printed these variables in another file <code>partfile.py</code> then variables having integer and string value got modified but the raw input is not giving value given in <code>main_fily.py</code></p>
<p>Code is as follow:</p>
<p>global_dec.py: </p>
<pre><code> class common(object):
a=0
x="x inside global class "
y=raw_input(" enter input for the global class: ")
</code></pre>
<p>main_file.py:</p>
<pre><code> from global_dec import common
common.x = " x changed inside main file "
common.a=1
def dummy():
print "dummy"
def main():
print " main"
if __name__ == '__main__':
main()
</code></pre>
<p>partfile.py:</p>
<pre><code> from global_dec import common
def main():
print "x: "+common.x, " y: "+common.y, " a: "+str(common.a)
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-08-18T05:19:27Z | 39,010,701 | <p>If I am interpreting your question right you want to be able to do the following...</p>
<pre><code>$ python main_file.py
enter input for the global class: something
main
$ python partfile.py
enter input for the global class: something else
x: x inside global class y: something else a: 0
</code></pre>
<p>If that is the case it is not possible because the python process ends and all values that are stored in memory for the app are thrown away. Change your <code>main</code> function in <code>main_file.py</code> to be exactly like the one in <code>partfile.py</code> and you will see that even the <code>x</code> and <code>a</code> values may change but they do not persist. The only way to have persistent data between running python processes is to use a database.</p>
<p>Probably a better way of showing this would be for your <code>main_file.py</code> to look like so...</p>
<pre><code>from global_dec import common
common.x = 'i have changed'
common.a += 1
def main():
print "x: " + common.x + " a: " + str(common.a) + " y: " + common.y
</code></pre>
<p>Then run it twice and it should look like this.</p>
<pre><code>$ python main_file.py
enter input for the global class: blah
x: I have changed a: 1 y: blah
$ python main_file.py
enter input for the global class: blah
x: I have changed a: 1 y: blah
</code></pre>
<p>Notice <code>a</code> will always be 1 since when it is imported at the beginning of the process it is 0 then is incremented to 1 and when the process finishes the variable is dumped from memory. I hope that helps</p>
| 0 | 2016-08-18T05:44:02Z | [
"python"
] |
Confidence in OpenCV FaceRecognizer predict method output | 39,010,477 | <p>I am using OpenCV for face recognition and have a newbie question.
Here is a portion of my code:</p>
<pre><code>recognizer = cv2.createLBPHFaceRecognizer()
...
nbr_predicted, confidence = recognizer.predict(predict_image)
...
</code></pre>
<p>My question is the higher the <strong>confidence</strong> is means faces are more similar or less similar?</p>
| 0 | 2016-08-18T05:20:11Z | 39,046,368 | <p>There is an implementation about face recognition wich you can read <a href="https://github.com/ragulin/face-recognition-server" rel="nofollow">here</a>.
They use OpenCV with face module.</p>
<p>In their read me there is an explanation about project and they say that confidence was more similiar when the number is lower. And vice-versa.</p>
<p>I have been studying about cv2.face with eigenfaces and fisherfaces and I received numbers around 10000 in my predictions but with LBPH I could predict with distance of 60~80.</p>
<p>Do you have any project about LBPH to share?</p>
| 1 | 2016-08-19T19:24:01Z | [
"python",
"opencv",
"face-recognition"
] |
Get file details in python | 39,010,497 | <p>I'm trying to extract the details of a file using Python. Specifically, when I right click a photo and select properties, under the Details tab of the menu that pops up, there's a whole bunch of details about the file. What I really need is the contents of the "People" detail.</p>
<p>This is the menu in question:</p>
<p><img src="http://i.stack.imgur.com/Agpot.png"></p>
<p>Is there a good way of getting that People detail in a string or something?</p>
<p>Some people have suggested using ExifRead. I tried that, but it didn't pull the People tag out of the Exif data.</p>
| 2 | 2016-08-18T05:22:28Z | 39,061,309 | <p>This is not EXIF data but rather data that Windows populates for different types of objects in the Windows Property System.</p>
<p>The one you are concerned with is called <a href="https://msdn.microsoft.com/en-us/library/dd391582(v=vs.85).aspx" rel="nofollow"><code>System.Photo.PeopleNames</code></a>:</p>
<pre><code>propertyDescription
name = System.Photo.PeopleNames
shellPKey = PKEY_Photo_PeopleNames
formatID = E8309B6E-084C-49B4-B1FC-90A80331B638
propID = 100
searchInfo
inInvertedIndex = true
isColumn = true
isColumnSparse = true
columnIndexType = OnDemand
maxSize = 128
mnemonics = people|people tag|people tags
labelInfo
label = People
sortDescription
invitationText = Add a people tag
hideLabel = false
typeInfo
type = String
groupingRange = Discrete
isInnate = true
canBePurged = true
multipleValues = true
isGroup = false
aggregationType = Union
isTreeProperty = false
isViewable = true
isQueryable (Vista) = false
includeInFullTextQuery (Vista) = false
searchRawValue (Windows 7) = true
conditionType = String
defaultOperation = Equal
aliasInfo
sortByAlias = None
additionalSortByAliases = None
displayInfo
defaultColumnWidth = 11
displayType = String
alignment = Left
relativeDescriptionType = General
defaultSortDirection = Ascending
stringFormat
formatAs = General
booleanFormat
formatAs = YesNo
numberFormat
formatAs = General
formatDurationAs = hh:mm:ss
dateTimeFormat
formatAs = General
formatTimeAs = ShortTime
formatDateAs = ShortDate
enumeratedList
defaultText
useValueForDefault = False
enum
value
text
enumRange
minValue
setValue
text
drawControl
control = Default
editControl
control = Default
filterControl
control = Default
queryControl
control = Default
</code></pre>
<p>To access this information in Python, use <code>win32com.propsys</code>.</p>
| 0 | 2016-08-21T06:04:09Z | [
"python",
"file",
"photo",
"details"
] |
Jupyter Notebook - Matplotlib keep running | 39,010,594 | <p>I just started to use <code>Jupiter Notebook</code> to learn <code>Python</code>. while I am trying out <code>matplotlib</code> with this basic code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
</code></pre>
<p>The kernel just keep running and nothing happen. How to resolve this? Is there an dependency issue? My newly installed <code>matplotlib</code> is 1.5.1, <code>python</code> is 3.5.2, <code>numpy</code> is 1.11. Running on MacBook Pro 10.11(El Capitan).</p>
| 0 | 2016-08-18T05:33:54Z | 39,010,693 | <p>It likely showed you a Matplotlib popup, with the IP(y) logo. To show it inline you have to use some IPython magic. Run this in a cell somewhere:</p>
<pre><code>%matplotlib inline
</code></pre>
<p>After you close the popup it will finish the statement in your kernel</p>
| 0 | 2016-08-18T05:43:33Z | [
"python",
"numpy",
"matplotlib",
"ipython",
"jupyter-notebook"
] |
Jupyter Notebook - Matplotlib keep running | 39,010,594 | <p>I just started to use <code>Jupiter Notebook</code> to learn <code>Python</code>. while I am trying out <code>matplotlib</code> with this basic code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
</code></pre>
<p>The kernel just keep running and nothing happen. How to resolve this? Is there an dependency issue? My newly installed <code>matplotlib</code> is 1.5.1, <code>python</code> is 3.5.2, <code>numpy</code> is 1.11. Running on MacBook Pro 10.11(El Capitan).</p>
| 0 | 2016-08-18T05:33:54Z | 39,010,728 | <p>To Visualize the plots created by the matplotlib in <strong>Jupiter Notebook or ipython notebook</strong> you have add one extra line at the beginning.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
</code></pre>
<p>If your matplotlib <strong>version is above 1.4, and you are using IPython 3.x</strong> you have to use the below code.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
</code></pre>
| 2 | 2016-08-18T05:46:27Z | [
"python",
"numpy",
"matplotlib",
"ipython",
"jupyter-notebook"
] |
Jupyter Notebook - Matplotlib keep running | 39,010,594 | <p>I just started to use <code>Jupiter Notebook</code> to learn <code>Python</code>. while I am trying out <code>matplotlib</code> with this basic code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
</code></pre>
<p>The kernel just keep running and nothing happen. How to resolve this? Is there an dependency issue? My newly installed <code>matplotlib</code> is 1.5.1, <code>python</code> is 3.5.2, <code>numpy</code> is 1.11. Running on MacBook Pro 10.11(El Capitan).</p>
| 0 | 2016-08-18T05:33:54Z | 39,010,809 | <p>It sometimes takes time until the kernel starts.</p>
<p>Check that the code is color-highlighted. If it is, it means that the kernel is running. Evaluate the cell again. You will notice a <code>*</code> beside that cell, meaning it's running. </p>
<p>And one more thing: Sometimes the plot is displayed but its window hides behind the notebook... Access it from the task bar</p>
| 0 | 2016-08-18T05:54:19Z | [
"python",
"numpy",
"matplotlib",
"ipython",
"jupyter-notebook"
] |
Django 1.8 No module named front | 39,010,599 | <p>Here is my project folder structure.</p>
<pre><code><pre>
front
âââ __init__.py
âââ __init__.pyc
âââ manage.py
âââ middleware.py
âââ settings.py
âââ news
â  âââ __init__.py
â  âââ __init__.pyc
â  âââ admin.py
â  âââ admin_views.py
â  âââ models.py
â  âââ search_indexes.py
â  âââ search_sites.py
â  âââ utils.py
â  âââ views.py
</pre>
</code></pre>
<p>After I run </p>
<pre><code>./manage.py runserver
</code></pre>
<p>then I visit <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a></p>
<p>It gives me error:</p>
<pre><code>No module named front
</code></pre>
<p>This is caused by the following line in file views.py under news folder. </p>
<pre><code>from front import settings
</code></pre>
<p>So the front folder is one level up to the views.py file. How I import the settings from one level up folder?</p>
<p>Thanks!</p>
| 0 | 2016-08-18T05:34:22Z | 39,011,378 | <p>Either way this is wrong, whenever you're importing your own settings you should be importing from <code>django.conf</code></p>
<pre><code>from django.conf import settings
</code></pre>
<p>This isn't a module, its an object that does magic to import any settings you have set in your <code>DJANGO_SETTINGS_MODULE</code></p>
<p>From the <a href="https://docs.djangoproject.com/en/1.10/topics/settings/#using-settings-in-python-code" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Also note that your code should not import from either global_settings or your own settings file. django.conf.settings abstracts the concepts of default settings and site-specific settings; it presents a single interface. It also decouples the code that uses settings from the location of your settings.</p>
</blockquote>
| 4 | 2016-08-18T06:34:07Z | [
"python",
"django"
] |
Pandas: Adding two dataframes on the common columns | 39,010,614 | <p>I have 2 tables which have the same columns and I want to add the numbers where the key matches, and if it doesn't then just add it as is in the output df.. I tried combine first, merge, concat and join.. They all create 2 seperate columnd for t1 and t2, but its the same key, so should just be together I know this would be something very basic.. pls could someone help? thanks vm!</p>
<pre><code> df1:
t1 a b
0 USD 2,877 -2,418
1 CNH 600 -593
2 AUD 756 -106
3 JPY 113 -173
4 XAG 8 0
df2:
t2 a b
0 CNH 64 -44
1 USD 756 -774
2 JPY 1,127 -2,574
3 TWO 56 -58
4 TWD 38 -231
Output:
t a b
USD 3,634 -3,192
CNH 664 -637
AUD 756 -106
JPY 1,240 -2,747
XAG 8 0
TWO 56 -58
TWD 38 -231
</code></pre>
| 2 | 2016-08-18T05:35:29Z | 39,010,650 | <p>First <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> in both <code>DataFrames</code> by first columns and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow"><code>add</code></a> with parameter <code>fill_value=0</code>:</p>
<pre><code>print (df1.set_index('t1').add(df2.set_index('t2'), fill_value=0)
.reset_index()
.rename(columns={'index':'t'}))
t a b
0 AUD 756.0 -106.0
1 CNH 664.0 -637.0
2 JPY 1240.0 -2747.0
3 TWD 38.0 -231.0
4 TWO 56.0 -58.0
5 USD 3633.0 -3192.0
6 XAG 8.0 0.0
</code></pre>
<p>If need convert output to <code>int</code>:</p>
<pre><code>print (df1.set_index('t1').add(df2.set_index('t2'), fill_value=0)
.astype(int)
.reset_index()
.rename(columns={'index':'t'}))
t a b
0 AUD 756 -106
1 CNH 664 -637
2 JPY 1240 -2747
3 TWD 38 -231
4 TWO 56 -58
5 USD 3633 -3192
6 XAG 8 0
</code></pre>
| 3 | 2016-08-18T05:38:55Z | [
"python",
"pandas",
"dataframe",
"add",
"multiple-columns"
] |
How to implement single logger in python for two scripts one defining the workflow and one containing all functions? | 39,010,659 | <p>I have two python scripts one as workflow.py and other is task.py. The workflow.py defines the workflow of the task.py and thus it has only main inside it in which it instantiate the constructor of task.py. The structure of worflow.py is as follows:</p>
<pre><code>workflow.py
from optparse import OptionParser
from optparse import OptionGroup
from task import *
def main():
dir = os.path.dirname(os.path.abspath(sys.argv[0]))
try:
parser = parse_options(parser, dir)
(options, args) = parser.parse_args()
print ("everything working fine in workflow")
except SystemExit:
return 0
task_object = task_C(options.source_dir, options.target, options.build_dir)
print ("workflow is reached")
task_object.another_funct()
##following 3 lines is when set_logger is defined
log = task_object .set_logger()
log.info(""workflow is reached"")
log.info("more info if required")
def parser(parser, dir):
group = OptionGroup(parser, "Prepare")
group.add_option("-t", "--target",action="store", dest="target",
help="Specifies the target.")
group.add_option("-s", "--Source",action="store", dest="source_dir",
help="Specifies the source dir.")
group.add_option("-b", "--build",action="store", dest="build_dir",
help="Specifies the build dir.")
parser.add_option_group(group)
task.py
class task_C():
def __init__(self, source_dir, target, build_dir):
self.target = self.settargetplatform(target)
self.source_dir = self.setsourcedir(source_dir)
self.build_dir = self.setbuilddir(build_dir)
def settargetplatform( target):
...sets target dir
def setsourcedir(source_dir ):
...sets source_dir
def setbuilddir(build_dir):
..sets build_dir
def another_funct( ):
print ("inside the another funct")
print ("some usefull info")
print ("...")
##following part after adding set_logger then using logger
log = self.set_logger()
log.info( "inside the another funct")
log.info( " some usefull info")
log.info ("...")
.
def set_logger(self):
logging.basicConfig()
l = logging.getLogger('root')
l.setLevel(logging.DEBUG)
formatter = logging.Formatter(' %(levelname)s : %(message)s')
fileHandler = logging.FileHandler(self.build_dir+"/root.log", mode='w')
fileHandler.setFormatter(formatter)
l.addHandler(fileHandler)
</code></pre>
<p>Now, as in the above script it is shown that the task.py constructor is invoked inside the workflow and there are various print statements in both script, i would like to have a logger instead of the print statements and for that purpose i want to place the log inside the location "build_dir" but that location is set inside the task.py and i don't want to add another function inside workflow.py which retrieve back the 'build_dir'. I added set_logger() function inside task.py as you can see in the task.py which could serve my purpose but the log i am getting contains all NULL NULL NULL...so on. So, suggest me how can i have one log containing all print statements in these two script and what improvements do i need to make?</p>
| 1 | 2016-08-18T05:40:08Z | 39,010,861 | <p>I think I would define logger inside <code>workflow.py</code> and pass it as a parameter into the constructor of <code>task_C</code>. That would seem to be the easiest solution.</p>
| 0 | 2016-08-18T05:57:37Z | [
"python",
"python-2.7",
"logging"
] |
How to implement single logger in python for two scripts one defining the workflow and one containing all functions? | 39,010,659 | <p>I have two python scripts one as workflow.py and other is task.py. The workflow.py defines the workflow of the task.py and thus it has only main inside it in which it instantiate the constructor of task.py. The structure of worflow.py is as follows:</p>
<pre><code>workflow.py
from optparse import OptionParser
from optparse import OptionGroup
from task import *
def main():
dir = os.path.dirname(os.path.abspath(sys.argv[0]))
try:
parser = parse_options(parser, dir)
(options, args) = parser.parse_args()
print ("everything working fine in workflow")
except SystemExit:
return 0
task_object = task_C(options.source_dir, options.target, options.build_dir)
print ("workflow is reached")
task_object.another_funct()
##following 3 lines is when set_logger is defined
log = task_object .set_logger()
log.info(""workflow is reached"")
log.info("more info if required")
def parser(parser, dir):
group = OptionGroup(parser, "Prepare")
group.add_option("-t", "--target",action="store", dest="target",
help="Specifies the target.")
group.add_option("-s", "--Source",action="store", dest="source_dir",
help="Specifies the source dir.")
group.add_option("-b", "--build",action="store", dest="build_dir",
help="Specifies the build dir.")
parser.add_option_group(group)
task.py
class task_C():
def __init__(self, source_dir, target, build_dir):
self.target = self.settargetplatform(target)
self.source_dir = self.setsourcedir(source_dir)
self.build_dir = self.setbuilddir(build_dir)
def settargetplatform( target):
...sets target dir
def setsourcedir(source_dir ):
...sets source_dir
def setbuilddir(build_dir):
..sets build_dir
def another_funct( ):
print ("inside the another funct")
print ("some usefull info")
print ("...")
##following part after adding set_logger then using logger
log = self.set_logger()
log.info( "inside the another funct")
log.info( " some usefull info")
log.info ("...")
.
def set_logger(self):
logging.basicConfig()
l = logging.getLogger('root')
l.setLevel(logging.DEBUG)
formatter = logging.Formatter(' %(levelname)s : %(message)s')
fileHandler = logging.FileHandler(self.build_dir+"/root.log", mode='w')
fileHandler.setFormatter(formatter)
l.addHandler(fileHandler)
</code></pre>
<p>Now, as in the above script it is shown that the task.py constructor is invoked inside the workflow and there are various print statements in both script, i would like to have a logger instead of the print statements and for that purpose i want to place the log inside the location "build_dir" but that location is set inside the task.py and i don't want to add another function inside workflow.py which retrieve back the 'build_dir'. I added set_logger() function inside task.py as you can see in the task.py which could serve my purpose but the log i am getting contains all NULL NULL NULL...so on. So, suggest me how can i have one log containing all print statements in these two script and what improvements do i need to make?</p>
| 1 | 2016-08-18T05:40:08Z | 39,015,779 | <blockquote>
<p>actually that can be done but the point is in that case log location
has to be defined in workflow.py and i don't want to define location
there as it is already defined in task.py. In workflow i don't want to
define the same location for logger which is already set in task.py</p>
</blockquote>
<p>As per your above comment -
Then you can call your <code>set_logger()</code> in <code>worker.py</code> and pass it to <code>task.py</code> i.e. have the following lines in <code>worker.py</code>: </p>
<pre><code>task_object = task_C(options.source_dir, options.target, options.build_dir)
log = task_object .set_logger()
</code></pre>
<p>For any call to task methods, pass the logger (methods must accept it as param) - for example:</p>
<pre><code>task_object.another_funct(log=log)
</code></pre>
<hr>
<p>For logging not working properly - add <code>return l</code> at the end of <code>set_logger()</code> in <code>task.py</code></p>
| 1 | 2016-08-18T10:25:30Z | [
"python",
"python-2.7",
"logging"
] |
Can't figure out errors during c++ python binding using Boost | 39,010,721 | <p>I am creating a Qt based app that requires python code to be run from it. For this, I am using Boost.Python. The error I have is: </p>
<pre><code>CMakeFiles/App.dir/main.cpp.o: In function `_GLOBAL__sub_I_main.cpp':
main.cpp:(.text.startup+0x3): undefined reference to `_Py_NoneStruct'
collect2: error: ld returned 1 exit status
make[2]: *** [source/App] Error 1
make[1]: *** [source/CMakeFiles/App.dir/all] Error 2
make: *** [all] Error 2
11:12:47: The process "/usr/local/bin/cmake" exited with code 2.
Error while building/deploying project App (kit: Desktop Qt 5.7.0 GCC 64bit)
When executing step "Make"
</code></pre>
<p>I am sure the error is linking error, but I cant figure out how to remove it. I have just started using cmake and am not proficient at it.
The code is here :
<code>https://github.com/daemonSlayer/App</code></p>
<p>What should I change in the code to make it work?</p>
<p>Edit:
<br>
[/root] CMakeLists.txt:</p>
<pre><code>cmake_minimum_required(VERSION 3.3)
# Default configuration values. These must be before the project command or
# they won't work in Windows.
# If no build type is specified, default to "Release"
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING
"None Debug Release RelWithDebInfo MinSizeRel"
FORCE)
endif()
# Install to "dist" directory in Windows for testing and as a staging directory
# for the installer.
if (WIN32 AND NOT CMAKE_INSTALL_PREFIX)
set(CMAKE_INSTALL_PREFIX dist CACHE STRING "Install path prefix.")
endif()
project(App)
set(PROJECT_LONGNAME "DeepLearningApp")
set(PROJECT_VERSION "0.0.1")
# Global CMake options
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
# Configure Qt
find_package(Qt5Widgets REQUIRED)
find_package(Qt5Test REQUIRED)
# Configure Boost
find_package(python)
find_package(Boost REQUIRED)
if (NOT MSVC)
# Enable the C++11 standard
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++11)
endif()
# Testing configuration
enable_testing()
set(TEST_LINK_LIBRARIES Qt5::Test)
add_subdirectory(source)
add_subdirectory(tests)
if (WIN32)
</code></pre>
<p>[/root/source] CMakeLists.txt:</p>
<pre><code>configure_file(${CMAKE_CURRENT_SOURCE_DIR}/defines.h.cmake
${CMAKE_CURRENT_BINARY_DIR}/defines.h)
file(GLOB_RECURSE UI_FILES *.ui)
file(GLOB_RECURSE CODE_FILES *.cpp)
qt5_wrap_ui(UI_HEADERS ${UI_FILES})
qt5_add_resources(RESOURCE_FILES ../resources/resources.qrc)
# Windows application icon
if (WIN32)
set(WINDOWS_RES_FILE ${CMAKE_CURRENT_BINARY_DIR}/resources.obj)
if (MSVC)
add_custom_command(OUTPUT ${WINDOWS_RES_FILE}
COMMAND rc.exe /fo ${WINDOWS_RES_FILE} resources.rc
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/win
)
else()
add_custom_command(OUTPUT ${WINDOWS_RES_FILE}
COMMAND windres.exe resources.rc ${WINDOWS_RES_FILE}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/win
)
endif()
endif()
add_executable(${CMAKE_PROJECT_NAME} WIN32
${UI_HEADERS}
${CODE_FILES}
${RESOURCE_FILES}
${WINDOWS_RES_FILE}
)
target_link_libraries(${CMAKE_PROJECT_NAME}
Qt5::Widgets
)
# Configure Python
find_package( PythonLibs 2.7 REQUIRED )
include_directories( ${PYTHON_INCLUDE_DIRS} )
# Configure Boost
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})
target_link_libraries(${CMAKE_PROJECT_NAME}
${Boost_LIBRARIES})
if (UNIX)
install(TARGETS ${CMAKE_PROJECT_NAME}
RUNTIME DESTINATION bin)
elseif (WIN32)
install(TARGETS ${CMAKE_PROJECT_NAME}
DESTINATION .)
endif()
add_subdirectory(win)
endif()
</code></pre>
| 0 | 2016-08-18T05:46:09Z | 39,011,538 | <p>It seems that you are not linking with the required Python libraries. Try adding <code>${PYTHON_LIBRARIES$} to</code>target_link_libraries`:</p>
<pre><code>target_link_libraries(${CMAKE_PROJECT_NAME}
${PYTHON_LIBRARIES}
)
</code></pre>
| -1 | 2016-08-18T06:44:41Z | [
"python",
"c++",
"qt",
"boost"
] |
python, how to handle event between multiple windows? | 39,010,886 | <p>I'm using the following sample code to generate two windows:</p>
<pre><code>import Tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def new_window(self):
print 1
self.newWindow = tk.Toplevel(self.master)
print 2
self.app = Demo2(self.newWindow)
print 3
class Demo2:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
<p>I expect "1" (or maybe "2") to be printed, when <code>new_window()</code> method is called. I expect "3" to be printed when <code>Demo2</code> was closed!
But by pressing <code>button1</code> I got all three print statements executed.
How can I han handle that?</p>
| -1 | 2016-08-18T06:00:19Z | 39,012,049 | <p>You may use <code>wait_window</code> method to wait for the second window to be destroyed before proceeding to the next statement in the first window.</p>
<p>I have modified your code to make it work. Hope it helps -</p>
<pre><code>import Tkinter as tk
class Demo1(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def new_window(self):
print 1
# self.newWindow = tk.Toplevel(self.master)
print 2
self.app = Demo2(self).display_window()
print 3
class Demo2:
def __init__(self, master):
self.master = tk.Toplevel(master)
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.master.destroy)
self.quitButton.pack()
self.frame.pack()
def display_window(self):
self.master.wait_window()
return 0
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
| 2 | 2016-08-18T07:15:37Z | [
"python",
"user-interface",
"tkinter"
] |
pip cant install radiopy | 39,010,960 | <p>I've tried
<code>pip install radiopy</code></p>
<p><em>Traceback:</em></p>
<pre><code>C:\Users\олег\Downloads>pip install radiopy
Collecting radiopy
Using cached radio
py-0.6.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\29F0~1\AppData\Local\Temp\pip-build-blxa2oob\radiopy\setup.py, line 23, in <module>
version=get_version('radio.py'),
File "C:\Users\29F0~1\AppData\Local\Temp\pip-build-blxa2oob\radiopy\setup.py
return __version__
NameError: name '__version__' is not defined
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in
C:\Users\29F0~1\AppData\Local\Temp\pip-build-blxa2oob\radiopy\
</code></pre>
<p>I've also tried:<br>
<code>easy_install radiopy</code></p>
<p><em>Traceback:</em></p>
<pre><code>File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 168, in save_modules
saved_exc.resume()
File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 143, in resume
six.reraise(type, exc, self._tb)
File "c:\python34\lib\site-packages\pkg_resources\_vendor\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 156, in save_modules
yield saved
File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 197, in setup_context yield
File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 246, in run_setup
DirectorySandbox(setup_dir).run(runner)
File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 276, in run return func()
File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 245, in runner
_execfile(setup_script, ns)
File "c:\python34\lib\site-packages\setuptools\sandbox.py", line 47, in _execfile
exec(code, globals, locals)
File "C:\Users\29F0~1\AppData\Local\Temp\easy_install-laprrvio\radiopy-0.6\setup.py", line 23, in <module>
File "C:\Users\29F0~1\AppData\Local\Temp\easy_install-laprrvio\radiopy-0.6\setup.py", line 19, in get_version
NameError: name '__version__' is not defined
</code></pre>
<p>Lately,<br>
<code>C:\Users\олег>pip install C:\\Users\\олег\\Downloads\\radiopy-0.6.tar.gz</code></p>
<p><em>Traceback:</em></p>
<pre><code>C:\Users\олег>pip install C:\\Users\\олег\\Downloads\\radiopy-0.6.tar.gz
Processing c:\users\олег\downloads\radiopy-0.6.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\29F0~1\AppData\Local\Temp\pip-8evw0uk0-build\setup.py", line 23, in <module>
version=get_version('radio.py'),
File "C:\Users\29F0~1\AppData\Local\Temp\pip-8evw0uk0-build\setup.py", line 19, in get_version
return __version__
NameError: name '__version__' is not defined
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\29F0~1\AppData\Local\Temp\pip-8evw0uk0-build\
</code></pre>
<p>How can I solve this?</p>
| 0 | 2016-08-18T06:05:32Z | 39,011,153 | <p>The module seems to support Python 2 only. The <code>setup.py</code> contains a very dubious hack to evaluate the <code>__version__</code> variable:</p>
<pre><code>def get_version(filename):
"""Extract __version__ from file by parsing it."""
with open(filename) as fp:
for line in fp:
if line.startswith('__version__'):
exec(line)
return __version__
</code></pre>
<p>What this does is to find a line that starts with <code>__version__</code>, namely <code>__version__ = '0.6'</code>, and then execute it as dynamic code with <code>exec</code>, which works. However in Python 3 this <em>doesn't</em> modify local variables and thus <code>__version__</code> is not defined on the next line.</p>
<p>Even if you fixed this bug, you'd met a countless others as the package is not Python-3-ready at all. The easiest solution would be to use Python 2. But even then I am not too sure if this works correctly on Windows as it is written for the <code>mplayer</code>/<code>mencoder</code> suite, and seems to be very Linux/POSIX minded in its code.</p>
| 0 | 2016-08-18T06:19:44Z | [
"python",
"install",
"pip"
] |
Django avatar class not work | 39,011,004 | <p>In django-avatar I want to add a custom CSS class using the template tag, but it's not working.</p>
<p>My template:</p>
<pre><code>{% load avatar_tags %}
<li>
<span class="userhome">
{% avatar user 50 class="mmb-img" id="user_avatar" %}
Welcome : {{ user.username }}
</span>
</li>
</code></pre>
<p>The rendered HTML is:</p>
<pre><code><li>
<span class="userhome">
<img src="https://www.gravatar.com/avatar/4bbcb352e5bdbe63fe8f9a5786ea9d69/?s=50" alt="cpoudevigne" width="50" height="50">
Welcome : cpoudevigne
</span>
</li>
</code></pre>
<p>The custom class does not appear. What is the problem?</p>
| 0 | 2016-08-18T06:09:17Z | 39,011,315 | <p>This is probably because the app <a href="http://django-avatar.readthedocs.io/en/latest/#global-settings" rel="nofollow">caches the output of those template tags</a>:</p>
<blockquote>
<p><code>AVATAR_CACHE_ENABLED</code></p>
<p>Set to <code>False</code> if you completely disable avatar caching. Defaults to <code>True</code>.</p>
</blockquote>
<p>Either change the <code>AVATAR_CACHE_ENABLED</code> setting or clear your cache.</p>
| 2 | 2016-08-18T06:29:55Z | [
"python",
"css",
"django",
"avatar"
] |
Django avatar class not work | 39,011,004 | <p>In django-avatar I want to add a custom CSS class using the template tag, but it's not working.</p>
<p>My template:</p>
<pre><code>{% load avatar_tags %}
<li>
<span class="userhome">
{% avatar user 50 class="mmb-img" id="user_avatar" %}
Welcome : {{ user.username }}
</span>
</li>
</code></pre>
<p>The rendered HTML is:</p>
<pre><code><li>
<span class="userhome">
<img src="https://www.gravatar.com/avatar/4bbcb352e5bdbe63fe8f9a5786ea9d69/?s=50" alt="cpoudevigne" width="50" height="50">
Welcome : cpoudevigne
</span>
</li>
</code></pre>
<p>The custom class does not appear. What is the problem?</p>
| 0 | 2016-08-18T06:09:17Z | 39,117,006 | <p>Same issue here, unable to set neither class="" nor id="".</p>
<p>No idea what's going on, so temporarily I can only set it via JavaScript/JQuery.</p>
<p>JQuery:</p>
<pre><code>$(function() {$("span.userhome img").addClass("img-responsive")});
</code></pre>
| 0 | 2016-08-24T07:30:09Z | [
"python",
"css",
"django",
"avatar"
] |
How to change dictionary that one key has multiple values to dataframe? | 39,011,022 | <p>I have a dictionary <code>self._alpha_series</code>.</p>
<p>I use <code>pd.DataFrame.from_dict(self._alpha_series.items())</code>,</p>
<p>It will become below:</p>
<p><a href="http://i.stack.imgur.com/StlhT.png" rel="nofollow"><img src="http://i.stack.imgur.com/StlhT.png" alt="enter image description here"></a></p>
<p>How to change dataframe like:</p>
<p><a href="http://i.stack.imgur.com/9kaBg.png" rel="nofollow"><img src="http://i.stack.imgur.com/9kaBg.png" alt="enter image description here"></a></p>
| 0 | 2016-08-18T06:10:59Z | 39,011,207 | <p>IIUC you can use:</p>
<pre><code>print (df)
0 1
0 1101.TW (nan, nan)
1 2227.TW (nan, 100.5)
2 2887.TW (nan, 24.7)
df[[1,2]] = pd.DataFrame.from_records(df.ix[:,1].values.tolist())
print (df)
0 1 2
0 1101.TW NaN NaN
1 2227.TW NaN 100.5
2 2887.TW NaN 24.7
</code></pre>
| 1 | 2016-08-18T06:23:37Z | [
"python",
"pandas",
"dictionary"
] |
Why does the local_binary_pattern function in scikit-image provide same value for different patterns | 39,011,167 | <p>I am using the <code>local_binary_pattern</code> function in the scikit-image package. I would like to compute the rotation invariant uniform LBP of 8 neighbors within radius 1. Here is my Python code:</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
from skimage.feature import local_binary_pattern
image = np.array([[150, 137, 137, 146, 146, 148],
[145, 144, 144, 144, 142, 144],
[149, 144, 144, 143, 153, 147],
[145, 144, 147, 150, 145, 150],
[146, 146, 139, 148, 144, 148],
[129, 139, 142, 150, 146, 140]]).astype(np.uint8)
lbp = local_binary_pattern(image, 8, 1, "uniform")
print "image ="
print image
print "lbp ="
print lbp
</code></pre>
<p>And here is the output</p>
<pre><code>image =
[[150 137 137 146 146 148]
[145 144 144 144 142 144]
[149 144 144 143 153 147]
[145 144 147 150 145 150]
[146 146 139 148 144 148]
[129 139 142 150 146 140]]
lbp =
[[ 0. 5. 5. 1. 9. 0.]
[ 9. 6. 9. 9. 8. 9.]
[ 0. 8. 6. 8. 0. 3.]
[ 9. 7. 1. 0. 7. 0.]
[ 1. 1. 8. 9. 7. 1.]
[ 3. 4. 9. 0. 2. 3.]]
</code></pre>
<p>What confuses me is that some same values in <code>lbp</code> do not correspond to the same uniform pattern. E.g., <code>lbp[1,1]</code> and <code>lbp[2,2]</code> are both 6. But the LBP of <code>image[1,1]</code> is </p>
<pre><code>1 0 0
1 x 1
1 1 1
</code></pre>
<p>The LBP of <code>image[2,2]</code> is </p>
<pre><code>1 1 1
1 x 0
1 1 1
</code></pre>
<p>, where based on the values in <code>lbp</code>, I assume the <code>local_binary_pattern</code> function uses 'greater or equal to' to compare with neighbors.</p>
<p>The LBPs of <code>image[2,2]</code> and <code>image[2,2]</code> are both uniform. But how could <code>image[1,1]</code> and <code>image[2,2]</code> have the same LBP value?</p>
| 2 | 2016-08-18T06:20:23Z | 39,017,137 | <p>The rotation-invariant LBP does not use the pixel values of neighbors directly, but rather values interpolated on a circle (for the rotation invariance). See <a href="https://github.com/scikit-image/scikit-image/blob/master/skimage/feature/_texture.pyx#L156" rel="nofollow">https://github.com/scikit-image/scikit-image/blob/master/skimage/feature/_texture.pyx#L156</a></p>
<p>Also see the original LBP paper <a href="http://vision.stanford.edu/teaching/cs231b_spring1415/papers/lbp.pdf" rel="nofollow">http://vision.stanford.edu/teaching/cs231b_spring1415/papers/lbp.pdf</a>, which mentions "The gray values of neighbors which do not fall
exactly in the center of pixels are estimated by interpolation."</p>
| 1 | 2016-08-18T11:32:51Z | [
"python",
"feature-extraction",
"scikit-image"
] |
How do I 'squash' the values in a DataFrame that I know only has one item per row into a Series? | 39,011,192 | <p>I have a DataFrame which I have confirmed has no more than one value in each row (the rest are np.nan). How can I turn this into a one-dimensional array or Series?</p>
<p>Say this is my starting array:</p>
<pre><code>In [7]: import pandas as pd
In [8]: data = [
[np.nan, 9.0, np.nan],
[np.nan, np.nan, 3.0],
[np.nan, np.nan, 5.0],
[np.nan, np.nan, np.nan],
[1.0, np.nan, np.nan]
]
In [9]: a = pd.DataFrame(data)
In [10]: a
Out[10]:
0 1 2
0 NaN 9.0 NaN
1 NaN NaN 3.0
2 NaN NaN 5.0
3 NaN NaN NaN
4 1.0 NaN NaN
</code></pre>
<p>And I want to create the following Series b:</p>
<pre><code>In [17]: b
Out[17]:
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
dtype: float64
</code></pre>
<p>I've written some code to do it:</p>
<pre><code>In [14]: m = a.notnull()
In [15]: m
Out[15]:
0 1 2
0 False True False
1 False False True
2 False False True
3 False False False
4 True False False
In [16]: for i, row in a.iterrows():
for j, v in row.iteritems():
if m.iloc[i, j]:
b[i] = v
</code></pre>
<p>But there must be an easier way!</p>
<p>I tried using <code>np.max</code> and <code>np.sum</code> but they both return an empty (nan) array.</p>
| 1 | 2016-08-18T06:22:19Z | 39,011,358 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html" rel="nofollow"><code>first_valid_index</code></a>, but need condition if all values are <code>NaN</code>:</p>
<pre><code>def f(x):
if x.first_valid_index() is None:
return None
else:
return x[x.first_valid_index()]
b = a.apply(f, axis=1)
print (b)
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
dtype: float64
</code></pre>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a> and <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>print (pd.Series(np.where(a.notnull().any(1), a.sum(1), np.nan)))
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
dtype: float64
</code></pre>
<p>Solution with <code>np.max</code> works nice also:</p>
<pre><code>print (np.max(a, axis=1))
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
dtype: float64
</code></pre>
<p>Or simplier and fastest only <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.max.html" rel="nofollow"><code>max</code></a>:</p>
<pre><code>print (a.max(axis=1))
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
dtype: float64
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>a = pd.concat([a]*10000).reset_index(drop=True)
In [133]: %timeit (a.max(axis=1))
100 loops, best of 3: 2.81 ms per loop
In [134]: %timeit (np.max(a, axis=1))
100 loops, best of 3: 2.83 ms per loop
In [135]: %timeit (pd.Series(np.where(a.notnull().any(1), a.sum(1), np.nan)))
100 loops, best of 3: 3.18 ms per loop
In [136]: %timeit (a.apply(f, axis=1))
1 loop, best of 3: 2.18 s per loop
#http://stackoverflow.com/a/39011722/2901002
In [137]: %timeit a.max(axis=1, skipna=True)
100 loops, best of 3: 2.84 ms per loop
</code></pre>
<hr>
<pre><code>def user(dataDF):
squash = pd.Series(index=dataDF.index)
for col in dataDF.columns.values:
squash.update(dataDF[col])
return squash
print(user(a))
In [151]: %timeit (user(a))
100 loops, best of 3: 7.75 ms per loop
</code></pre>
<p>EDIT by comment:</p>
<p>If values are not numeric, you can use:</p>
<pre><code>import pandas as pd
import numpy as np
data = [
[np.nan, 'a', np.nan],
[np.nan, np.nan, 'b'],
[np.nan, np.nan, 'c'],
[np.nan, np.nan, np.nan],
['d', np.nan, np.nan]
]
a = pd.DataFrame(data)
print (a)
0 1 2
0 NaN a NaN
1 NaN NaN b
2 NaN NaN c
3 NaN NaN NaN
4 d NaN NaN
print (a.fillna('').sum(axis=1).mask(a.isnull().all(1)))
0 a
1 b
2 c
3 NaN
4 d
dtype: object
</code></pre>
| 2 | 2016-08-18T06:32:46Z | [
"python",
"pandas",
"dataframe",
null,
"series"
] |
How do I 'squash' the values in a DataFrame that I know only has one item per row into a Series? | 39,011,192 | <p>I have a DataFrame which I have confirmed has no more than one value in each row (the rest are np.nan). How can I turn this into a one-dimensional array or Series?</p>
<p>Say this is my starting array:</p>
<pre><code>In [7]: import pandas as pd
In [8]: data = [
[np.nan, 9.0, np.nan],
[np.nan, np.nan, 3.0],
[np.nan, np.nan, 5.0],
[np.nan, np.nan, np.nan],
[1.0, np.nan, np.nan]
]
In [9]: a = pd.DataFrame(data)
In [10]: a
Out[10]:
0 1 2
0 NaN 9.0 NaN
1 NaN NaN 3.0
2 NaN NaN 5.0
3 NaN NaN NaN
4 1.0 NaN NaN
</code></pre>
<p>And I want to create the following Series b:</p>
<pre><code>In [17]: b
Out[17]:
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
dtype: float64
</code></pre>
<p>I've written some code to do it:</p>
<pre><code>In [14]: m = a.notnull()
In [15]: m
Out[15]:
0 1 2
0 False True False
1 False False True
2 False False True
3 False False False
4 True False False
In [16]: for i, row in a.iterrows():
for j, v in row.iteritems():
if m.iloc[i, j]:
b[i] = v
</code></pre>
<p>But there must be an easier way!</p>
<p>I tried using <code>np.max</code> and <code>np.sum</code> but they both return an empty (nan) array.</p>
| 1 | 2016-08-18T06:22:19Z | 39,011,722 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow"><code>pd.DataFrame.max</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>pd.DataFrame.sum</code></a> with the <code>skipna</code> value set to <code>True</code>:</p>
<blockquote>
<p><strong>skipna</strong>: boolean, default True; Exclude NA/null values. If an entire row/column is NA, the result will be NA</p>
</blockquote>
<p>So, you should try</p>
<pre><code>a.max(axis=1, skipna=True)
</code></pre>
| 2 | 2016-08-18T06:56:10Z | [
"python",
"pandas",
"dataframe",
null,
"series"
] |
How do I 'squash' the values in a DataFrame that I know only has one item per row into a Series? | 39,011,192 | <p>I have a DataFrame which I have confirmed has no more than one value in each row (the rest are np.nan). How can I turn this into a one-dimensional array or Series?</p>
<p>Say this is my starting array:</p>
<pre><code>In [7]: import pandas as pd
In [8]: data = [
[np.nan, 9.0, np.nan],
[np.nan, np.nan, 3.0],
[np.nan, np.nan, 5.0],
[np.nan, np.nan, np.nan],
[1.0, np.nan, np.nan]
]
In [9]: a = pd.DataFrame(data)
In [10]: a
Out[10]:
0 1 2
0 NaN 9.0 NaN
1 NaN NaN 3.0
2 NaN NaN 5.0
3 NaN NaN NaN
4 1.0 NaN NaN
</code></pre>
<p>And I want to create the following Series b:</p>
<pre><code>In [17]: b
Out[17]:
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
dtype: float64
</code></pre>
<p>I've written some code to do it:</p>
<pre><code>In [14]: m = a.notnull()
In [15]: m
Out[15]:
0 1 2
0 False True False
1 False False True
2 False False True
3 False False False
4 True False False
In [16]: for i, row in a.iterrows():
for j, v in row.iteritems():
if m.iloc[i, j]:
b[i] = v
</code></pre>
<p>But there must be an easier way!</p>
<p>I tried using <code>np.max</code> and <code>np.sum</code> but they both return an empty (nan) array.</p>
| 1 | 2016-08-18T06:22:19Z | 39,014,167 | <p>I would make use of the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.update.html" rel="nofollow">update()</a> function. For a variable number of columns:</p>
<pre><code>dataDF = pd.DataFrame(data)
squash = pd.Series(index=dataDF.index)
for col in dataDF.columns.values:
squash.update(dataDF[col])
print (squash)
0 9.0
1 3.0
2 5.0
3 NaN
4 1.0
Name: 0, dtype: float64
</code></pre>
| 1 | 2016-08-18T09:09:54Z | [
"python",
"pandas",
"dataframe",
null,
"series"
] |
python getpass module is not taking German characters as input | 39,011,208 | <p>I am trying to enter password having German characters using python <strong>getpass</strong> module on Windows 7. Python version is 2.7.8</p>
<ul>
<li>First I set the system locale as German(Germany) and reboot.</li>
<li>The command prompt codepage is now set to cp850 which supports German characters.</li>
<li><p>Then I execute getpass in command prompt as follows : </p>
<blockquote>
<blockquote>
<blockquote>
<p>pwd = getpass.getpass()</p>
</blockquote>
</blockquote>
</blockquote>
<pre><code>Password:
</code></pre>
<blockquote>
<blockquote>
<blockquote>
<p>print pwd</p>
</blockquote>
</blockquote>
</blockquote></li>
<li><p>I had input ö as password and printing it gives me nothing. This is confirmed by printing the length of the password which is 0.</p></li>
</ul>
<p>The same is working with Chinese, Japanese and Korean characters when I set the corresponding locale.</p>
<p>I have the same thing with python 2.3.5 and same issue persists. </p>
<p>Please let me know if I am doing something wrong?</p>
| 1 | 2016-08-18T06:23:40Z | 39,037,079 | <p>I was entering the German character (ö) by typing following : alt + 0246.
But typing the same character directly from the German keyboard (semi-colon ';' on American keyboard) is working fine.</p>
<p>However, still I am confused as to what is the difference between above two.
Maybe alt code characters are in a different encoding than what is given by sys.stdin.encoding!!!</p>
| 0 | 2016-08-19T10:45:15Z | [
"python",
"getpasswd"
] |
Python randomly stops writing to csv, but for loop is still running | 39,011,235 | <p>I am trying to fetch data from Last.fm, and write these data to a CSV file. I have a.csv, and based on each line of this a.csv, I fetch additional data from Last.fm, then save them to b.csv. So as a result, a.csv and b.csv are of the same size.</p>
<p>a.csv is a large text file with about 8 million data lines, so I am trying to run multiple processes that each process about 250,000 lines.</p>
<p>I tried with the python multiprocessing module, and I also tried running multiple terminals. The problem is that most of the time (about 9 out of 10 or more), the processes randomly stop writing to each CSV file.</p>
<p>For example, I start running 4 processes, and they will normally start writing to separate CSV files. Then when random time passes, few of the CSV files won't be modified anymore. Sometimes one of the CSV will stop right after (a few minutes or so) I start running the process, and other csvs also stop after a few hours, or a few decimal hours. These patterns are totally random, and very rarely, all the processes will finish successfully, which is why I cannot figure out the reason they keep stopping. I tried on other computers and there is no difference, so the problem doesn't seem computing resource-dependent.</p>
<p>Also, even though the CSV files stop being modified, the process is still running, as I made the code print its progress to the terminal every 1000 data lines. </p>
<p>Following is the overall structure of my code (I just wrote the codes that I thought is indispensable to understand the program, in abstracted form):</p>
<pre><code>f_reader = csv.reader(f, delimeter=',')
# (same for other csv files needed ..)
for line in a.csv:
if 1000 data lines are processed:
print('1000 tracks processed')
url = Lastfm API root url + selective data in line
req = urllib2.Request(url)
response = urllib2.urlopen(req) # fetch data from Last.fm and save result to req
info = etree.fromstring(response.read())
temp1 = info.find('data1').text.encode('utf-8')
temp2 = info.find('data2').text.encode('utf-8')
temp = [temp1, temp2]
for column in temp:
f.write('%s;' % column)
f.write('\n')
f.close()
</code></pre>
<p><strong>Can anyone help?</strong></p>
| 0 | 2016-08-18T06:25:11Z | 39,011,981 | <p>Try adding a <code>f.flush()</code> call somewhere, for instance, in your 1000 lines checkpoint. Maybe the files are just being buffered, and not getting written to disk. For example, see <a href="http://stackoverflow.com/questions/3167494/how-often-does-python-flush-to-a-file">How often does python flush to a file?</a> </p>
| 0 | 2016-08-18T07:11:51Z | [
"python",
"file",
"csv",
"multiprocessing",
"python-multiprocessing"
] |
python function error : Type Error | 39,011,363 | <p>hi im fairly new to python and cant spot my error in this program, my error looks like this</p>
<blockquote>
<p>TypeError: hitormiss() missing 1 required positional argument:
'totalaim'</p>
</blockquote>
<pre><code>#!usr/bin/python3
import random
def takeshot(prompt='do you want to take shot?\n'):
answer = input(prompt)
if answer == ['yes', 'y']:
print("taking shot...")
else:
print("not-working")
def cal(randomnum = random.randrange(0, 100) , baseaim = 15):
totalaim = randomnum + baseaim
return totalaim
def hitormiss(totalaim, hit=50):
if totalaim >= hit:
print("You have hit your target!")
elif totalaim < hit:
print("You have missed your target!")
else:
print("Revise Code.")
takeshot()
cal()
hitormiss()
</code></pre>
<p>Is totalaim not already declared in cal?</p>
| -1 | 2016-08-18T06:32:49Z | 39,011,405 | <p>You should remove the <code>cal()</code> and <code>hitormiss()</code> function call and replace it with:</p>
<pre><code>hitormiss(cal())
</code></pre>
<p>This is because a parameter has to be passed to <code>hitormiss()</code> and <code>cal()</code> returns the <code>totalaim</code> value.</p>
| 0 | 2016-08-18T06:36:05Z | [
"python",
"python-3.x"
] |
python function error : Type Error | 39,011,363 | <p>hi im fairly new to python and cant spot my error in this program, my error looks like this</p>
<blockquote>
<p>TypeError: hitormiss() missing 1 required positional argument:
'totalaim'</p>
</blockquote>
<pre><code>#!usr/bin/python3
import random
def takeshot(prompt='do you want to take shot?\n'):
answer = input(prompt)
if answer == ['yes', 'y']:
print("taking shot...")
else:
print("not-working")
def cal(randomnum = random.randrange(0, 100) , baseaim = 15):
totalaim = randomnum + baseaim
return totalaim
def hitormiss(totalaim, hit=50):
if totalaim >= hit:
print("You have hit your target!")
elif totalaim < hit:
print("You have missed your target!")
else:
print("Revise Code.")
takeshot()
cal()
hitormiss()
</code></pre>
<p>Is totalaim not already declared in cal?</p>
| -1 | 2016-08-18T06:32:49Z | 39,011,472 | <p>Also, <code>cal.totalaim</code> won't resolve in the way you're planning</p>
<pre><code>def hitormiss(totalaim, hit=50):
if totalaim >= hit:
print("You have hit your target!")
elif totalaim < hit:
print("You have missed your target!")
else:
print("Revise Code.")
</code></pre>
<p>And then call, as suggested</p>
<pre><code>takeshot()
hitormiss(cal())
</code></pre>
| 0 | 2016-08-18T06:40:49Z | [
"python",
"python-3.x"
] |
How to use some field instead of primary keys in Django 1.6 model fixtures? | 39,011,469 | <p>I need to dump and load fixtures of model objects without usage of primary keys. The model is flat. I know about natural keys in Django, spent a lot of time reading the documentation, but all documentation has solutions only for usage natural keys instead of relations (fk / m2m). This is totally not what I need.</p>
<p>I need something like this:</p>
<p>(models.py)</p>
<pre><code>class Template(models.Model):
name = models.CharField(_('name'), max_length=100)
content = models.TextField(_('content'), blank=True)
def natural_key(self):
return (self.name,)
</code></pre>
<p>(fixture1.json)</p>
<pre><code>[
{
"pk": null,
"model": "dbtemplates.Template",
"fields" {
"content": "",
"name": "product"
}
}
]
</code></pre>
<p>And after command</p>
<pre><code>./manage.py <SOME_LOADDATA_COMMAND> fixture1.json --natural
</code></pre>
<p>I need to update my Template object which has name "product" or insert it.</p>
<p>The standard Django commands don't do this. Please, help me with any solution. Maybe there are some libraries for this? I'm confusing.</p>
<p>Django 1.6. Python 2.7</p>
| 1 | 2016-08-18T06:40:42Z | 39,012,174 | <p>Django 1.6 does not provide a way to dump data with natural primary keys, but Django 1.7 does. </p>
<ul>
<li>Django 1.6 docs: <a href="https://docs.djangoproject.com/en/1.7/ref/django-admin/#dumpdata-app-label-app-label-app-label-model" rel="nofollow">https://docs.djangoproject.com/en/1.7/ref/django-admin/#dumpdata-app-label-app-label-app-label-model</a></li>
<li>Django 1.7 docs (note the <code>--natural-primary</code> option): <a href="https://docs.djangoproject.com/en/1.7/ref/django-admin/#dumpdata-app-label-app-label-app-label-model" rel="nofollow">https://docs.djangoproject.com/en/1.7/ref/django-admin/#dumpdata-app-label-app-label-app-label-model</a></li>
</ul>
<p>Unfortunately, the <code>use_natural_primary_keys</code> keyword argument is not supported by the base Django 1.6 serializer: <a href="https://github.com/django/django/blob/1.6.11/django/core/serializers/base.py#L20" rel="nofollow">https://github.com/django/django/blob/1.6.11/django/core/serializers/base.py#L20</a></p>
<p>So I suggest you either upgrade to django 1.7 (which I totally understand is not always possible) or you write your own serializer, drawing inspiration from the base Django 1.7 serializer (<a href="https://github.com/django/django/blob/1.7.11/django/core/serializers/base.py" rel="nofollow">https://github.com/django/django/blob/1.7.11/django/core/serializers/base.py</a>).</p>
| 3 | 2016-08-18T07:22:39Z | [
"python",
"django",
"django-fixtures"
] |
How to use some field instead of primary keys in Django 1.6 model fixtures? | 39,011,469 | <p>I need to dump and load fixtures of model objects without usage of primary keys. The model is flat. I know about natural keys in Django, spent a lot of time reading the documentation, but all documentation has solutions only for usage natural keys instead of relations (fk / m2m). This is totally not what I need.</p>
<p>I need something like this:</p>
<p>(models.py)</p>
<pre><code>class Template(models.Model):
name = models.CharField(_('name'), max_length=100)
content = models.TextField(_('content'), blank=True)
def natural_key(self):
return (self.name,)
</code></pre>
<p>(fixture1.json)</p>
<pre><code>[
{
"pk": null,
"model": "dbtemplates.Template",
"fields" {
"content": "",
"name": "product"
}
}
]
</code></pre>
<p>And after command</p>
<pre><code>./manage.py <SOME_LOADDATA_COMMAND> fixture1.json --natural
</code></pre>
<p>I need to update my Template object which has name "product" or insert it.</p>
<p>The standard Django commands don't do this. Please, help me with any solution. Maybe there are some libraries for this? I'm confusing.</p>
<p>Django 1.6. Python 2.7</p>
| 1 | 2016-08-18T06:40:42Z | 39,020,378 | <p>Based on the <a href="/a/39012174/1911913">answer of régis-b</a> I wrote some code that allows use natural keys in Django 1.6 "loaddata" management command <strong>without upgrade to 1.7</strong>. I chose this way because a full upgrading of my project may be painful. This solution can be considered as a temporary.</p>
<p><strong>tree structure:</strong></p>
<pre><code>âââ project_main_app
â  âââ __init__.py
â  âââ backports
â  â  âââ __init__.py
â  â  âââ django
â  â  âââ __init__.py
â  â  âââ deserializer.py
â  âââ monkey.py
</code></pre>
<p><strong>project_main_app/backports/django/deserializer.py</strong></p>
<pre><code>from __future__ import unicode_literals
from django.conf import settings
from django.core.serializers import base
from django.core.serializers.python import _get_model
from django.db import models, DEFAULT_DB_ALIAS
from django.utils.encoding import smart_text
from django.utils import six
def Deserializer(object_list, **options):
"""
Deserialize simple Python objects back into Django ORM instances.
It's expected that you pass the Python objects themselves (instead of a
stream or a string) to the constructor
"""
db = options.pop('using', DEFAULT_DB_ALIAS)
ignore = options.pop('ignorenonexistent', False)
models.get_apps()
for d in object_list:
# Look up the model and starting build a dict of data for it.
Model = _get_model(d["model"])
data = {Model._meta.pk.attname: Model._meta.pk.to_python(d.get("pk", None))}
m2m_data = {}
model_fields = Model._meta.get_all_field_names()
# Handle each field
for (field_name, field_value) in six.iteritems(d["fields"]):
if ignore and field_name not in model_fields:
# skip fields no longer on model
continue
if isinstance(field_value, str):
field_value = smart_text(field_value, options.get("encoding", settings.DEFAULT_CHARSET), strings_only=True)
field = Model._meta.get_field(field_name)
# Handle M2M relations
if field.rel and isinstance(field.rel, models.ManyToManyRel):
if hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
def m2m_convert(value):
if hasattr(value, '__iter__') and not isinstance(value, six.text_type):
return field.rel.to._default_manager.db_manager(db).get_by_natural_key(*value).pk
else:
return smart_text(field.rel.to._meta.pk.to_python(value))
else:
m2m_convert = lambda v: smart_text(field.rel.to._meta.pk.to_python(v))
m2m_data[field.name] = [m2m_convert(pk) for pk in field_value]
# Handle FK fields
elif field.rel and isinstance(field.rel, models.ManyToOneRel):
if field_value is not None:
if hasattr(field.rel.to._default_manager, 'get_by_natural_key'):
if hasattr(field_value, '__iter__') and not isinstance(field_value, six.text_type):
obj = field.rel.to._default_manager.db_manager(db).get_by_natural_key(*field_value)
value = getattr(obj, field.rel.field_name)
# If this is a natural foreign key to an object that
# has a FK/O2O as the foreign key, use the FK value
if field.rel.to._meta.pk.rel:
value = value.pk
else:
value = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
data[field.attname] = value
else:
data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
else:
data[field.attname] = None
# Handle all other fields
else:
data[field.name] = field.to_python(field_value)
# The key block taken from Django 1.7 sources
obj = build_instance(Model, data, db)
yield base.DeserializedObject(obj, m2m_data)
# This is also taken from Django 1.7 sources
def build_instance(Model, data, db):
"""
Build a model instance.
If the model instance doesn't have a primary key and the model supports
natural keys, try to retrieve it from the database.
"""
obj = Model(**data)
if (obj.pk is None and hasattr(Model, 'natural_key') and
hasattr(Model._default_manager, 'get_by_natural_key')):
natural_key = obj.natural_key()
try:
obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*natural_key).pk
except Model.DoesNotExist:
pass
return obj
</code></pre>
<p><strong>project_main_app/monkey.py</strong></p>
<pre><code>def patch_all():
import django.core.serializers.python
import project_main_app.backports.django.deserializer
# Patch the Deserializer
django.core.serializers.python.Deserializer = project_main_app.backports.django.deserializer.Deserializer
</code></pre>
<p><strong>project_main_app/init.py</strong></p>
<pre><code>from project_main_app.monkey import patch_all
patch_all()
</code></pre>
<p>So after this I just add some things and my model becomes like</p>
<pre><code>class TemplateManager(models.Manager):
"""1"""
def get_by_natural_key(self, name):
return self.get(name=name)
class Template(models.Model):
name = models.CharField(_('name'), max_length=100)
content = models.TextField(_('content'), blank=True)
objects = TemplateManager() # 2
def natural_key(self):
"""3"""
return (self.name,)
</code></pre>
<p>and if fixtures has an empty pk like</p>
<pre><code>[
{
"pk": null,
"model": "dbtemplates.Template",
"fields": {
"content": "Some content",
"name": "product"
}
}
]
</code></pre>
<p>the standard command <strong>./manage.py loaddata dbtemplates.Template</strong> updates or inserts object matching by <strong>name</strong> field.</p>
<p><strong>Warning</strong>: all of natural key components (like a "name" in my case) must have unique values in the database. The proper way is to set them unique by adding the argument "unique=True" when defining a model.</p>
| 0 | 2016-08-18T14:07:52Z | [
"python",
"django",
"django-fixtures"
] |
Pandas expand rows from list data available in column | 39,011,511 | <p>I have a data frame like this in pandas:</p>
<pre><code> column1 column2
[a,b,c] 1
[d,e,f] 2
[g,h,i] 3
</code></pre>
<h1><strong>Expected output:</strong></h1>
<pre><code>column1 column2
a 1
b 1
c 1
d 2
e 2
f 2
g 3
h 3
i 3
</code></pre>
<p>How to process this data ? </p>
| 1 | 2016-08-18T06:42:41Z | 39,011,596 | <p>You can create <code>DataFrame</code> by its constructor and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p>
<pre><code> df2 = pd.DataFrame(df.column1.tolist(), index=df.column2)
.stack()
.reset_index(level=1, drop=True)
.reset_index(name='column1')[['column1','column2']]
print (df2)
column1 column2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 2
6 g 3
7 h 3
8 i 3
</code></pre>
<p>If need change ordering by subset <code>[['column1','column2']]</code>, you can also omit first <code>reset_index</code>:</p>
<pre><code>df2 = pd.DataFrame(df.column1.tolist(), index=df.column2)
.stack()
.reset_index(name='column1')[['column1','column2']]
print (df2)
column1 column2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 2
6 g 3
7 h 3
8 i 3
</code></pre>
<p>Another solution <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow"><code>DataFrame.from_records</code></a> for creating <code>DataFrame</code> from first column, then create <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a> to original <code>DataFrame</code>:</p>
<pre><code>df = pd.DataFrame({'column1': [['a','b','c'],['d','e','f'],['g','h','i']],
'column2':[1,2,3]})
a = pd.DataFrame.from_records(df.column1.tolist())
.stack()
.reset_index(level=1, drop=True)
.rename('column1')
print (a)
0 a
0 b
0 c
1 d
1 e
1 f
2 g
2 h
2 i
Name: column1, dtype: object
print (df.drop('column1', axis=1)
.join(a)
.reset_index(drop=True)[['column1','column2']])
column1 column2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 2
6 g 3
7 h 3
8 i 3
</code></pre>
| 1 | 2016-08-18T06:48:34Z | [
"python",
"list",
"pandas",
"dataframe",
"expand"
] |
Hide button if access rights in Accounting and Finance = Invoicing & Payments | 39,011,714 | <p>I am trying to hide the button 'Refund Invoice' found in Accounting->Customer Invoices & Customer Refunds</p>
<p><a href="http://i.stack.imgur.com/gEgym.png" rel="nofollow"><img src="http://i.stack.imgur.com/gEgym.png" alt="enter image description here"></a></p>
<p>If the user's access rights in Accounting and Finance = Invoicing & Payments. Except on administrator.</p>
<p><a href="http://i.stack.imgur.com/pFqEU.png" rel="nofollow"><img src="http://i.stack.imgur.com/pFqEU.png" alt="enter image description here"></a></p>
<p>Is that possible ?
If yes, then how ?</p>
<p>Thanks,</p>
| 0 | 2016-08-18T06:55:43Z | 39,012,267 | <p>You have to extend/override the invoice formular view. You can set groups directly on fields or buttons, which will show these things only to member of these groups. You will find an example <a href="https://github.com/OCA/account-invoicing/blob/9.0/stock_picking_invoicing/stock_view.xml" rel="nofollow">here</a> where of course need to change something to set a group. For this example changing the group would be like:</p>
<pre class="lang-xml prettyprint-override"><code><button name="%(stock.act_stock_return_picking)d" position="attributes">
<attribute name="groups">base.group_system</attribute>
</button>
</code></pre>
| 1 | 2016-08-18T07:28:14Z | [
"python",
"openerp",
"openerp-7"
] |
Softlayer - Running Jumpgate | 39,011,757 | <p>Fist question, somebody knows if the Jumpgate project still active? I see that the last activity was in 2014.</p>
<p>Second,
I tried to install Jumpgate using the steps in this article [<a href="http://bodenr.blogspot.jp/2014/03/managing-openstack-softlayer-resources.html]" rel="nofollow">http://bodenr.blogspot.jp/2014/03/managing-openstack-softlayer-resources.html]</a> however when running the following line</p>
<pre><code>sudo python setup.py install
</code></pre>
<p>An error is generated</p>
<blockquote>
<p>error: Installed distribution pbr 0.11.1 conflicts with requirement pbr>=1.6</p>
</blockquote>
<p>I think the problem is because the version of the packages referenced have changed.</p>
<p>Does somebody knows how to install jumpgate successfully with the current (2016/08) python packages ?</p>
<p>This is the list of my python packages:</p>
<pre><code>Babel (2.3.4)
backports.ssl-match-hostname (3.4.0.2)
click (6.6)
configobj (4.7.2)
Cython (0.24.1)
debtcollector (1.8.0)
decorator (3.4.0)
falcon (0.1.8)
funcsigs (1.0.2)
gunicorn (18.0)
iniparse (0.4)
iso8601 (0.1.11)
jumpgate (0.1)
keystoneauth1 (2.11.1)
monotonic (1.2)
msgpack-python (0.4.8)
netaddr (0.7.18)
netifaces (0.10.4)
oslo.config (1.5.0)
oslo.i18n (3.8.0)
oslo.serialization (2.13.0)
oslo.utils (3.16.0)
pbr (0.11.1)
perf (0.1)
pip (8.1.2)
positional (1.1.1)
prettytable (0.7.2)
prompt-toolkit (1.0.6)
py2-ipaddress (3.4.1)
pycrypto (2.6.1)
pycurl (7.19.0)
Pygments (2.1.3)
pygobject (3.14.0)
pygpgme (0.3)
pyliblzma (0.5.3)
pyparsing (2.1.8)
python-mimeparse (1.5.2)
python-novaclient (5.0.1.dev33)
pytz (2016.6.1)
pyudev (0.15)
pyxattr (0.5.1)
requests (2.11.1)
rfc3986 (0.3.1)
setuptools (0.9.8)
simplejson (3.8.2)
six (1.10.0)
slip (0.4.0)
slip.dbus (0.4.0)
SoftLayer (5.1.0)
stevedore (1.17.0)
urlgrabber (3.10)
wcwidth (0.1.7)
wheel (0.29.0)
wrapt (1.10.8)
yum-metadata-parser (1.1.4)
</code></pre>
<p>Thank you</p>
<p>--</p>
<p>Let me update the question:</p>
<p>After installing the dependencies</p>
<pre><code>cd /usr/local/jumpgate && sudo pip install -r tools/requirements.txt
</code></pre>
<p>I had to rollback oslo.config and falcon to previous version</p>
<pre><code>sudo pip install -U oslo.config==1.5.0
sudo pip install -U falcon==0.1.8
</code></pre>
<p>Now I'm able to install Jumpgate and run it.</p>
<pre><code>gunicorn "jumpgate.wsgi:make_api()" --bind="localhost:5000" --timeout=600 --access-logfile="-" -w 4
</code></pre>
<p>Continuing with the @bolden Blog I installed nova client OpenStack and configure the global variables to match SoftLayer account</p>
<pre><code>export OS_AUTH_URL=http://127.0.0.1:5000/v2.0
export OS_PASSWORD=xyz
export OS_TENANT_ID=SL9999999
export OS_USERNAME=SoftLayerUserName
</code></pre>
<p>Next I tried to execute the test</p>
<pre><code>nova --debug availability-zone-list
</code></pre>
<p>And I get the following error:</p>
<p><strong>Server side:</strong></p>
<p>REQ: GET /v2.0 {} [ReqId: req-9b0e1fe0-6536-11e6-818f-525400b263eb]
UNKNOWN PATH: GET /v2.0
RESP: GET /v2.0 501 Not Implemented [ReqId: req-9b0e1fe0-6536-11e6-818f-525400b263eb]</p>
<p>127.0.0.1 - - [18/Aug/2016:20:26:28 +0900] "GET /v2.0 HTTP/1.1" 501 95 "-" "nova keystoneauth1/2.11.1 python-requests/2.9.1 CPython/2.7.5"
REQ: POST /v2.0/tokens {} [ReqId: req-9b0f926c-6536-11e6-818f-525400b263eb]
RESP: POST /v2.0/tokens 401 Unauthorized [ReqId: req-9b0f926c-6536-11e6-818f-525400b263eb]</p>
<p>127.0.0.1 - - [18/Aug/2016:20:26:29 +0900] "POST /v2.0/tokens HTTP/1.1" 401 100 "-" "nova keystoneauth1/2.11.1 python-requests/2.9.1 CPython/2.7.5"</p>
<p><strong>Nova</strong></p>
<p>DEBUG (session:337) REQ: curl -g -i -X GET http:// 127.0.0.1:5000/v2.0 -H "Accept: application/json" -H "User-Agent: nova keystoneauth1/2.11.1 python-requests/2.9.1 CPython/2.7.5"</p>
<p>INFO (connectionpool:207) Starting new HTTP connection (1): 127.0.0.1</p>
<p>DEBUG (connectionpool:387) "GET /v2.0 HTTP/1.1" 501 95</p>
<p>DEBUG (session:366) RESP: [501] content-length: 95 x-compute-request-id: req-9b0e1fe0-6536-11e6-818f-525400b263eb Server: gunicorn/19.6.0 Connection: close Date: Thu, 18 Aug 2016 11:26:28 GMT content-type: application/json
RESP BODY: {"notImplemented": {"message": "Not Implemented", "code": "501", "details": "Not Implemented"}}</p>
<p>DEBUG (session:569) Request returned failure status: 501</p>
<p>WARNING (base:122) Discovering versions from the identity service failed when creating the password plugin. Attempting to determine version from URL.</p>
<p>DEBUG (v2:63) Making authentication request to http ://127.0.0.1:5000/v2.0/tokens</p>
<p>INFO (connectionpool:242) Resetting dropped connection: 127.0.0.1</p>
<p>DEBUG (connectionpool:387) "POST /v2.0/tokens HTTP/1.1" 401 100</p>
<p>DEBUG (session:569) Request returned failure status: 401</p>
<p>DEBUG (shell:984) Unauthorized (HTTP 401)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/novaclient/shell.py", line 982, in main
OpenStackComputeShell().main(argv)
...
File "/usr/lib/python2.7/site-packages/keystoneauth1/session.py", line 570, in request
raise exceptions.from_response(resp, method, url)
Unauthorized: Unauthorized (HTTP 401)
ERROR (Unauthorized): Unauthorized (HTTP 401)</p>
<p>My questions:</p>
<p>1 - Is the Unauthorized message comming from SoftLayer or from Jumpgate ?</p>
<p>2 - Is the default SoftLayer end point valid? [/etc/jumpgate/jumpgate.conf]</p>
<pre><code>endpoint = https://api.softlayer.com/xmlrpc/v3/
</code></pre>
<p>Any idea is appreciated.</p>
<p>Thank you</p>
| 0 | 2016-08-18T06:59:11Z | 39,019,622 | <p>I've never installed jumpgate before, but I was able to install it.</p>
<p>At firts I got a similar error like you got, but I fix it installing all the needed pakages using pip.</p>
<pre><code>sudo pip install falcon
sudo pip install requests
sudo pip install six
sudo pip install oslo.config
sudo pip install softlayer
sudo pip install pycrypto
sudo pip install iso8601
</code></pre>
<p>and then I ran:</p>
<pre><code>sudo python setup.py install
</code></pre>
<p>And it installed successfully.</p>
<p>The list of packages installed are:</p>
<pre><code>falcon (1.0.0)
requests (2.9.1)
six (1.10.0)
oslo.config (3.15.0)
softlayer (4.1.1)
pycrypto (2.4.1)
iso8601 (0.1.11)
</code></pre>
<p>I hope it helps</p>
<p>Regards</p>
| 0 | 2016-08-18T13:33:27Z | [
"python",
"openstack",
"softlayer"
] |
Softlayer - Running Jumpgate | 39,011,757 | <p>Fist question, somebody knows if the Jumpgate project still active? I see that the last activity was in 2014.</p>
<p>Second,
I tried to install Jumpgate using the steps in this article [<a href="http://bodenr.blogspot.jp/2014/03/managing-openstack-softlayer-resources.html]" rel="nofollow">http://bodenr.blogspot.jp/2014/03/managing-openstack-softlayer-resources.html]</a> however when running the following line</p>
<pre><code>sudo python setup.py install
</code></pre>
<p>An error is generated</p>
<blockquote>
<p>error: Installed distribution pbr 0.11.1 conflicts with requirement pbr>=1.6</p>
</blockquote>
<p>I think the problem is because the version of the packages referenced have changed.</p>
<p>Does somebody knows how to install jumpgate successfully with the current (2016/08) python packages ?</p>
<p>This is the list of my python packages:</p>
<pre><code>Babel (2.3.4)
backports.ssl-match-hostname (3.4.0.2)
click (6.6)
configobj (4.7.2)
Cython (0.24.1)
debtcollector (1.8.0)
decorator (3.4.0)
falcon (0.1.8)
funcsigs (1.0.2)
gunicorn (18.0)
iniparse (0.4)
iso8601 (0.1.11)
jumpgate (0.1)
keystoneauth1 (2.11.1)
monotonic (1.2)
msgpack-python (0.4.8)
netaddr (0.7.18)
netifaces (0.10.4)
oslo.config (1.5.0)
oslo.i18n (3.8.0)
oslo.serialization (2.13.0)
oslo.utils (3.16.0)
pbr (0.11.1)
perf (0.1)
pip (8.1.2)
positional (1.1.1)
prettytable (0.7.2)
prompt-toolkit (1.0.6)
py2-ipaddress (3.4.1)
pycrypto (2.6.1)
pycurl (7.19.0)
Pygments (2.1.3)
pygobject (3.14.0)
pygpgme (0.3)
pyliblzma (0.5.3)
pyparsing (2.1.8)
python-mimeparse (1.5.2)
python-novaclient (5.0.1.dev33)
pytz (2016.6.1)
pyudev (0.15)
pyxattr (0.5.1)
requests (2.11.1)
rfc3986 (0.3.1)
setuptools (0.9.8)
simplejson (3.8.2)
six (1.10.0)
slip (0.4.0)
slip.dbus (0.4.0)
SoftLayer (5.1.0)
stevedore (1.17.0)
urlgrabber (3.10)
wcwidth (0.1.7)
wheel (0.29.0)
wrapt (1.10.8)
yum-metadata-parser (1.1.4)
</code></pre>
<p>Thank you</p>
<p>--</p>
<p>Let me update the question:</p>
<p>After installing the dependencies</p>
<pre><code>cd /usr/local/jumpgate && sudo pip install -r tools/requirements.txt
</code></pre>
<p>I had to rollback oslo.config and falcon to previous version</p>
<pre><code>sudo pip install -U oslo.config==1.5.0
sudo pip install -U falcon==0.1.8
</code></pre>
<p>Now I'm able to install Jumpgate and run it.</p>
<pre><code>gunicorn "jumpgate.wsgi:make_api()" --bind="localhost:5000" --timeout=600 --access-logfile="-" -w 4
</code></pre>
<p>Continuing with the @bolden Blog I installed nova client OpenStack and configure the global variables to match SoftLayer account</p>
<pre><code>export OS_AUTH_URL=http://127.0.0.1:5000/v2.0
export OS_PASSWORD=xyz
export OS_TENANT_ID=SL9999999
export OS_USERNAME=SoftLayerUserName
</code></pre>
<p>Next I tried to execute the test</p>
<pre><code>nova --debug availability-zone-list
</code></pre>
<p>And I get the following error:</p>
<p><strong>Server side:</strong></p>
<p>REQ: GET /v2.0 {} [ReqId: req-9b0e1fe0-6536-11e6-818f-525400b263eb]
UNKNOWN PATH: GET /v2.0
RESP: GET /v2.0 501 Not Implemented [ReqId: req-9b0e1fe0-6536-11e6-818f-525400b263eb]</p>
<p>127.0.0.1 - - [18/Aug/2016:20:26:28 +0900] "GET /v2.0 HTTP/1.1" 501 95 "-" "nova keystoneauth1/2.11.1 python-requests/2.9.1 CPython/2.7.5"
REQ: POST /v2.0/tokens {} [ReqId: req-9b0f926c-6536-11e6-818f-525400b263eb]
RESP: POST /v2.0/tokens 401 Unauthorized [ReqId: req-9b0f926c-6536-11e6-818f-525400b263eb]</p>
<p>127.0.0.1 - - [18/Aug/2016:20:26:29 +0900] "POST /v2.0/tokens HTTP/1.1" 401 100 "-" "nova keystoneauth1/2.11.1 python-requests/2.9.1 CPython/2.7.5"</p>
<p><strong>Nova</strong></p>
<p>DEBUG (session:337) REQ: curl -g -i -X GET http:// 127.0.0.1:5000/v2.0 -H "Accept: application/json" -H "User-Agent: nova keystoneauth1/2.11.1 python-requests/2.9.1 CPython/2.7.5"</p>
<p>INFO (connectionpool:207) Starting new HTTP connection (1): 127.0.0.1</p>
<p>DEBUG (connectionpool:387) "GET /v2.0 HTTP/1.1" 501 95</p>
<p>DEBUG (session:366) RESP: [501] content-length: 95 x-compute-request-id: req-9b0e1fe0-6536-11e6-818f-525400b263eb Server: gunicorn/19.6.0 Connection: close Date: Thu, 18 Aug 2016 11:26:28 GMT content-type: application/json
RESP BODY: {"notImplemented": {"message": "Not Implemented", "code": "501", "details": "Not Implemented"}}</p>
<p>DEBUG (session:569) Request returned failure status: 501</p>
<p>WARNING (base:122) Discovering versions from the identity service failed when creating the password plugin. Attempting to determine version from URL.</p>
<p>DEBUG (v2:63) Making authentication request to http ://127.0.0.1:5000/v2.0/tokens</p>
<p>INFO (connectionpool:242) Resetting dropped connection: 127.0.0.1</p>
<p>DEBUG (connectionpool:387) "POST /v2.0/tokens HTTP/1.1" 401 100</p>
<p>DEBUG (session:569) Request returned failure status: 401</p>
<p>DEBUG (shell:984) Unauthorized (HTTP 401)
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/novaclient/shell.py", line 982, in main
OpenStackComputeShell().main(argv)
...
File "/usr/lib/python2.7/site-packages/keystoneauth1/session.py", line 570, in request
raise exceptions.from_response(resp, method, url)
Unauthorized: Unauthorized (HTTP 401)
ERROR (Unauthorized): Unauthorized (HTTP 401)</p>
<p>My questions:</p>
<p>1 - Is the Unauthorized message comming from SoftLayer or from Jumpgate ?</p>
<p>2 - Is the default SoftLayer end point valid? [/etc/jumpgate/jumpgate.conf]</p>
<pre><code>endpoint = https://api.softlayer.com/xmlrpc/v3/
</code></pre>
<p>Any idea is appreciated.</p>
<p>Thank you</p>
| 0 | 2016-08-18T06:59:11Z | 39,111,420 | <p>Run all in a virtualenv and save yourself some headaches.</p>
| 0 | 2016-08-23T22:06:44Z | [
"python",
"openstack",
"softlayer"
] |
pytest dependent parameters in parametrize | 39,011,777 | <p>I would like one parametrize to depend on an earlier one:</p>
<pre><code>@pytest.mark.parametrize("locale_name", LOCALES)
@pytest.mark.parametrize("money_string", ["500{currency}", "500 {currency}"])
@pytest.mark.parametrize("currency", LOCALES['locale_name']['currencies'])
def test_do_stuff(locale_name, money_string, currency):
print(locale_name, money_string, currency)
</code></pre>
<p>Here, the 3rd parametrize depends on the first.</p>
<p>I tried to split it up in the following way:</p>
<pre><code>@pytest.mark.parametrize("locale_name", LOCALES)
@pytest.mark.parametrize("money_string", ["500{currency}", "500 {currency}"])
def test_currencies(locale_name, money_string):
# locale is actually also needed as an object, cannot be taken out.
locale = LOCALES[locale_name]
@pytest.mark.parametrize("currency", locale['currencies'])
def test_inner_currencies(currency):
print("this does not run however")
</code></pre>
<p>But the inner code does not run. I'm not sure what can I do about this case, other than pre-generating the pairs using <code>itertools.product</code> (but that would look quite ugly)?</p>
<p>Note that I could just have a for loop, but then I would not "officially" run as many tests.</p>
| 0 | 2016-08-18T06:59:56Z | 39,061,694 | <p>I dont think py.test supports tests with in tests, If I understand correctly based on your example code, all you want is to test the currencies, Assuming <code>LOCALES</code> is a nested dict , I would do something of this sort to address the test</p>
<pre><code>import pytest
LOCALES = {"US": {"currencies": "dollar"},
"EU": {"currencies": "euro"},
"IN": {"currencies": "rupees"},
"CH": {"currencies": "yuan"}}
def currencies():
return [(local_name, currency["currencies"]) for local_name, currency in
LOCALES.items()]
@pytest.mark.parametrize("currency", currencies())
@pytest.mark.parametrize("money_string", ["500{currency}", "500 {currency}"])
def test_currencies(currency, money_string):
locale_name, currency = currency
print locale_name, money_string, currency
</code></pre>
<p>And the output </p>
<pre><code>============================= test session starts ==============================
platform darwin -- Python 2.7.10, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /Users/sanjay/Library/Preferences/PyCharm2016.2/scratches, inifile:
plugins: xdist-1.14
collected 8 items
scratch_11.py EU 500{currency} euro
.CH 500{currency} yuan
.US 500{currency} dollar
.IN 500{currency} rupees
.EU 500 {currency} euro
.CH 500 {currency} yuan
.US 500 {currency} dollar
.IN 500 {currency} rupees
.
=========================== 8 passed in 0.03 seconds ===========================
Process finished with exit code 0
</code></pre>
| 0 | 2016-08-21T07:06:30Z | [
"python",
"dependencies",
"py.test"
] |
I cannot use Quanterion values that i use with PyOpenGL.glRotatef in Unity | 39,011,834 | <p>i have values Quaternion(x,y,z,w)=(p0,p1,p2,p3)
in pyOpenGl</p>
<pre><code> norm=math.sqrt(program_dict['q0']*program_dict['q0'] + program_dict['q1']*program_dict['q1'] + program_dict['q2']*program_dict['q2'] + program_dict['q3']*program_dict['q3'])
glPushMatrix()
if (norm == 0):
pass
else:
program_dict['q0'] = program_dict['q0'] / norm
program_dict['q1'] = program_dict['q1'] / norm
program_dict['q2'] = program_dict['q2'] / norm
program_dict['q3'] = program_dict['q3'] / norm
theta = ( math.acos(program_dict['q3'])*2)
aNorm = math.sqrt(program_dict['q1'] * program_dict['q1'] + program_dict['q2'] * program_dict['q2'] + program_dict['q0'] * program_dict['q0'])
if (aNorm != 0):
glRotatef(theta*180.0/math.pi, program_dict['q2']/aNorm, -program_dict['q0']/aNorm, program_dict['q1']/aNorm)
else:
glRotatef(theta*180.0/math.pi, program_dict['q2'], -program_dict['q0'], program_dict['q1'])
</code></pre>
<p>I normalize the data first (btw data comes from an prototype device so it must be normalised)
How can i use this in c# Unity and rotate an object? I dont know how Unity units work...</p>
| 1 | 2016-08-18T07:02:37Z | 39,128,105 | <p>The confusion here is between an axis-angle representation and a quaternion. The glRotatef you are using uses the former, while the <code>rotation</code> and <code>localRotation</code> of Unity's <code>Transform</code> are the latter. </p>
<p>You can however convert between the two. <a href="https://docs.unity3d.com/ScriptReference/Quaternion.AngleAxis.html" rel="nofollow"><code>Quaternion.AngleAxis(float angle, Vector3 axis)</code></a> does exactly that. It takes the axis-angle representation and converts it to the corresponding Quaternion. This you can then feed into <code>localRotation</code> for example. </p>
| 0 | 2016-08-24T16:03:34Z | [
"c#",
"python",
"unity3d",
"unity5",
"pyopengl"
] |
display content of graphs in matplotlib inmmediately | 39,011,935 | <p>I'm using Canopy in a Win7 machine, with <code>%pylab</code> enabled and interactive(Qt4) as backend. IMHO, I'm getting what I consider a weird behavior of <code>matplotlib</code>.</p>
<p>If the code is executed line by line, the frames for the graphs appear as I expect, but not the content of the graphs themselves. If, after the plotting, I need information regarding to those graphs, as I can't see them, I can't answer properly. Once I answer the question with a dummy answer, the graphs appear.</p>
<p>What I would like to achieve is that the graphs show before the question would be asked, in order to have the information to reply.</p>
<p>Thanks in advance. </p>
<p>This is a MWE</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
N = 8
y = np.zeros(N)
x1 = np.linspace(0, 10, N, endpoint=True)
x2 = np.linspace(0, 10, N, endpoint=False)
plt.figure()
plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.5, 'o')
plt.ylim([-0.5, 1])
plt.show()
y1 = np.random.random(8)
plt.figure()
plt.plot(x1, y1)
plt.show()
dummy = raw_input("What is the third point in the second graph?")
</code></pre>
<p>EDIT: If I change the backend in Canopy from interactive(Qt4) to interactive(wx), it works as expected.</p>
| 1 | 2016-08-18T07:08:56Z | 39,013,502 | <p>If I understand, the problem is that <code>plt.show</code> will block and the second figure will not be plotted until the first is closed. With different backends the behaviour may be different but you shouldn't call show more than once (see <a href="http://stackoverflow.com/questions/5524858/matplotlib-show-doesnt-work-twice">matplotlib show() doesn't work twice</a>). I'd suggest using two <code>subplots</code> here and maybe turning blocking off as raw_input block and you can enter an input with the figure showing. You code would then look like this,</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
N = 8
y = np.zeros(N)
x1 = np.linspace(0, 10, N, endpoint=True)
x2 = np.linspace(0, 10, N, endpoint=False)
fig,ax = plt.subplots(2,1)
ax[0].plot(x1, y, 'o')
ax[0].plot(x2, y + 0.5, 'o')
ax[0].set_ylim([-0.5, 1])
y1 = np.random.random(8)
ax[1].plot(x1, y1)
plt.show(block=False)
dummy = raw_input("What is the third point in the second graph?")
print("dummy = ", dummy)
</code></pre>
<p>which works for me.</p>
| 1 | 2016-08-18T08:37:03Z | [
"python",
"matplotlib",
"enthought"
] |
display content of graphs in matplotlib inmmediately | 39,011,935 | <p>I'm using Canopy in a Win7 machine, with <code>%pylab</code> enabled and interactive(Qt4) as backend. IMHO, I'm getting what I consider a weird behavior of <code>matplotlib</code>.</p>
<p>If the code is executed line by line, the frames for the graphs appear as I expect, but not the content of the graphs themselves. If, after the plotting, I need information regarding to those graphs, as I can't see them, I can't answer properly. Once I answer the question with a dummy answer, the graphs appear.</p>
<p>What I would like to achieve is that the graphs show before the question would be asked, in order to have the information to reply.</p>
<p>Thanks in advance. </p>
<p>This is a MWE</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
N = 8
y = np.zeros(N)
x1 = np.linspace(0, 10, N, endpoint=True)
x2 = np.linspace(0, 10, N, endpoint=False)
plt.figure()
plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.5, 'o')
plt.ylim([-0.5, 1])
plt.show()
y1 = np.random.random(8)
plt.figure()
plt.plot(x1, y1)
plt.show()
dummy = raw_input("What is the third point in the second graph?")
</code></pre>
<p>EDIT: If I change the backend in Canopy from interactive(Qt4) to interactive(wx), it works as expected.</p>
| 1 | 2016-08-18T07:08:56Z | 39,024,992 | <p>As Ed Smith said, only the first call to <code>plt.show()</code> works.
If you want to force a redraw of the figure, you can use <code>figure.canvas.draw()</code></p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([0, 1], [2, 3])
plt.show()
#do more stuff, get user input
plt.plot([5,6], [-7, -8])
fig.canvas.draw()
</code></pre>
<p><a href="http://i.stack.imgur.com/VXo2Y.png" rel="nofollow"><img src="http://i.stack.imgur.com/VXo2Y.png" alt="enter image description here"></a></p>
| 1 | 2016-08-18T18:19:36Z | [
"python",
"matplotlib",
"enthought"
] |
reportlab, find position/coordinates for last paragraph in page | 39,011,936 | <p>I need to insert some text after last paragraph on last page, am not sure if it is possible to find coordinates for last paragraph.</p>
<p>As I know reportlab is most robust library for dealing with pdf, however if that is possible via another library will be fine.</p>
<p>Also to ask is it possible to replicate (find font attributes like name and size for last paragraph)?</p>
<p>What I have</p>
<pre><code>from reportlab.pdfgen.canvas import Canvas
from pdfrw import PdfReader
from pdfrw.toreportlab import makerl
from pdfrw.buildxobj import pagexobj
input_file = 'abc.pdf'
output_file = 'def.pdf'
# Get pages
reader = PdfReader(input_file)
pages = [pagexobj(p) for p in reader.pages]
canvas = Canvas(output_file)
lastpage = pages[-1]
for page_num, page in enumerate(pages, start=1):
canvas.setPageSize((page.BBox[2], page.BBox[3]))
canvas.doForm(makerl(canvas, page))
if page == lastpage:
canvas.saveState()
# helpful code might come here
canvas.restoreState()
canvas.showPage()
canvas.save()
</code></pre>
| 0 | 2016-08-18T07:08:57Z | 39,067,810 | <p>Solution is in Great pdfminer python library from Yusuke Shinyama. 5 stars for his project.</p>
<p>pdfminer is at present available only for python2.7</p>
<p>Is installing from source after unpacking archive with</p>
<pre><code>sudo python setup.py install
</code></pre>
<p>After instalation commandline tool pdf2txt.py can be used like</p>
<pre><code>/usr/local/bin/pdf2txt.py -t xml file.pdf > xmlfile.xml
</code></pre>
<p>with all needed information and more then that!</p>
| 0 | 2016-08-21T18:58:39Z | [
"python",
"reportlab",
"pdfrw"
] |
Pulling Income Statement Data using Python | 39,011,939 | <p>I am trying to pull data from Yahoo Finance using the below code but it is throwing me error. </p>
<p>I tried to debug from my end and it looks the title is coming as blank when using the find command</p>
<p>title = soup.find("strong", text=pattern) #returning blank</p>
<p>Code:</p>
<pre><code># -*- coding: utf-8 -*-
"""
"""
#Read income statement to calculate ratios
from bs4 import BeautifulSoup
import requests
import re,sys
myurl = "https://finance.yahoo.com/q/is?s=AAPL&annual"
html = requests.get(myurl).content
soup = BeautifulSoup(html)
def periodic_figure_values(soup, yahoo_figure):
values = []
pattern = re.compile(yahoo_figure)
title = soup.find("strong", text=pattern) # works for the figures printed in bold
if title:
row = title.parent.parent
else:
title = soup.find("td", text=pattern) # works for any other available figure
if title:
row = title.parent
else:
sys.exit("Invalid figure '" + yahoo_figure + "' passed.")
cells = row.find_all("td")[1:] # exclude the <td> with figure name
for cell in cells:
if cell.text.strip() != yahoo_figure: # needed because some figures are indented
str_value = cell.text.strip().replace(",", "").replace("(", "-").replace(")", "")
if str_value == "-":
str_value = 0
value = int(str_value) * 1000
values.append(value)
return values
def financials_soup(ticker_symbol, statement="is", quarterly=False):
if statement == "is" or statement == "bs" or statement == "cf":
url = "https://finance.yahoo.com/q/" + statement + "?s=" + ticker_symbol
if not quarterly:
url += "&annual"
return BeautifulSoup(requests.get(url).text, "html.parser")
return sys.exit("Invalid financial statement code '" + statement + "' passed.")
print(periodic_figure_values(financials_soup("AAPL", "is"), "Income Tax Expense"))
"""throws error: An exception has occurred, use %tb to see the full traceback.
SystemExit: Invalid figure 'Income Tax Expense' passed."""
</code></pre>
| 0 | 2016-08-18T07:09:15Z | 39,070,877 | <p>As far as I found out (I'm just staring, complete noob), Yahoo finance uses Java Script. And as such, Beautiful Soup will not work. At least this is what I was told. Selenium should be correct tool for sites like this. </p>
<p>Here bellow is the link, where I asked similar question and in that link is code that works. Well almost. I had to change 2-3 small, trivial things:</p>
<p><a href="http://stackoverflow.com/questions/38732496/how-should-i-properly-use-selenium">How should I properly use Selenium</a></p>
<p>Here is my comment, response what I changed to make it work: (not sure if code was later changed to reflect this, see if it is working for you without changing it, if not implement changes I did:</p>
<p>I had to change code a little bit, wait was not used, so I searched internet and I changed Wait to WebDriverWait and it still didn't click on Balance Sheet until I changed to this: balanceSheet = WebDriverWait(browser, 5) and now it is working and I have learned a lot and I can now start working on my project and learning to code in the process. Thank you so much! â Al_ Aug 3 at 13:07</p>
<hr>
<p>Edit, my example only download one thing from Balance Sheet, but this should help you figure out how to do it for your case (Financial Statement). If you can't get code to work, I will send you my working code once I'm back at that computer.</p>
| 0 | 2016-08-22T03:10:10Z | [
"python",
"yahoo-finance"
] |
Why can't I assign array to pandas DataFrame column? | 39,011,954 | <p>I am using <code>KNeighborsClassifier</code> to classify some values like this:</p>
<pre><code>arr = classifier_3NN.predict(testData_df)
len(arr)
10960
</code></pre>
<p>I want to assign this array to a column in a DataFrame, I have checked & it is the same size:</p>
<pre><code>len(df[df['events']=='NaN']['events'])
10960
</code></pre>
<blockquote>
<p>When I do the following command the array values are not in the column as expected:</p>
</blockquote>
<pre><code>df[df['events']=='NaN']['events'] = arr
</code></pre>
<p>Can anyone see what I'm doing wrong?</p>
| 1 | 2016-08-18T07:09:58Z | 39,011,994 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code></a> for checking <code>NaN</code> values with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>:</p>
<pre><code>df.ix[df['events'].isnull(), 'events'] = arr
</code></pre>
<p>But if need replace <code>NaN</code> values by <code>arr</code> better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> by <code>Series</code> created from <code>arr</code>:</p>
<pre><code>arr = [5,7,9]
df = pd.DataFrame({'events':[np.nan, 1, np.nan]})
print (df)
events
0 NaN
1 1.0
2 NaN
df['events'] = df['events'].fillna(pd.Series(arr, index=df.index))
print (df)
events
0 5.0
1 1.0
2 9.0
</code></pre>
| 1 | 2016-08-18T07:12:36Z | [
"python",
"arrays",
"pandas",
"numpy"
] |
Issue regarding the installation of android backend server | 39,012,030 | <p>I have an issue regarding the android backend storage. Can anyone help in initial steps from determining which server to buy, how to use it and which integrated development environment (ide) should be used for python??
Any leads will be helpful.
Thanks </p>
| 0 | 2016-08-18T07:14:27Z | 39,012,131 | <p>check out once about Firebase
link: <a href="https://firebase.google.com/docs/" rel="nofollow">https://firebase.google.com/docs/</a>
it may useful to you.it offers storage and realtime database and more.</p>
| 0 | 2016-08-18T07:19:45Z | [
"android",
"python",
"sql-server",
"backend"
] |
Spark ML Pipeline Causes java.lang.Exception: failed to compile ... Code ... grows beyond 64 KB | 39,012,073 | <p>Using Spark 2.0, I am trying to run a simple VectorAssembler in a pyspark ML pipeline, like so: </p>
<pre><code>feature_assembler = VectorAssembler(inputCols=['category_count', 'name_count'], \
outputCol="features")
pipeline = Pipeline(stages=[feature_assembler])
model = pipeline.fit(df_train)
model_output = model.transform(df_train)
</code></pre>
<p>When I try to look at the output using </p>
<pre><code>model_output.select("features").show(1)
</code></pre>
<p>I get the error </p>
<pre><code>Py4JJavaError Traceback (most recent call last)
<ipython-input-95-7a3e3d4f281c> in <module>()
2
3
----> 4 model_output.select("features").show(1)
/usr/local/spark20/python/pyspark/sql/dataframe.pyc in show(self, n, truncate)
285 +---+-----+
286 """
--> 287 print(self._jdf.showString(n, truncate))
288
289 def __repr__(self):
/usr/local/spark20/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py in __call__(self, *args)
931 answer = self.gateway_client.send_command(command)
932 return_value = get_return_value(
--> 933 answer, self.gateway_client, self.target_id, self.name)
934
935 for temp_arg in temp_args:
/usr/local/spark20/python/pyspark/sql/utils.pyc in deco(*a, **kw)
61 def deco(*a, **kw):
62 try:
---> 63 return f(*a, **kw)
64 except py4j.protocol.Py4JJavaError as e:
65 s = e.java_exception.toString()
/usr/local/spark20/python/lib/py4j-0.10.1-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
310 raise Py4JJavaError(
311 "An error occurred while calling {0}{1}{2}.\n".
--> 312 format(target_id, ".", name), value)
313 else:
314 raise Py4JError(
Py4JJavaError: An error occurred while calling o2875.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure:
Task 0 in stage 1084.0 failed 4 times, most recent failure: Lost task 0.3 in stage 1084.0 (TID 42910, 169.45.92.174):
java.util.concurrent.ExecutionException: java.lang.Exception: failed to
compile: org.codehaus.janino.JaninoRuntimeException: Code of method "
(Lorg/apache/spark/sql/catalyst/InternalRow;Lorg/apache/spark/sql/catalyst/InternalRow;)I" of class
"org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificOrdering"
grows beyond 64 KB
</code></pre>
<p>It then lists the generated code, which looks like:</p>
<pre><code>/* 001 */ public SpecificOrdering generate(Object[] references) {
/* 002 */ return new SpecificOrdering(references);
/* 003 */ }
/* 004 */
/* 005 */ class SpecificOrdering extends org.apache.spark.sql.catalyst.expressions.codegen.BaseOrdering {
/* 006 */
/* 007 */ private Object[] references;
/* 008 */
/* 009 */
/* 010 */ public int compareStruct1(InternalRow a, InternalRow b) {
/* 011 */ InternalRow i = null;
/* 012 */
/* 013 */ i = a;
/* 014 */ boolean isNullA836;
/* 015 */ byte primitiveA834;
/* 016 */ {
/* 017 */
/* 018 */ boolean isNull834 = i.isNullAt(0);
/* 019 */ byte value834 = isNull834 ? (byte)-1 : (i.getByte(0));
/* 020 */ isNullA836 = isNull834;
/* 021 */ primitiveA834 = value834;
/* 022 */ }
/* 023 */ i = b;
â¦
/* 28649 */ return 0;
/* 28650 */ }
/* 28651 */ }
</code></pre>
<p>Why would this simple VectorAssembler generate 28,651 lines of code and exceed 64KB? </p>
| 2 | 2016-08-18T07:16:54Z | 39,976,133 | <p>It seems like there may be a limit, namely 64KB, to Spark's lazy evaluation. In other words, it's being a little to lazy in this case which is causing it to hit that limit.</p>
<p>I was able to work around this same exception, which I was triggering via a <code>join</code> rather than with a VectorAssembler, by calling <code>cache</code> on one of my <code>Dataset</code>s about half way through my pipeline. I don't know (yet) exactly why this solved the issue however.</p>
| 0 | 2016-10-11T11:22:19Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql",
"pyspark-sql"
] |
UnicodeEncodeError in Python CSV manipulation script | 39,012,122 | <p>I have a script that was working earlier but now stops due to UnicodeEncodeError.</p>
<p>I am using Python 3.4.3.</p>
<p>The full error message is the following:</p>
<pre><code>Traceback (most recent call last):
File "R:/A/APIDevelopment/ScivalPubsExternal/Combine/ScivalPubsExt.py", line 58, in <module>
outputFD.writerow(row)
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x8a' in position 413: character maps to <undefined>
</code></pre>
<p>How can I address this error?</p>
<p>The Python script is the following below:</p>
<pre><code>import pdb
import csv,sys,os
import glob
import os
import codecs
os.chdir('R:/A/APIDevelopment/ScivalPubsExternal/Combine')
joinedFileOut='ScivalUpdate'
csvSourceDir="R:/A/APIDevelopment/ScivalPubsExternal/Combine/AustralianUniversities"
# create dictionary from Codes file (Institution names and codes)
codes = csv.reader(open('Codes.csv'))
#rows of the file are stored as lists/arrays
InstitutionCodesDict = {}
InstitutionYearsDict = {}
for row in codes:
#keys: instnames, #values: instcodes
InstitutionCodesDict[row[0]] = row[1]
#define year dictionary with empty values field
InstitutionYearsDict[row[0]] = []
#to create a fiel descriptor for the outputfile, wt means text mode (also rt opr r is the same)
with open(joinedFileOut,'wt') as csvWriteFD:
#write the file (it is still empty here)
outputFD=csv.writer(csvWriteFD,delimiter=',')
#with closes the file at the end, if exception occurs then before that
# open each scival file, create file descriptor (encoding needed) and then read it and print the name of the file
if not glob.glob(csvSourceDir+"/*.csv"):
print("CSV source files not found")
sys.exit()
for scivalFile in glob.glob(csvSourceDir+"/*.csv"):
#with open(scivalFile,"rt", encoding="utf8") as csvInFD:
with open(scivalFile,"rt", encoding="ISO-8859-1") as csvInFD:
fileFD = csv.reader(csvInFD)
print(scivalFile)
#create condition for loop
printon=False
#reads all rows in file and creates lists/arrays of each row
for row in fileFD:
if len(row)>1:
#the next printon part is skipped when looping through the rows above the data because it is not set to true
if printon:
#inserts instcode and inst sequentially to each row where there is data and after the header row
row.insert(0, InstitutionCode)
row.insert(0, Institution)
if row[10].strip() == "-":
row[10] = " "
else:
p = row[10].zfill(8)
q = p[0:4] + '-' + p[4:]
row[10] = q
#writes output file
outputFD.writerow(row)
else:
if "Publications at" in row[1]:
#get institution name from cell B1
Institution=row[1].replace('Publications at the ', "").replace('Publications at ',"")
print(Institution)
#lookup institution code from dictionary
InstitutionCode=InstitutionCodesDict[Institution]
#printon gets set to TRUE after the header column
if "Title" in row[0]: printon=True
if "Publication years" in row[0]:
#get the year to print it later to see which years were pulled
year=row[1]
#add year to institution in dictionary
if not year in InstitutionYearsDict[Institution]:
InstitutionYearsDict[Institution].append(year)
# Write a report showing the institution name followed by the years for
# which we have that institution's data.
with open("Instyears.txt","w") as instReportFD:
for inst in (InstitutionYearsDict):
instReportFD.write(inst)
for yr in InstitutionYearsDict[inst]:
instReportFD.write(" "+yr)
instReportFD.write("\n")
</code></pre>
| 0 | 2016-08-18T07:19:14Z | 39,014,157 | <p>The error is caused by an attempt to write a string containing a U+008A character using the default cp1252 encoding of your system. It is trivial to fix, just declare a latin1 encoding (or iso-8859-1) for your output file (because it just outputs the original byte without conversion):</p>
<pre><code>with open(joinedFileOut,'wt', encoding='latin1') as csvWriteFD:
</code></pre>
<p>But this will only hide the real problem: where does this <code>0x8a</code> character come from? My advice is to intercept the exception and dump the line where it occurs:</p>
<pre><code>try:
outputFD.writerow(row)
except UnicodeEncodeError:
# print row, the name of the file being processed and the line number
</code></pre>
<p>It is probably caused by one of the input files not being is-8859-1 encoded but more probably utf8 encoded...</p>
| 0 | 2016-08-18T09:09:20Z | [
"python",
"csv",
"unicode",
"encode"
] |
UnicodeEncodeError in Python CSV manipulation script | 39,012,122 | <p>I have a script that was working earlier but now stops due to UnicodeEncodeError.</p>
<p>I am using Python 3.4.3.</p>
<p>The full error message is the following:</p>
<pre><code>Traceback (most recent call last):
File "R:/A/APIDevelopment/ScivalPubsExternal/Combine/ScivalPubsExt.py", line 58, in <module>
outputFD.writerow(row)
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x8a' in position 413: character maps to <undefined>
</code></pre>
<p>How can I address this error?</p>
<p>The Python script is the following below:</p>
<pre><code>import pdb
import csv,sys,os
import glob
import os
import codecs
os.chdir('R:/A/APIDevelopment/ScivalPubsExternal/Combine')
joinedFileOut='ScivalUpdate'
csvSourceDir="R:/A/APIDevelopment/ScivalPubsExternal/Combine/AustralianUniversities"
# create dictionary from Codes file (Institution names and codes)
codes = csv.reader(open('Codes.csv'))
#rows of the file are stored as lists/arrays
InstitutionCodesDict = {}
InstitutionYearsDict = {}
for row in codes:
#keys: instnames, #values: instcodes
InstitutionCodesDict[row[0]] = row[1]
#define year dictionary with empty values field
InstitutionYearsDict[row[0]] = []
#to create a fiel descriptor for the outputfile, wt means text mode (also rt opr r is the same)
with open(joinedFileOut,'wt') as csvWriteFD:
#write the file (it is still empty here)
outputFD=csv.writer(csvWriteFD,delimiter=',')
#with closes the file at the end, if exception occurs then before that
# open each scival file, create file descriptor (encoding needed) and then read it and print the name of the file
if not glob.glob(csvSourceDir+"/*.csv"):
print("CSV source files not found")
sys.exit()
for scivalFile in glob.glob(csvSourceDir+"/*.csv"):
#with open(scivalFile,"rt", encoding="utf8") as csvInFD:
with open(scivalFile,"rt", encoding="ISO-8859-1") as csvInFD:
fileFD = csv.reader(csvInFD)
print(scivalFile)
#create condition for loop
printon=False
#reads all rows in file and creates lists/arrays of each row
for row in fileFD:
if len(row)>1:
#the next printon part is skipped when looping through the rows above the data because it is not set to true
if printon:
#inserts instcode and inst sequentially to each row where there is data and after the header row
row.insert(0, InstitutionCode)
row.insert(0, Institution)
if row[10].strip() == "-":
row[10] = " "
else:
p = row[10].zfill(8)
q = p[0:4] + '-' + p[4:]
row[10] = q
#writes output file
outputFD.writerow(row)
else:
if "Publications at" in row[1]:
#get institution name from cell B1
Institution=row[1].replace('Publications at the ', "").replace('Publications at ',"")
print(Institution)
#lookup institution code from dictionary
InstitutionCode=InstitutionCodesDict[Institution]
#printon gets set to TRUE after the header column
if "Title" in row[0]: printon=True
if "Publication years" in row[0]:
#get the year to print it later to see which years were pulled
year=row[1]
#add year to institution in dictionary
if not year in InstitutionYearsDict[Institution]:
InstitutionYearsDict[Institution].append(year)
# Write a report showing the institution name followed by the years for
# which we have that institution's data.
with open("Instyears.txt","w") as instReportFD:
for inst in (InstitutionYearsDict):
instReportFD.write(inst)
for yr in InstitutionYearsDict[inst]:
instReportFD.write(" "+yr)
instReportFD.write("\n")
</code></pre>
| 0 | 2016-08-18T07:19:14Z | 39,057,325 | <p>Make sure to use the <strong>correct</strong> encoding of your source and destination files. You open files in three locations:</p>
<pre><code>codes = csv.reader(open('Codes.csv'))
: : :
with open(joinedFileOut,'wt') as csvWriteFD:
outputFD=csv.writer(csvWriteFD,delimiter=',')
: : :
with open(scivalFile,"rt", encoding="ISO-8859-1") as csvInFD:
fileFD = csv.reader(csvInFD)
</code></pre>
<p>This should look something like:</p>
<pre><code># Use the correct encoding. If you made this file on
# Windows it is likely Windows-1252 (also known as cp1252):
with open('Codes.csv', encoding='cp1252') as f:
codes = csv.reader(f)
: : :
# The output encoding can be anything you want. UTF-8
# supports all Unicode characters. Windows apps tend to like
# the files to start with a UTF-8 BOM if the file is UTF-8,
# so 'utf-8-sig' is an option.
with open(joinedFileOut,'w', encoding='utf-8-sig') as csvWriteFD:
outputFD=csv.writer(csvWriteFD)
: : :
# This file is probably the cause of your problem and is not ISO-8859-1.
# Maybe UTF-8 instead? 'utf-8-sig' will safely handle and remove a UTF-8 BOM
# if present.
with open(scivalFile,'r', encoding='utf-8-sig') as csvInFD:
fileFD = csv.reader(csvInFD)
</code></pre>
| 0 | 2016-08-20T18:15:24Z | [
"python",
"csv",
"unicode",
"encode"
] |
How to redirect the output to file and print required words line by line in python | 39,012,177 | <p>Am beginner in python I have just extracted permissions from an file using python through this code</p>
<pre><code>def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
file = open('op3.txt', 'w')
from xml.dom.minidom import parseString
data = ''
with open('C:/Users/kireet/Desktop/AndroidManifest.xml','r') as f:
data = f.read()
dom = parseString(data)
nodes = dom.getElementsByTagName('uses-permission')
# Iterate over all the uses-permission nodes
for node in nodes:
perm=node.getAttribute('android:name')
perm1=remove_prefix(perm,'android.permission.')
print(perm1)
file.write(perm1)
</code></pre>
<p>I have got output as:</p>
<blockquote>
<p>INTERNET</p>
<p>ACCESS_NETWORK_STATE</p>
<p>ACCESS_WIFI_STATE</p>
<p>RECEIVE_BOOT_COMPLETED</p>
<p>READ_PHONE_STATE</p>
<p>WRITE_EXTERNAL_STORAGE</p>
<p>WAKE_LOCK</p>
<p>com.android.launcher.permission.INSTALL_SHORTCUT</p>
<p>GET_TASKS</p>
<p>EXPAND_STATUS_BAR</p>
<p>SET_WALLPAPER</p>
<p>CAMERA</p>
<p>MANAGE_DOCUMENTS</p>
<p>READ_EXTERNAL_STORAGE</p>
<p>ACCESS_COARSE_LOCATION</p>
<p>ACCESS_FINE_LOCATION</p>
<p>CHANGE_WIFI_STATE</p>
<p>READ_LOGS</p>
<p>VIBRATE</p>
<p>RECORD_AUDIO</p>
<p>com.google.android.gms.permission.ACTIVITY_RECOGNITION</p>
<p>READ_CALENDAR</p>
<p>WRITE_CALENDAR</p>
<p>GET_ACCOUNTS</p>
<p>USE_CREDENTIALS</p>
</blockquote>
<p>but the same output when redirected to file shows the output in a single line without any spaces as:</p>
<blockquote>
<p>INTERNETACCESS_NETWORK_STATEACCESS_WIFI_STATERECEIVE_BOOT_COMPLETEDREAD_PHONE_STATEWRITE_EXTERNAL_STORAGEWAKE_LOCKcom.android.launcher.</p>
</blockquote>
<p>can any one help how to get the output of required permissions line by line in a redirected file?</p>
| -1 | 2016-08-18T07:22:50Z | 39,012,384 | <p>add a new line character when writing the strings</p>
<p><code>file.write(perm1 + '\n')</code></p>
| 0 | 2016-08-18T07:35:02Z | [
"android",
"python"
] |
How do I combine nodes with the same node type from different matched patterns into a single column or collection? | 39,012,181 | <p>I'm creating a social network for learning Neo4J. We have users and their followers, posts. We want merge two statements.</p>
<p><strong>Goal: list of posts including yours and those you follow in chronological order.</strong></p>
<ol>
<li>My posts</li>
<li>My following users posts</li>
</ol>
<p>We tried <strong>OR</strong> and <strong>RETURN p+l as posts</strong> and <strong>Serverside language merging (Order Problem)</strong></p>
<p>How I can create this Cypher statement?</p>
<p><strong>Labels and Relations</strong></p>
<ul>
<li>User
<ul>
<li>username</li>
</ul></li>
<li>Post
<ul>
<li>text</li>
</ul></li>
</ul>
<p>(User)-[f: FOLLOW]-(User)</p>
<p>(Post)-[p: POSTED_BY]-(User)</p>
<p><strong>Edit</strong></p>
<p>Also we tried this Cypher </p>
<p><code>
match (cur_user: User {username: 'ahmetsa'})-[:FOLLOW]->(others: User)<- [:POSTED_BY]-(p: Post)
match ( l: Post) - [:POSTED_BY]->(cur_user: User {username: 'ahmetsa'})
return p+l
</code></p>
<p>but makes type error</p>
<p><strong>Type mismatch: expected Collection but was Node (line 3, column 10 (offset: 177))
"return p+l"</strong></p>
<hr>
<p><strong>Solution</strong></p>
<p><code>
Match (cur_user: User {username: 'ahmetsa'})-[:FOLLOW]->(others: User)<- [:POSTED_BY]-(p: Post) With cur_user,p
Match ( l: Post) - [:POSTED_BY]->(cur_user)
Return collect(p) + collect(l) as posts
</code></p>
| -1 | 2016-08-18T07:23:03Z | 39,012,344 | <p>You can merge your two statements using <code>WITH</code>:</p>
<pre><code>Match (cur_user: User {username: 'ahmetsa'})-[:FOLLOW]->(others: User)<- [:POSTED_BY]-(p: Post) With cur_user, p
Match ( l: Post) - [:POSTED_BY]->(cur_user)
Return collect(p) + collect(l) as posts
</code></pre>
<p><code>WITH</code> allows you to pass variable to the next query part so you can use it without matching it again.</p>
| 1 | 2016-08-18T07:32:13Z | [
"python",
"neo4j"
] |
change bin size of histogram data | 39,012,192 | <p>I have data from an SQL statement like</p>
<pre><code>'select action_count, count(*) "num_users" from customers group by action_count;'
</code></pre>
<p>and load this into a pandas data frame. I can run a simple plot command on the data, or <em>barplot</em> it to make it look like a histogram. But how can I easily change the bin size of this data set? And how do I then plot the bins, i.e. the x-axis correctly?</p>
<p>Thanks!</p>
| 1 | 2016-08-18T07:23:36Z | 39,013,133 | <p>You can specify the location of the edges of bins using a list in <code>pandas</code> <code>hist</code>. For example, using a custom sequence with bin from <code>-2.0</code> to <code>-0.5</code> and then <code>-0.5</code> to <code>0.0</code> followed by a few increments of <code>0.1</code>,</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df =pd.DataFrame({'col1':np.random.randn(10000)})
df.hist(bins=[-2.,-0.5,0.,0.1,0.2,0.3])
plt.show()
</code></pre>
<p>which plots,</p>
<p><a href="http://i.stack.imgur.com/tfQhz.png" rel="nofollow"><img src="http://i.stack.imgur.com/tfQhz.png" alt="enter image description here"></a></p>
| 0 | 2016-08-18T08:17:38Z | [
"python",
"pandas",
"numpy",
"matplotlib",
"seaborn"
] |
How to Access Many to many field in class based views in Django? | 39,012,367 | <p>I have two models, Author & Book in models.py</p>
<pre><code>class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age = models.IntegerField()
def __str__(self):
return '%s %s' %(self.first_name, self.last_name)
def __unicode__(self):
return '%s %s' %(self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100) #name = title
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
author = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __str__(self):
return self.title
def __unicode__(self):
return self.title
</code></pre>
<p>Now i'm listing all the books using ListView. And on click of a book i'm getting information the book using following method</p>
<pre><code>class BookDetailView(generic.DetailView):
template_name = 'books/book_detail1.html'
model = Book
context_object_name = 'book_detail'
</code></pre>
<p>I'm able to access title, pages, price, rating, publisher & publication_date but not getting all the Authors(Author list). While i'm going to simply print it, it prints None in template. I even try to iterate using For Loop but not done in template</p>
<p>views.py</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<li>Price:{{ book_detail.price }}</li>
<li>Pub Date:{{ book_detail.publication_date }}</li>
<li>Title: {{ book_detail.title }}</li>
<li>Pages: {{ book_detail.pages }}</li>
<li>Rating: {{ book_detail.rating }}</li>
<li>Publisher: {{ book_detail.publisher }}</li>
<li>Author: {{ book_detail.author }}</li>
</ul>
</body>
</html>
</code></pre>
<p>Can anyone help me to out from this?</p>
| 3 | 2016-08-18T07:33:50Z | 39,012,587 | <p>You have defined a many-to-many relationship between <code>Book</code> and <code>Author</code> which means that a book can have any number of authors. In order to display them you need to loop through the set of authors:</p>
<pre><code>Authors:
<ul>
{% for author in book_detail.author.all %}
<li>{{ author }}</li>
{% endfor %}
</ul>
</code></pre>
<p>You might want to change the name of that field to <code>authors</code> to be less confusing.</p>
<p>Alternatively if you want only one author for a book then you need to use a <code>ForeignKey</code> instead of a <code>ManyToManyField</code>. In that case your existing template logic would work. </p>
| 6 | 2016-08-18T07:47:35Z | [
"python",
"django",
"many-to-many",
"django-class-based-views"
] |
Pandas groupby plot gives first plot twice | 39,012,371 | <p>I have a dataframe with several categories and I want to use <code>groupby</code> to plot each category individually. However, the first category (or the first plot) is always plotted twice.</p>
<p>For example:</p>
<pre><code> import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
n = 100000
x = np.random.standard_normal(n)
y1 = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
y2 = 1.0 + 5.0 * x + 2.0 * np.random.standard_normal(n)
df1 = pd.DataFrame({"A": x,
"B": y1})
df2 = pd.DataFrame({"A": x,
"B": y2})
df1["Cat"] = "Cat1"
df2["Cat"] = "Cat2"
df = df1.append(df2, ignore_index=True)
df.groupby("Cat").plot.hexbin(x="A", y="B",cmap = "jet")
plt.show()
</code></pre>
<p>This will give me three plots, where Cat1 is plotted twice.</p>
<p>I just want two plots. What am I doing wrong?</p>
| 2 | 2016-08-18T07:33:58Z | 39,012,557 | <p>This is expected behaviour, see the warning in the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#flexible-apply" rel="nofollow">docs</a>:</p>
<blockquote>
<p><strong>Warning:</strong> In the current implementation apply calls func twice on the first group to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first group.</p>
</blockquote>
<p>In your case, the plot function is called twice, which is visible in the result.</p>
| 1 | 2016-08-18T07:45:33Z | [
"python",
"pandas",
"plot"
] |
How to measure power consumption of my application on Android | 39,012,385 | <p>I have developed an android application and I would like to know the power consumption of my app on an android device. I came across various threads on SO but none of them helped me.</p>
<p>Is there any application in android which measures the power consumption of my app or any other viable method?</p>
<p>Let me know about your views.</p>
<p>Edited:</p>
<p>From the answers of below SO post</p>
<p><a href="http://stackoverflow.com/questions/12581333/android-app-power-consumption">Android App power consumption</a></p>
<p>I used "Battery Historian" and generated batteryinfo.txt and batteryinfo.html</p>
<p>The Batteryinfo.txt is as follows</p>
<pre><code>Battery History:
-3m04s883ms 090 6c120104 status=discharging health=overheat plug=none temp=0 volt=3797 +screen +phone_scanning +wifi +wifi_running +wake_lock +sensor brightness=bright phone_state=out
-3m02s651ms 090 6c1a0104 status=charging plug=usb volt=4123 +plugged
-3m00s087ms 090 6c1a0104 volt=4090
-2m57s951ms 090 6c1a0104 volt=4125
-2m43s775ms 090 6c1a0104 volt=4123
-2m41s563ms 087 6c1a0104
-2m31s787ms 087 6c1a0104 volt=4114
-2m28s300ms 087 6c1a0104 volt=4112
-2m26s037ms 087 6c1a0104 volt=4114
-2m22s891ms 087 6c1a0104 volt=4112
-2m20s797ms 087 6c1a0104 volt=4134
-2m08s632ms 087 6c1a0104 volt=3849
-2m06s567ms 083 6c1a0104 volt=3838
-2m04s370ms 083 6c1a0104 volt=4123
-1m43s700ms 087 6c1a0104 volt=4122
-1m32s936ms 087 6c1a0104 volt=4007
-1m22s724ms 083 6c1a0104 health=good
-1m02s524ms 080 6c1a0104 volt=3957
Per-PID Stats:
PID 166 wake time: +203ms
PID 109 wake time: +2m57s295ms
Statistics since last charge:
System starts: 0, currently on battery: false
Time on battery: 2s 232ms (0.0%) realtime, 2s 232ms (0.0%) uptime
Total run time: 3d 15h 52m 45s 402ms realtime, 1d 9h 16m 33s 630ms uptime,
Screen on: 2s 231ms (100.0%), Input events: 0, Active phone call: 0ms (0.0%)
Screen brightnesses: bright 2s 231ms (100.0%)
Kernel Wake lock "PowerManagerService": 2s 191ms (0 times) realtime
Kernel Wake lock "power-supply": 412ms (1 times) realtime
Kernel Wake lock "main": 2s 191ms (0 times) realtime
Total received: 0B, Total sent: 0B
Total full wakelock time: 2s 197ms , Total partial waklock time: 2s 203ms
Signal levels: none 2s 231ms (100.0%) 0x
Signal scanning time: 2s 231ms
Radio types: none 2s 231ms (100.0%) 0x
Radio data uptime when unplugged: 0 ms
Wifi on: 2s 231ms (100.0%), Wifi running: 2s 231ms (100.0%), Bluetooth on: 0ms (0.0%)
Device battery use since last full charge
Amount discharged (lower bound): 0
Amount discharged (upper bound): 0
Amount discharged while screen on: 0
Amount discharged while screen off: 0
#1000:
User activity: 2 other
Sensor 2: 2s 206ms realtime (0 times)
#1013:
Wake lock AudioIn_369: 2s 203ms partial (1 times) realtime
#10010:
Apk com.android.providers.media:
Service com.android.providers.media.MtpService:
Created for: 0ms uptime
Starts: 1, launches: 1
#10029:
Wake lock Samsung Recognition Service: 2s 197ms full (0 times) realtime
Statistics since last unplugged:
Time on battery: 2s 232ms (1.2%) realtime, 2s 232ms (1.2%) uptime
Total run time: 3m 4s 912ms realtime, 3m 4s 911ms uptime,
Screen on: 2s 232ms (100.0%), Input events: 0, Active phone call: 0ms (0.0%)
Screen brightnesses: bright 2s 232ms (100.0%)
Kernel Wake lock "PowerManagerService": 2s 191ms (0 times) realtime
Kernel Wake lock "power-supply": 412ms (1 times) realtime
Kernel Wake lock "main": 2s 191ms (0 times) realtime
Total received: 0B, Total sent: 0B
Total full wakelock time: 2s 232ms , Total partial waklock time: 2s 232ms
Signal levels: none 2s 232ms (100.0%) 0x
Signal scanning time: 2s 232ms
Radio types: none 2s 232ms (100.0%) 0x
Radio data uptime when unplugged: 0 ms
Wifi on: 2s 232ms (100.0%), Wifi running: 2s 232ms (100.0%), Bluetooth on: 0ms (0.0%)
Device is currently plugged into power
Last discharge cycle start level: 90
Last discharge cycle end level: 90
Amount discharged while screen on: 0
Amount discharged while screen off: 0
#1000:
User activity: 2 other
Sensor 2: 2s 232ms realtime (0 times)
#1013:
Wake lock AudioIn_369: 2s 232ms partial (1 times) realtime
#10010:
Apk com.android.providers.media:
Service com.android.providers.media.MtpService:
Created for: 0ms uptime
Starts: 1, launches: 1
#10029:
Wake lock Samsung Recognition Service: 2s 232ms full (0 times) realtime
</code></pre>
<p>When I open Batteryinfo.html it displaying "<strong>Cannot Find End Time</strong>".</p>
<p>I followed the answers in the below post and commented out the code as mentioned</p>
<p><a href="http://stackoverflow.com/questions/34487749/battery-historian-cannot-find-end-time-android">Battery historian cannot find end time android</a></p>
<p>This time when I run the commd to generate batteryinfo.html from batteryinfo.html it displaying an error (Which is referrinf to the commented out code of 3 lines)</p>
<p>NOTE: As my device is not supporting to use batterystats and so am using batteryinfo.</p>
<p>Any help on this please. I want to open the batteryinfo.html with the details</p>
| 0 | 2016-08-18T07:35:04Z | 39,494,352 | <p>I don't know what you mean by can't read estimated value in the setting.</p>
<p>Look at my answer in <a href="http://stackoverflow.com/questions/12581333/android-app-power-consumption">Android App power consumption</a> </p>
<p>"
First, the powertutor from Google Play is out of date. I've checked the source code of it, and find that the power estimation model is for some old mobile model. The value from power tutor is way smaller than the actual power consumption.</p>
<p>Therefore, I would recommend to use Battery Historian which is development by google used to estimate battery consumption of each App. But it's written in Python/Go. It will show the hardware invocation in a html file. And you can find battery consumption of each App in a corresponding text file.</p>
<p><a href="https://developer.android.com/studio/profile/battery-historian.html" rel="nofollow">https://developer.android.com/studio/profile/battery-historian.html</a>
"</p>
<p>It will create a batterystats.txt, showing exactly the same as it in the setting.</p>
| 0 | 2016-09-14T15:30:04Z | [
"android",
"python",
"python-2.7",
"battery",
"measurement"
] |
passing many arguments to one placeholder of django cursor (placeholer in IN) | 39,012,390 | <p>I mean something like this:</p>
<pre><code>from django.db import connection
cursor=connection.cursor()
cursor.execute('SELECT * FROM mytable where id IN (%s)', [params])
</code></pre>
<p>Parameters can not be just iterable - it doesn't work.
Cannot be also in CSV format due escaping value by db handler.</p>
<p>How to use placeholder within <code>IN</code> ?</p>
<hr>
<p>By CSV is wrong, I mean that for <code>params=['1','2','3','4','5']</code></p>
<pre><code>c.execute('select * from mytable where id in (%s)', [','.join(params)])
</code></pre>
<p>will produce:</p>
<pre><code>select * from mytable where id in ('1,2,3,4,5')
</code></pre>
<p>but correct sql is:</p>
<pre><code>select * from mytable where id in (1,2,3,4,5)
</code></pre>
<p>and it seems to be hard to achieve with placeholders.</p>
| 0 | 2016-08-18T07:35:14Z | 39,012,670 | <p><strong>Updated Answer</strong>
Sorry about the older answer. This should work as you want, but might not be the best solution. I tried it with both, params as a list of strings and a list of integers.</p>
<pre><code>from django.db import connection
params = [1, 2, 3, '4', '5']
placeholders = ('%s,'*len(params)).rstrip(',') # Having a comma at the end will give a syntax error
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM mytable where id IN ({})'.format(placeholders), params)
# Use the cursor here
</code></pre>
<p><strong>End updated answer</strong></p>
<hr>
<p>In SQL the value for <code>IN</code> needs to be a comma separated list</p>
<pre><code>SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
</code></pre>
<p><strike>
So the simplest approach for you, assuming that params is an iterable would be </p>
<pre><code>from django.db import connection
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM mytable where id IN (%s)', [', '.join(params)])
</code></pre>
<p>The join will convert your iterable params into a comma separated string which will then replace the %s.
</strike> </p>
<p>Generally you will want your query params to be escaped. Even the data you stored should be escaped.</p>
<p><strong>Edit:</strong> Also notice that I have moved your cursor into a <code>with</code> block. You should always close your connections. <a href="https://docs.djangoproject.com/en/1.10/topics/db/sql/#connections-and-cursors" rel="nofollow">Read up more here</a>.</p>
| 1 | 2016-08-18T07:53:05Z | [
"python",
"sql",
"django",
"placeholder"
] |
passing many arguments to one placeholder of django cursor (placeholer in IN) | 39,012,390 | <p>I mean something like this:</p>
<pre><code>from django.db import connection
cursor=connection.cursor()
cursor.execute('SELECT * FROM mytable where id IN (%s)', [params])
</code></pre>
<p>Parameters can not be just iterable - it doesn't work.
Cannot be also in CSV format due escaping value by db handler.</p>
<p>How to use placeholder within <code>IN</code> ?</p>
<hr>
<p>By CSV is wrong, I mean that for <code>params=['1','2','3','4','5']</code></p>
<pre><code>c.execute('select * from mytable where id in (%s)', [','.join(params)])
</code></pre>
<p>will produce:</p>
<pre><code>select * from mytable where id in ('1,2,3,4,5')
</code></pre>
<p>but correct sql is:</p>
<pre><code>select * from mytable where id in (1,2,3,4,5)
</code></pre>
<p>and it seems to be hard to achieve with placeholders.</p>
| 0 | 2016-08-18T07:35:14Z | 39,013,919 | <p>Solution is rather simple:</p>
<p><code>c.execute('select * from mytable where id in (%s)' % (','.join(params),))</code></p>
<p>See similar topic:
<a href="http://stackoverflow.com/questions/589284/imploding-a-list-for-use-in-a-python-mysqldb-in-clause">imploding a list for use in a python MySQLDB IN clause</a></p>
| 0 | 2016-08-18T08:57:41Z | [
"python",
"sql",
"django",
"placeholder"
] |
passing many arguments to one placeholder of django cursor (placeholer in IN) | 39,012,390 | <p>I mean something like this:</p>
<pre><code>from django.db import connection
cursor=connection.cursor()
cursor.execute('SELECT * FROM mytable where id IN (%s)', [params])
</code></pre>
<p>Parameters can not be just iterable - it doesn't work.
Cannot be also in CSV format due escaping value by db handler.</p>
<p>How to use placeholder within <code>IN</code> ?</p>
<hr>
<p>By CSV is wrong, I mean that for <code>params=['1','2','3','4','5']</code></p>
<pre><code>c.execute('select * from mytable where id in (%s)', [','.join(params)])
</code></pre>
<p>will produce:</p>
<pre><code>select * from mytable where id in ('1,2,3,4,5')
</code></pre>
<p>but correct sql is:</p>
<pre><code>select * from mytable where id in (1,2,3,4,5)
</code></pre>
<p>and it seems to be hard to achieve with placeholders.</p>
| 0 | 2016-08-18T07:35:14Z | 39,035,248 | <p>You cannot use <code>IN</code> for this since indeed, in expects a sequence of ints, but the ORM translates a list to an <code>ARRAY</code>, and if you use <code>join</code> you'll end up with a string.</p>
<p>The solution is to use the equivalent <code>ANY</code>. The formatting is slightly different, but this should work for you:</p>
<pre><code>c.execute('select * from mytable where id = ANY(%s)', [params])
</code></pre>
<p>Given <code>params = [1, 2, 3, 4, 5]</code>, the resulting SQL will be:</p>
<pre><code>SELECT * FROM mytable where id = ANY(ARRAY[1, 2, 3, 4, 5])
</code></pre>
<p>Note that this requires the list of ids to be made up of ints, so if you have a list of strings be sure to convert them first.</p>
| 0 | 2016-08-19T09:11:31Z | [
"python",
"sql",
"django",
"placeholder"
] |
How get equation after fitting in scikit-learn? | 39,012,611 | <p>I want to use <a href="http://scikit-learn.org/stable/" rel="nofollow">scikit-learn</a> for calculating the equation of some data. I used this code to fit a curve to my data:</p>
<pre><code>svr_lin = SVR(kernel='linear', C=1e3)
y_lin = svr_lin.fit(X, y).predict(Xp)
</code></pre>
<p>But I don't know what I should do to get the exact equation of the fitted model.
Do you know how I can get these equations?</p>
| 1 | 2016-08-18T07:49:14Z | 39,022,912 | <p>Here is an example:</p>
<pre><code>from sklearn.datasets import load_boston
from sklearn.svm import SVR
boston = load_boston()
X = boston.data
y = boston.target
svr = SVR(kernel='linear')
svr.fit(X,y);
print('weights: ')
print(svr.coef_)
print('Intercept: ')
print(svr.intercept_)
</code></pre>
<p>the output is:</p>
<pre><code>weights:
[[-0.14125916 0.03619729 -0.01672455 1.35506651 -2.42367649 5.19249046
-0.0307062 -0.91438543 0.17264082 -0.01115169 -0.64903308 0.01144761
-0.33160831]]
Intercept:
[ 11.03647437]
</code></pre>
<p>And for a linear kernel, your fitted model is a hyperplane (<strong>ω</strong>^[T] <strong>x</strong>+ b = 0), where <strong>ω</strong> is the vector of weights and b is the intercept.</p>
| 2 | 2016-08-18T16:08:02Z | [
"python",
"scikit-learn"
] |
Python: List with [< >, <>...] | 39,012,656 | <p>I'm using PySVN to get diff between 2 links, and the function I'm using returns a list with '<>':</p>
<pre><code>[<PysvnDiffSummary u'sdk_include/EthernetScannerSDK.h'>, <PysvnDiffSummary u'sdk_include/EthernetScannerSDKDefine.h'>, <PysvnDiffSummary u'sdk_include/CMakeLists.txt'>]
</code></pre>
<p>What exactly is this type of data? And how can I acces only the part after " ' "? (E.G. from < PysvnDiffSummary u'sdk_include/EthernetScannerSDK.h' > I only want sdk_include/EthernetScannerSDK.h, without using .split(' \' ') if possible.</p>
| 1 | 2016-08-18T07:52:26Z | 39,012,795 | <p>It's a representation of PySvnDiffSummary object. Try using dir(Object) to get it's attributes and from there. It's probably going to be something like object.url</p>
<p>so when you find out what the attribute is (from comments elsewhere, it's <code>__name</code>), you'll want something like:</p>
<pre><code>urls = [sumary.__name for summary in list]
</code></pre>
<p>Working list with just what you want :)</p>
| 1 | 2016-08-18T08:00:25Z | [
"python",
"pysvn"
] |
Regular expression matching lines that are not commented out | 39,012,690 | <p>Given the following code</p>
<pre><code>print("aaa")
#print("bbb")
# print("ccc")
def doSomething():
print("doSomething")
</code></pre>
<p>How can I use regular expression in Atom text editor to find all the <code>print</code> functions that are not commented out? I mean I only want to match the <code>print</code>s in <code>print("aaa")</code> and <code>print("doSomething")</code>.</p>
<p>I've tried <code>[^#]print</code>, but this also matches the <code>print</code> in <code># print("ccc")</code>, which is something that is not desired.</p>
<p><code>[^# ]print</code> doesn't match any line here.</p>
<p>The reason I want to do this is that I want to disable the log messages inside a legacy project written by others.</p>
| 3 | 2016-08-18T07:54:16Z | 39,012,940 | <p>I you want to match only the print (and not all arguments), you can use : </p>
<pre><code>^\s*(print)
</code></pre>
<p>See this live sample : <a href="http://refiddle.com/refiddles/57b56c8075622d22e8080000" rel="nofollow">http://refiddle.com/refiddles/57b56c8075622d22e8080000</a></p>
| 0 | 2016-08-18T08:07:06Z | [
"python",
"regex",
"atom"
] |
Regular expression matching lines that are not commented out | 39,012,690 | <p>Given the following code</p>
<pre><code>print("aaa")
#print("bbb")
# print("ccc")
def doSomething():
print("doSomething")
</code></pre>
<p>How can I use regular expression in Atom text editor to find all the <code>print</code> functions that are not commented out? I mean I only want to match the <code>print</code>s in <code>print("aaa")</code> and <code>print("doSomething")</code>.</p>
<p>I've tried <code>[^#]print</code>, but this also matches the <code>print</code> in <code># print("ccc")</code>, which is something that is not desired.</p>
<p><code>[^# ]print</code> doesn't match any line here.</p>
<p>The reason I want to do this is that I want to disable the log messages inside a legacy project written by others.</p>
| 3 | 2016-08-18T07:54:16Z | 39,013,954 | <p>Since you confirm my first suggestion (<code>^(?![ \t]*#)[ \t]*print</code>) worked for you (I deleted that first comment), I believe you just want to find the <code>print</code> on single lines. </p>
<p>The <code>\s</code> matches any whitespace, incl. newline symbols. If you need to just match tabs or spaces, use a <code>[ \t]</code> character class.</p>
<p>Use</p>
<pre><code>^[ \t]*print
</code></pre>
<p>or (a bit safer in order not to find any <code>printer</code>s):</p>
<pre><code>^[ \t]*print\(
</code></pre>
| 3 | 2016-08-18T08:59:44Z | [
"python",
"regex",
"atom"
] |
Changing words in a string using dictionary. python | 39,012,700 | <p>I have the following message:</p>
<pre><code>msg = "Cowlishaw Street &amp; Athllon Drive, Greenway now free of obstruction."
</code></pre>
<p>I want to change things such as "Drive" to "Dr" or "Street" to "St"</p>
<pre><code>expected_msg = "Cowlishaw St and Athllon Dr Greenway now free of obstruction"
</code></pre>
<p>I also have a "conversion function"</p>
<p>how do I check the list if such word is in it. and if so, change it with the "conversion" function. "conversion" is a dictionary that have word such as "Drive" act as a key and the value is "Dr"</p>
<p>this is what I have done</p>
<pre><code>def convert_message(msg, conversion):
msg = msg.translate({ord(i): None for i in ".,"})
tokens = msg.strip().split(" ")
for x in msg:
if x in keys (conversion):
return " ".join(tokens)
</code></pre>
| 0 | 2016-08-18T07:54:40Z | 39,013,014 | <p>Isn't it simply:</p>
<pre><code>translations = {'Drive': 'Dr'}
for index, token in enumerate(tokens):
if token in conversion:
tokens[index] = conversion[token]
return ' '.join(tokens)
</code></pre>
<p>However, this wouldn't work on sentences like <code>"Obstruction on Cowlishaw Street."</code> since the token now would be <code>Street.</code>. Perhaps you should use a regular expression with <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a>:</p>
<pre><code>import re
def convert_message(msg, conversion):
def translate(match):
word = match.group(0)
if word in conversion:
return conversion[word]
return word
return re.sub(r'\w+', translate, msg)
</code></pre>
<p>Here the <code>re.sub</code> finds 1 or more consecutive (<code>+</code>) alphanumeric characters (<code>\w</code>); and for each such regular expression match calls the given function, giving the match as a parameter; the matched word can be retrieved with <code>match.group(0)</code>. The function should return a replacement for the given match - here, if the word is found in the dictionary we return that instead, otherwise the original is returned.</p>
<p>Thus:</p>
<pre><code>>>> msg = "Cowlishaw Street &amp; Athllon Drive, Greenway now free of obstruction."
>>> convert_message(msg, {'Drive': 'Dr', 'Street': 'St'})
'Cowlishaw St &amp; Athllon Dr, Greenway now free of obstruction.'
</code></pre>
<hr>
<p>As for the <code>&amp;</code>, on Python 3.4+ you should use <a href="https://docs.python.org/3/library/html.html#html.unescape" rel="nofollow"><code>html.unescape</code></a> to decode HTML entities:</p>
<pre><code>>>> import html
>>> html.unescape('Cowlishaw Street &amp; Athllon Drive, Greenway now free of obstruction.')
'Cowlishaw Street & Athllon Drive, Greenway now free of obstruction.'
</code></pre>
<p>This will take care of <em>all</em> known HTML entities. For older python versions you can see <a href="http://stackoverflow.com/questions/2087370/decode-html-entities-in-python-string">alternatives on this question</a>.</p>
<p>The regular expression does not match the <code>&</code> character; if you want to replace it too, we can use regular expression <code>\w+|.</code> which means: "any consecutive run of alphanumeric characters, or then any single character that is not in such a run":</p>
<pre><code>import re
import html
def convert_message(msg, conversion):
msg = html.unescape(msg)
def translate(match):
word = match.group(0)
if word in conversion:
return conversion[word]
return word
return re.sub(r'\w+|.', translate, msg)
</code></pre>
<p>Then you can do</p>
<pre><code>>>> msg = 'Cowlishaw Street &amp; Athllon Drive, Greenway now free of obstruction.'
>>> convert_message(msg, {'Drive': 'Dr', '&': 'and',
'Street': 'St', '.': '', ',': ''})
'Cowlishaw St and Athllon Dr Greenway now free of obstruction'
</code></pre>
| 0 | 2016-08-18T08:10:58Z | [
"python",
"string",
"dictionary"
] |
Need to extract all the font sizes and the text using beautifulsoup | 39,012,739 | <p>I have the following html file stored on my local system:</p>
<pre><code><span style="position:absolute; border: gray 1px solid; left:0px; top:50px; width:612px; height:792px;"></span>
<div style="position:absolute; top:50px;"><a name="1">Page 1</a></div>
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:71px; width:322px; height:38px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:30px">One
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:104px; width:175px; height:40px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Two</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: two txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Three</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Three txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Four</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Four txt
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:274px; top:144px; width:56px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">FIVE
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:171px; width:515px; height:44px;"><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">five txt
<br>five txt2
<br>five txt3
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:220px; top:223px; width:164px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">SIX
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:44px; top:247px; width:489px; height:159px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:17px">six txt
<br></span><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">six txt2
<br>- six txt2
<br>⢠six txt3
<br>⢠six txt4
<br>⢠six txt5
<br></span>
</code></pre>
<p>I need to extract all the font-sizes that occur in this html file. I am using beautifulsoup, but I know only how to extract the text.</p>
<p>I can extract the text using the following code:</p>
<pre><code>from bs4 import BeautifulSoup
htmlData = open('/home/usr/Downloads/files/output.html', 'r')
soup = BeautifulSoup(htmlData)
texts = soup.findAll(text=True)
</code></pre>
<p>I need to extract the font size of each piece of text and store the font-text pair into a list or array. To be specific, I want to have a data structure like <code>[('One','30'),('Two','15')]</code> and so on where 30 is from the <code>font-size:30px</code> and 15 from <code>font-size:15px</code></p>
<p>The only problem is that I can't figure out a way to get the font-size value. Any ideas? </p>
| 0 | 2016-08-18T07:57:18Z | 39,013,822 | <p>You have to make some research for your self, the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">beautiful soup documentation</a> and the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regex doc</a> are something that you should read and understand how the things flow.</p>
<p>Check out the following example which using a regular expression to extract the <strong>first</strong> occurrence of the font-size and then splitted properly to get only the pixel numbers.</p>
<pre><code>from bs4 import BeautifulSoup as Soup
from bs4 import Tag
import re
data = """
<span style="position:absolute; border: gray 1px solid; left:0px; top:50px; width:612px; height:792px;"></span>
<div style="position:absolute; top:50px;"><a name="1">Page 1</a></div>
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:71px; width:322px; height:38px;">
<span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:30px">One
<br></span>
</div>
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:104px; width:175px; height:40px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Two</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: two txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Three</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Three txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Four</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Four txt
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:274px; top:144px; width:56px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">FIVE
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:171px; width:515px; height:44px;"><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">five txt
<br>five txt2
<br>five txt3
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:220px; top:223px; width:164px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">SIX
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:44px; top:247px; width:489px; height:159px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:17px">six txt
<br></span><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">six txt2
<br>- six txt2
<br> six txt3
<br> six txt4
<br> six txt5
<br></span>
"""
soup = Soup(data, 'html.parser')
def get_the_start_of_font(attr):
""" Return the index of the 'font-size' first occurrence or None. """
match = re.search(r'font-size:', attr)
if match is not None:
return match.start()
return None
def get_font_size_from(attr):
""" Return the font size as string or None if not found. """
font_start_i = get_the_start_of_font(attr)
if font_start_i is not None:
return str(attr[font_start_i + len('font-size:'):].split('px')[0])
return None
# iterate through all descendants:
fonts = []
for child in soup.descendants:
if isinstance(child, Tag) is True and child.get('style') is not None:
font = get_font_size_from(child.get('style'))
if font is not None:
fonts.append([
str(child.text).strip(), font])
print(fonts)
</code></pre>
<p>The solution can be improved, but this is a working example.</p>
| 0 | 2016-08-18T08:53:03Z | [
"python",
"html",
"fonts",
"beautifulsoup"
] |
Need to extract all the font sizes and the text using beautifulsoup | 39,012,739 | <p>I have the following html file stored on my local system:</p>
<pre><code><span style="position:absolute; border: gray 1px solid; left:0px; top:50px; width:612px; height:792px;"></span>
<div style="position:absolute; top:50px;"><a name="1">Page 1</a></div>
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:71px; width:322px; height:38px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:30px">One
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:104px; width:175px; height:40px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Two</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: two txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Three</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Three txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Four</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Four txt
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:274px; top:144px; width:56px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">FIVE
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:171px; width:515px; height:44px;"><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">five txt
<br>five txt2
<br>five txt3
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:220px; top:223px; width:164px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">SIX
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:44px; top:247px; width:489px; height:159px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:17px">six txt
<br></span><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">six txt2
<br>- six txt2
<br>⢠six txt3
<br>⢠six txt4
<br>⢠six txt5
<br></span>
</code></pre>
<p>I need to extract all the font-sizes that occur in this html file. I am using beautifulsoup, but I know only how to extract the text.</p>
<p>I can extract the text using the following code:</p>
<pre><code>from bs4 import BeautifulSoup
htmlData = open('/home/usr/Downloads/files/output.html', 'r')
soup = BeautifulSoup(htmlData)
texts = soup.findAll(text=True)
</code></pre>
<p>I need to extract the font size of each piece of text and store the font-text pair into a list or array. To be specific, I want to have a data structure like <code>[('One','30'),('Two','15')]</code> and so on where 30 is from the <code>font-size:30px</code> and 15 from <code>font-size:15px</code></p>
<p>The only problem is that I can't figure out a way to get the font-size value. Any ideas? </p>
| 0 | 2016-08-18T07:57:18Z | 39,015,419 | <p>Hope this helps : I suggest you to read more documents on <code>BeautifulSoup</code></p>
<pre><code>from bs4 import BeautifulSoup
htmlData = open('/home/usr/Downloads/files/output.html', 'r')
soup = BeautifulSoup(htmlData)
font_spans = [ data for data in soup.select('span') if 'font-size' in str(data) ]
output = []
for i in font_spans:
tup = ()
fonts_size = re.search(r'(?is)(font-size:)(.*?)(px)',str(i.get('style'))).group(2)
tup = (str(i.text).strip(),fs.strip())
output.append(tup)
print(output)
[('One', '30'),('Two', '15'), ....]
</code></pre>
<p>If you want to eliminate text values which contains <code>txt</code> you may add <code>if not 'txt' in i.text:</code></p>
<p>Explanation : </p>
<p>First you need to identify tags which contains <code>font-size</code>,</p>
<pre><code>font_spans = [ data for data in soup.select('span') if 'font-size' in str(data) ]
</code></pre>
<p>Then you need to iterate <code>font_spans</code> and extract font-size and text value,</p>
<pre><code>textvalue = i.text # One,Two..
fonts_size = re.search(r'(?is)(font-size:)(.*?)(px)',str(i.get('style'))).group(2) # 30, 15, 16..
</code></pre>
<p>and Finally you need to create a list which contains all your output as in tuples.</p>
| 1 | 2016-08-18T10:07:20Z | [
"python",
"html",
"fonts",
"beautifulsoup"
] |
Need to extract all the font sizes and the text using beautifulsoup | 39,012,739 | <p>I have the following html file stored on my local system:</p>
<pre><code><span style="position:absolute; border: gray 1px solid; left:0px; top:50px; width:612px; height:792px;"></span>
<div style="position:absolute; top:50px;"><a name="1">Page 1</a></div>
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:71px; width:322px; height:38px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:30px">One
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:104px; width:175px; height:40px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Two</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: two txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Three</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Three txt
<br></span><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:15px">Four</span><span style="font-family: CAAAAA+DejaVuSans; font-size:16px">: Four txt
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:274px; top:144px; width:56px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">FIVE
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:171px; width:515px; height:44px;"><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">five txt
<br>five txt2
<br>five txt3
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:220px; top:223px; width:164px; height:19px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:19px">SIX
<br></span></div><div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:44px; top:247px; width:489px; height:159px;"><span style="font-family: BAAAAA+DejaVuSans-Bold; font-size:17px">six txt
<br></span><span style="font-family: CAAAAA+DejaVuSans; font-size:18px">six txt2
<br>- six txt2
<br>⢠six txt3
<br>⢠six txt4
<br>⢠six txt5
<br></span>
</code></pre>
<p>I need to extract all the font-sizes that occur in this html file. I am using beautifulsoup, but I know only how to extract the text.</p>
<p>I can extract the text using the following code:</p>
<pre><code>from bs4 import BeautifulSoup
htmlData = open('/home/usr/Downloads/files/output.html', 'r')
soup = BeautifulSoup(htmlData)
texts = soup.findAll(text=True)
</code></pre>
<p>I need to extract the font size of each piece of text and store the font-text pair into a list or array. To be specific, I want to have a data structure like <code>[('One','30'),('Two','15')]</code> and so on where 30 is from the <code>font-size:30px</code> and 15 from <code>font-size:15px</code></p>
<p>The only problem is that I can't figure out a way to get the font-size value. Any ideas? </p>
| 0 | 2016-08-18T07:57:18Z | 39,016,902 | <p>You can use a <em>css select</em> <code>select("[style*=font-size]")</code> to fing tags with a style attribute that contains <em>font-size</em> and use a regex to extract the value:</p>
<pre><code>In [12]: from bs4 import BeautifulSoup
In [13]: import re
In [14]: soup = BeautifulSoup(html, "html.parser")
In [15]: patt = re.compile("font-size:(\d+)")
In [16]: [(tag.text.strip(), patt.search(tag["style"]).group(1)) for tag in soup.select("[style*=font-size]")]
Out[16]:
[('One', '30'),
('Two', '15'),
(': two txt', '16'),
('Three', '15'),
(': Three txt', '16'),
('Four', '15'),
(': Four txt', '16'),
('FIVE', '19'),
('five txt\nfive txt2\nfive txt3', '18'),
('SIX', '19'),
('six txt', '17'),
('six txt2\n- six txt2\n⢠six txt3\n⢠six txt4\n⢠six txt5', '18')]
</code></pre>
| 1 | 2016-08-18T11:20:55Z | [
"python",
"html",
"fonts",
"beautifulsoup"
] |
Alternative to numpy.random.poisson() for drawin a SINGLE poisson distributed random number | 39,012,787 | <p>I noticed that drawing <strong>single</strong> random numbers using <code>numpy.random</code> is generally way slower than using <code>random</code>, obviously because <code>numpy.random</code> is optimized for drawing a bunch of random numbers in one shot. E.g., timings for sampling a random integer from a list are shown here:</p>
<pre><code>import timeit
setup = '''
import random
import numpy
'''
min(timeit.Timer('numpy.random.choice(range(100))',setup=setup).repeat(10, int(1e4)))
min(timeit.Timer('random.choice(range(100))', setup=setup).repeat(10, int(1e4)))
</code></pre>
<p>numpy.random: 0.1427</p>
<p>random : 0.0095</p>
<p>Now I need to draw single poission distributed random variables with <strong>variable</strong> lambda parameter, which implies that I cannot generation a bunch of them in one run for later usage. Hence, I seek an alternative to <code>numpy.random.poisson()</code>, because I expect, analogous to the above result, that using it will extremely slow me down. However, <code>random</code> does not offer the poisson distribution (why?).</p>
| 0 | 2016-08-18T07:59:54Z | 39,014,499 | <p>You can create all values at once by passing in an iterable of lambdas:</p>
<pre><code>numpy.random.poisson(lam=numpy.arange(200), size=(100, 200))
</code></pre>
<p>this will return 100 values for each of the 200 different lambda (100 * 200 values in total) values in one execution.</p>
| 0 | 2016-08-18T09:24:23Z | [
"python"
] |
Python - Remove 'style'-attribute from HTML | 39,012,857 | <p>I have a String in Python, which has some HTML in it. Basically it looks like this.</p>
<pre><code>>>> print someString # I get someString from the backend
"<img style='height:50px;' src='somepath'/>"
</code></pre>
<p>I try to display this HTML in a PDF. Because my PDF generator can't handle the styles-attribute (and no, I can't take another one), I have to remove it from the string. So basically, it should be like that:</p>
<pre><code>>>> print someString # I get someString from the backend
"<img style='height:50px;' src='somepath'/>"
>>> parsedString = someFunction(someString)
>>> print parsedString
"<img src='somepath'/>"
</code></pre>
<p>I guess the best way to do this is with RegEx, but I'm not very keen on it. Can someone help me out?</p>
| -1 | 2016-08-18T08:03:08Z | 39,013,125 | <p>I wouldn't use RegEx with this because </p>
<ol>
<li>Regex is not really suited for HTML parsing and even though this is a simple one there could be many variations and edge cases you need to consider and the resulting regex could turn out to be a nightmare</li>
<li>Regex sucks. It can be really useful but honestly, they are the epitome of user unfriendly.</li>
</ol>
<p>Alright, so how would I go about it. I would use trusty <code>BeautifulSoup</code>! Install with pip by using the following command:</p>
<p><code>pip install beautifulsoup4</code></p>
<p>Then you can do the following to remove the style:</p>
<pre><code>from bs4 import BeautifulSoup as Soup
del Soup(someString).find('img')['style']
</code></pre>
<p>This first parses your string, then finds the <code>img</code> tag and then deletes its <code>style</code> attribute.</p>
<p>It should also work with arbitrary strings but I can't promise that. Maybe you will come up with an edge case.</p>
<p>Remember, using RegEx to parse an HTML string is not the best of ideas. The internet and Stackoverflow is full of answers why this is not possible.</p>
<p>Edit: Just for kicks you might want to check out this <a href="http://stackoverflow.com/a/1732454/2570695">answer</a>. You know stuff is serious when it is said that even Jon Skeet can't do it.</p>
| 0 | 2016-08-18T08:17:23Z | [
"python",
"html"
] |
Python - Remove 'style'-attribute from HTML | 39,012,857 | <p>I have a String in Python, which has some HTML in it. Basically it looks like this.</p>
<pre><code>>>> print someString # I get someString from the backend
"<img style='height:50px;' src='somepath'/>"
</code></pre>
<p>I try to display this HTML in a PDF. Because my PDF generator can't handle the styles-attribute (and no, I can't take another one), I have to remove it from the string. So basically, it should be like that:</p>
<pre><code>>>> print someString # I get someString from the backend
"<img style='height:50px;' src='somepath'/>"
>>> parsedString = someFunction(someString)
>>> print parsedString
"<img src='somepath'/>"
</code></pre>
<p>I guess the best way to do this is with RegEx, but I'm not very keen on it. Can someone help me out?</p>
| -1 | 2016-08-18T08:03:08Z | 39,013,319 | <p>Using RegEx to work with HTML is a very bad idea but if you really want to use it, try this:</p>
<pre><code>/style=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/ig
</code></pre>
| 0 | 2016-08-18T08:27:23Z | [
"python",
"html"
] |
Python3 and elementium | 39,012,863 | <p>I'm trying to refactor my tests from Python 2.7 to Python 3.5. On this moment I've got problem with elementium lib. What is wrong with this lib?</p>
<pre><code>return SeElements(
self.browser, context=self, fn=lambda context: [context.items[i]], config=self.config)
</code></pre>
<p>Error:</p>
<pre><code>File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/elementium/drivers/se.py", line 96, in <lambda>
self.browser, context=self, fn=lambda context: [context.items[i]],
TypeError: list indices must be integers or slices, not str
</code></pre>
| 0 | 2016-08-18T08:03:21Z | 39,018,391 | <p>At the moment you are passing a value <code>i</code> to the <code>items</code> list. The error is pretty descriptive, it is complaining that the value of i is a string, not an integer. To access a list element by its index you must provide integer. </p>
<p>Can you share a bit of the code where you define <code>i</code>? Perhaps you just need to call int() function on it?</p>
| 0 | 2016-08-18T12:34:28Z | [
"python",
"python-2.7",
"python-3.x",
"pycharm"
] |
Scrapy making Request with POST method | 39,012,902 | <p>I'm trying to scrape a list of product from "<a href="http://eastasiaeg.com/en/laptop-in-egypt" rel="nofollow">http://eastasiaeg.com/en/laptop-in-egypt</a>"
using Scrapy. </p>
<p>Part of products loads dynamically, and a tried to build Scrapy request.
But something is wrong with it. Pls help.</p>
<pre><code># -*- coding: utf-8 -*-
import scrapy
from v4.items import Product
class IntelEGEastasiaegComSpider(scrapy.Spider):
name = "intel_eg_eastasiaeg_com_py"
start_urls = [
'http://eastasiaeg.com/en/laptop-in-egypt'
]
def start_requests(self):
request_body = {"categoryId":"3","manufacturerId":"0","vendorId":"0","priceRangeFilterModel7Spikes":{"CategoryId":"3","ManufacturerId":"0","VendorId":"0","SelectedPriceRange":{},"MinPrice":"2400","MaxPrice":"44625"},"specificationFiltersModel7Spikes":{"CategoryId":"3","ManufacturerId":"0","VendorId":"0","SpecificationFilterGroups":[{"Id":"27","FilterItems":[{"Id":"103","FilterItemState":"Unchecked"},{"Id":"104","FilterItemState":"Unchecked"},{"Id":"105","FilterItemState":"Unchecked"},{"Id":"110","FilterItemState":"Unchecked"}]},{"Id":"11","FilterItems":[{"Id":"302","FilterItemState":"Unchecked"},{"Id":"75","FilterItemState":"Unchecked"}]},{"Id":"6","FilterItems":[{"Id":"21","FilterItemState":"Unchecked"},{"Id":"24","FilterItemState":"Unchecked"},{"Id":"25","FilterItemState":"Unchecked"},{"Id":"26","FilterItemState":"Unchecked"}]},{"Id":"5","FilterItems":[{"Id":"1069","FilterItemState":"Unchecked"},{"Id":"1078","FilterItemState":"Unchecked"},{"Id":"1118","FilterItemState":"Unchecked"},{"Id":"1862","FilterItemState":"Unchecked"}]},{"Id":"2","FilterItems":[{"Id":"8","FilterItemState":"Unchecked"},{"Id":"10","FilterItemState":"Unchecked"},{"Id":"1451","FilterItemState":"Unchecked"},{"Id":"1119","FilterItemState":"Unchecked"}]},{"Id":"8","FilterItems":[{"Id":"61","FilterItemState":"Unchecked"},{"Id":"62","FilterItemState":"Unchecked"},{"Id":"63","FilterItemState":"Unchecked"}]},{"Id":"333","FilterItems":[{"Id":"2460","FilterItemState":"Unchecked"}]}]},"attributeFiltersModel7Spikes":"null","manufacturerFiltersModel7Spikes":{"CategoryId":"3","ManufacturerFilterItems":[{"Id":"2","FilterItemState":"Unchecked"},{"Id":"1","FilterItemState":"Unchecked"},{"Id":"3","FilterItemState":"Unchecked"},{"Id":"6","FilterItemState":"Unchecked"}]},"vendorFiltersModel7Spikes":"null","pageNumber":"2","orderby":"10","viewmode":"grid","pagesize":"null","queryString":"","shouldNotStartFromFirstPage":"true","onSaleFilterModel":"null","keyword":"","searchCategoryId":"0","searchManufacturerId":"0","priceFrom":"","priceTo":"","includeSubcategories":"False","searchInProductDescriptions":"False","advancedSearch":"False","isOnSearchPage":"False"}
for body in request_body:
request_body = body
yield scrapy.Request('http://eastasiaeg.com/en/getFilteredProducts',
method="POST",
body=request_body,
callback=self.parse,
headers={'Content-type': 'application/json; charset=UTF-8'}, )
def parse(self, response):
print response.body
</code></pre>
| 0 | 2016-08-18T08:05:21Z | 39,013,935 | <p>You should use <code>scrapy.FormRequest</code> when you want to do POST requests with form data in them. </p>
<pre><code>def start_requests(self):
form_data = {} # your formdata
yield scrapy.FormRequest(url, formdata=form_data)
</code></pre>
<p>Your approach could work as well, but your for loop doesn't make much sense here.<br>
<code>for body in request_body:</code> iterates through the keys of the dictionary that your <code>request_body</code> is and you basically make 24 requests with only 1 key in the body.<br>
So to do it with <code>scrapy.Request</code> try: </p>
<pre><code>def start_requests(self):
form_data = {} # your formdata
# Request only takes string as body so you need to
# convert python dict to string
request_body = json.dumps(form_data)
yield scrapy.Request('http://eastasiaeg.com/en/getFilteredProducts',
method="POST",
body=request_body,
headers={'Content-Type': 'application/json; charset=UTF-8'}, )
# Usually Content-Type matters here a lot.
</code></pre>
<p>P.S. scrapy Requests default to <code>self.parse</code> callback so you don't need to specify it.</p>
| 0 | 2016-08-18T08:58:37Z | [
"python",
"request",
"scrapy"
] |
How do I check if there is a string item in a list of mixed types, in python | 39,012,938 | <p>Say I have a <code>list l1 = ['s',1,2] and l2 = [1,2,3]</code>.
Obviously <code>l1</code> has an item of string type and <code>l2</code> doesn't.</p>
<p>But when a list gets super large and I do not know the items in a list, how do I know if this list contains an item of string type.</p>
| -1 | 2016-08-18T08:07:00Z | 39,013,037 | <pre><code>if any(isinstance(x, str) for x in your_list):
print("the list contains a string")
</code></pre>
| 5 | 2016-08-18T08:12:17Z | [
"python",
"string",
"list"
] |
How do I check if there is a string item in a list of mixed types, in python | 39,012,938 | <p>Say I have a <code>list l1 = ['s',1,2] and l2 = [1,2,3]</code>.
Obviously <code>l1</code> has an item of string type and <code>l2</code> doesn't.</p>
<p>But when a list gets super large and I do not know the items in a list, how do I know if this list contains an item of string type.</p>
| -1 | 2016-08-18T08:07:00Z | 39,013,048 | <p>You can use a loop and check if, at each index of your array, the value is corresponding to a number.
Use ascii code ( code 48 to 57 for 0 to 9)
If the ascii code of your value is between 48 and 57, you know it's a number.
If not, you know it's not a number.</p>
<p>Hope this helps</p>
| 1 | 2016-08-18T08:13:18Z | [
"python",
"string",
"list"
] |
How do I check if there is a string item in a list of mixed types, in python | 39,012,938 | <p>Say I have a <code>list l1 = ['s',1,2] and l2 = [1,2,3]</code>.
Obviously <code>l1</code> has an item of string type and <code>l2</code> doesn't.</p>
<p>But when a list gets super large and I do not know the items in a list, how do I know if this list contains an item of string type.</p>
| -1 | 2016-08-18T08:07:00Z | 39,013,069 | <p>You can try this:</p>
<p><code>if any(type(each_item) is str for each_item in l1):
# Do something</code></p>
| 0 | 2016-08-18T08:14:21Z | [
"python",
"string",
"list"
] |
How do I check if there is a string item in a list of mixed types, in python | 39,012,938 | <p>Say I have a <code>list l1 = ['s',1,2] and l2 = [1,2,3]</code>.
Obviously <code>l1</code> has an item of string type and <code>l2</code> doesn't.</p>
<p>But when a list gets super large and I do not know the items in a list, how do I know if this list contains an item of string type.</p>
| -1 | 2016-08-18T08:07:00Z | 39,013,084 | <p>The solution using <code>isinstance</code> function:</p>
<pre><code>def hasString(l):
for item in l:
if isinstance(item, str):
return True
return False
l1 = [1, 2, 3]
l2 = ['s', 2, 3]
print(hasString(l1)) # False
print(hasString(l2)) # True
</code></pre>
| 0 | 2016-08-18T08:15:43Z | [
"python",
"string",
"list"
] |
How do I check if there is a string item in a list of mixed types, in python | 39,012,938 | <p>Say I have a <code>list l1 = ['s',1,2] and l2 = [1,2,3]</code>.
Obviously <code>l1</code> has an item of string type and <code>l2</code> doesn't.</p>
<p>But when a list gets super large and I do not know the items in a list, how do I know if this list contains an item of string type.</p>
| -1 | 2016-08-18T08:07:00Z | 39,013,275 | <p>I just saw this post : <a href="http://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python">What's the canonical way to check for type in python?</a></p>
<p><strong>quote</strong> : <em>"Since Python encourages Duck Typing, you should just try to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!"</em>
(This answer were quite suprising to me)</p>
<p>The way i understood that is that you have to act like if all your items in your list were like you want (we don't know yet what do you want to do with your lists).</p>
| 1 | 2016-08-18T08:25:05Z | [
"python",
"string",
"list"
] |
SciPy's interp1d endpoints | 39,013,058 | <p>In SciPy's interpolation module there is a function called <strong>interp1d</strong>. The documentation says that it is a spline interpolation: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html</a> I could however nowhere find what is the boundary condition on the endpoints. For instance, in the case of a cubic spline, one should specify the derivatives (or the second derivatives) at the endpoints. What are the values used by interp1d?</p>
| 1 | 2016-08-18T08:13:46Z | 39,036,665 | <p><code>CubicSpline</code>, which is new in scipy 0.18, allows a user control over the boundary conditions. Neither FITPACK nor interp1d do.</p>
| 1 | 2016-08-19T10:25:08Z | [
"python",
"scipy",
"interpolation",
"cubic-spline"
] |
Skip directories in a search in Python | 39,013,059 | <p>Im running the following code, and i want to skip 3 folders with respective names:
folder1, folder2, .repository.</p>
<p>However if some of the folders is not present i get the error:</p>
<p>indentationerror: unindent does not match any outer indentation level</p>
<p>How can I search skipping that folders, and even if they are not present not get any error? Here my code:</p>
<pre><code>import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("."):
dirs.remove("folder1")
dirs.remove("folder2")
dirs.remove(".repo")
if "pom.xml" in files:
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file has been modified",p)
</code></pre>
<p>------UPDATE:</p>
<pre><code>import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("/home/temp/"):
dirs.remove("/home/temp/test1")
dirs.remove("/home/temp/test2")
dirs.remove("/home/temp/test3")
if "pom.xml" in files:
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file contains user code modules:-------------> ",p)
</code></pre>
<p>And here the output:</p>
<pre><code>python /home/temp/test_folder/python_script_4.py
File "/home/temp/test_folder/python_script_4.py", line 12
if "pom.xml" in files:
^
IndentationError: unexpected indent
</code></pre>
<p>LAST UPDATE ---------></p>
<pre><code>import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("/home/dlopez/temp/test_folder/"):
dirs.remove("/home/temp/test_folder/test1")
dirs.remove("/home/temp/test_folder/test2")
dirs.remove("/home/temp/test_folder/test3")
if "pom.xml" in files:
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file contains user code modules:-------------> ",p)
</code></pre>
<p>And my Output:</p>
<pre><code> python /home/temp/test_folder/python_script_5.py
Traceback (most recent call last):
File "/home/dlopez/temp/test_folder/python_script_5.py", line 8, in <module>
dirs.remove("/home/temp/test_folder/test1")
ValueError: list.remove(x): x not in list
</code></pre>
<p>Help please thanks! :)</p>
| -1 | 2016-08-18T08:13:52Z | 39,013,259 | <p>Your indentation of the if doesn't match the current indentation</p>
<pre><code>import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("/home/dlopez/temp/"):
dirs.remove("/home/dlopez/temp/test1")
dirs.remove("/home/dlopez/temp/test2")
dirs.remove("/home/dlopez/temp/test3")
if "pom.xml" in files: # The if statement is not aligned to anything
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file contains user code modules:-------------> ",p)
</code></pre>
<p>Change it to:</p>
<pre><code>import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("/home/dlopez/temp/"):
# Skip the dirs you want looping a list
for skipped in ("/home/dlopez/temp/test1", "/home/dlopez/temp/test1", "/home/dlopez/temp/test3"):
if skipped in dirs: dirs.remove(skipped)
if "pom.xml" in files:
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file contains user code modules:-------------> ",p)
</code></pre>
| 0 | 2016-08-18T08:24:11Z | [
"python"
] |
Trouble with Python3 imports | 39,013,061 | <p>This question was asked a lots of times but none of the solutions seem to help in my case.</p>
<p>I have a directory structure like this</p>
<pre><code>my_project/
main.py
bootstrap/
__init__.py
boot.py
consumer/
__init__.py
main.py
</code></pre>
<p>Being at the toplevel directory (<code>myproject</code>) and executing <code>python3 consumer/main.py</code> throws an error:</p>
<pre><code>Traceback (most recent call last):
File "consumer/main.py", line 7, in <module>
from bootstrap.boot import MyClass
ImportError: No module named 'bootstrap'
</code></pre>
<p>Weird thing is that importing that module using the interpreter works as expected. Running the code from PyCharm also works fine.</p>
<p>I've tried importing with "full path" e.g. <code>from my_project.bootstrap.boot import MyClass</code> which fails with the same <code>ImportError</code>. I have also tried using relative imports e.g. <code>from .bootstrap.boot import MyClass</code> which also failed with <code>SystemError: Parent module '' not loaded, cannot perform relative import</code></p>
<p>One hack that fixes this is when I add <code>export PYTHONPATH="/root/my_project"</code> at the bottom of virtualenv <code>activate</code> script</p>
| 0 | 2016-08-18T08:13:55Z | 39,013,627 | <p>You are getting this error because module search path only includes the current directory, and not its parents; and since your other module is not in the <code>PYTHONPATH</code> it isn't available to import.</p>
<p>You can find this out yourself by printing <code>sys.path</code> in your script.</p>
<p>I created a directory <code>t</code> with the following:</p>
<pre><code>$ tree
.
âââ a.py
âââ bar
â  âââ __init__.py
â  âââ world.py
âââ foo
âââ hello.py
âââ __init__.py
2 directories, 5 files
</code></pre>
<p>Here is the source of <code>hello.py</code>:</p>
<pre><code>$ cat foo/hello.py
import sys
print("I am in {}".format(__file__))
for path in sys.path:
print(path)
from bar.world import var
print(var)
</code></pre>
<p>Now watch what happens, when I execute <code>foo/hello.py</code> and try to import something from <code>bar/world.py</code>; </p>
<pre><code>$ python foo/hello.py
I am in foo/hello.py
/home/burhan/t/foo
/usr/lib/python2.7
/usr/lib/python2.7/plat-x86_64-linux-gnu
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
/home/burhan/.local/lib/python2.7/site-packages
/usr/local/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages
Traceback (most recent call last):
File "foo/hello.py", line 6, in <module>
from bar.world import var
ImportError: No module named bar.world
</code></pre>
<p>You can tell from the paths printed that only the system-wide Python library paths, and the current directory of the script is listed. This is why it cannot find <code>bar.world</code>.</p>
<p>To fix this issue, you can adjust the PYTHONPATH or use relative imports; for example:</p>
<pre><code>$ PYTHONPATH=../t python foo/hello.py
I am in foo/hello.py
/home/burhan/t/foo
/home/burhan/t
/usr/lib/python2.7
/usr/lib/python2.7/plat-x86_64-linux-gnu
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
/home/burhan/.local/lib/python2.7/site-packages
/usr/local/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages
42
</code></pre>
<p>You notice here I am manually overriding the <code>PYTHONTPATH</code> and adding the common parent of the scripts (<code>42</code> is coming from bar/world).</p>
<p>To fix this using relative imports, you first have a to create a package in the top most directory, otherwise you'll get the famous <code>Attempted relative import in non-package</code> error; for more on this and details on how Python 3 importing works, have a look at: <a href="http://stackoverflow.com/questions/16981921/relative-imports-in-python-3">Relative imports in Python 3</a></p>
| 4 | 2016-08-18T08:43:51Z | [
"python",
"python-3.x",
"import"
] |
How to savefig as show in matplotlib.pyplot? | 39,013,094 | <p>I'm using <code>matplotlib.pyplot</code> to draw a bar chart with a legend, the figure saved by <code>plt.savefig()</code> is incomplete compared to <code>plt.show()</code>. To be more precise, the legend is out of the plot, the jpg file only have the leftside half of the legend.</p>
<p>My codes:</p>
<pre><code>from matplotlib import pyplot as plt
fig = plt.figure(figsize=(12,6))
plt.bar(x, y, label="a")
plt.legend(bbox_to_anchor=(1.02, 1), loc="upper left")
plt.show()
fig.savefig("a.jpeg")
</code></pre>
<p>I looked through this answer <a href="http://stackoverflow.com/questions/8971834/matplotlib-savefig-with-a-legend-outside-the-plot">Matplotlib savefig with a legend outside the plot</a> but the chosen answer suggest to adjust the axis manually. I have many different figures so that may be inappropriate. Since it was posted years ago, I wonder whether any automatic method could be used to make the effect of <code>plt.savefig()</code> as <code>plt.show()</code>? I couldn't find any appropriate argument for that in <code>plt.savefig()</code>.</p>
<p>Thanks!</p>
| 0 | 2016-08-18T08:16:17Z | 39,013,772 | <p>Hope this will solve the problem.Add <code>bbox_inches='tight'</code> in the params which helps removing white spaces</p>
<pre><code> fig.savefig('a.jpeg', bbox_inches='tight', pad_inches=0)
</code></pre>
| 1 | 2016-08-18T08:51:03Z | [
"python",
"matplotlib",
"plot",
"legend"
] |
How to display two images on the same Tkinter Toplevel () window | 39,013,108 | <p>So I'm building an app which has the option to compare two photos. I put a listbox on the left side of the screen, and a place for the two photos on the right side of the screen. There are three buttons under the listbox which are used to place pictures under a certain title (Pic 1 or Pic 2). It works, but I can only put one photo on both Pic 1 and Pic 2 - if I select one photo and put it under Pic 1, then select another photo and put it under Pic 2, the first one dissappears. </p>
<p>For a better understanding of my problem, here is the photo browse function from my app.</p>
<pre><code>from Tkinter import *
import tkMessageBox
from PIL import ImageTk, Image
def photo_browse ():
def add_photo (screen, column_num):
if not "pic" in globals ():
tkMessageBox.showerror ("Error!", "No picture selected!")
screen.lift ()
else:
screen.image = pic
can = Label (screen, image = pic)
can.grid (row = 0, column = column_num)
Label (screen, text = chosen_photo).grid (row = 1, column = column_num)
def selection_listbox (evt):
global chosen_photo
chosen_photo = str (photo_listbox.get (photo_listbox.curselection ()))
image_location = "Pics/" + chosen_photo
global pict
pict = Image.open (image_location)
global pic
pic = ImageTk.PhotoImage (pict)
import glob
photo_browse_screen = Toplevel ()
photo_browse_screen.title ("Photo browse")
photo_browse_screen.geometry ("1000x600")
photo_browse_screen.resizable (0, 0)
photo_listbox = Listbox (photo_browse_screen, width = 50, height = 35)
photo_listbox.grid (columnspan = 3)
photo_listbox.bind ('<<ListboxSelect>>', selection_listbox)
name_list = glob.glob ("Pics/*.jpg")
name_list = [i [6:] for i in name_list]
name_list.sort ()
n = 1
m = 0
for i in name_list:
photo_listbox.insert (n, name_list [m])
n += 1
m += 1
Button (photo_browse_screen, text = "PIC 1", command = lambda: add_photo (photo_browse_screen, 4)).grid (row = 1, column = 0)
Button (photo_browse_screen, text = "PIC 2", command = lambda: add_photo (photo_browse_screen, 5)).grid (row = 1, column = 1)
Button (photo_browse_screen, text = "EXIT", command = photo_browse_screen.destroy).grid (row = 1, column = 2)
can_pic_1 = Label (photo_browse_screen, text = "Pic 1", font= "-weight bold")
can_pic_1.grid (row = 0, column = 4, padx = (200, 100), sticky = N)
can_pic_2 = Label (photo_browse_screen, text = "Pic 2", font= "-weight bold")
can_pic_2.grid (row = 0, column = 5, padx = (100, 150), sticky = N)
root = Tk ()
root.title ("Main menu")
root.geometry ("1000x600")
root.resizable (0, 0)
main_menu = Menu (root)
photos_menu = Menu (main_menu, tearoff = 0)
main_menu.add_cascade (label = "Photos", menu = photos_menu)
photos_menu.add_command (label = "Browse photos", command = photo_browse)
root.config (menu = main_menu)
root.mainloop ()
</code></pre>
<p>In a previous function (add photos) I resize photos to 308x440 dimension so they fit in this window perfectly.</p>
<p>After reviewing my code, I am almost positive that <code>global</code> variables are causing this problem, so if anyone can offer an alternative, I would be grateful.</p>
| 0 | 2016-08-18T08:16:41Z | 39,042,026 | <p>I'm using python 3.4 so i'm not 100% sure this will work for you (for me Tkinter is tkinter)</p>
<p>When I want to use multiple images I add them all to a list, you don't need to do anything with the list after that</p>
<p>This has always worked for me and I have the same problem you described without a list</p>
<pre><code>from Tkinter import *
import tkMessageBox
from PIL import ImageTk, Image
global all_images
all_images = []
def photo_browse ():
def selection_listbox (evt):
global chosen_photo
chosen_photo = str (photo_listbox.get (photo_listbox.curselection ()))
image_location = "Pics/" + chosen_photo
global pict
pict = Image.open (image_location)
global pic
pic = ImageTk.PhotoImage (pict)
# adding all the images to a list has worked for me in the past
global all_images
all_images = all_images + [chosen_photo, pic, pict]
</code></pre>
| 0 | 2016-08-19T14:51:46Z | [
"python",
"image",
"tkinter",
"listbox",
"global-variables"
] |
zipfile in Python produces not quite normal ZIP files | 39,013,110 | <p>In my project set of files are created and packed to ZIP archive to be used at Android mobile phone. Android application is opening such ZIP files for reading initial data and then store results of its work to the same ZIPs. I have no access to source code of mentioned Android App and old script that generated zip files before (actually, I do not know how old ZIP files were created). But structure of ZIP archive is known and I have written new python script to make the same files. </p>
<p>I was faced with the following problem: ZIP files produced by my script cannot be opened by Android App (error message about incorrect file structure arrears), but if I unpack all the contents and pack it back to new ZIP file with the same name by <strong>WinZIP</strong>, <strong>7-Zip</strong> or "<strong>Send to -> Compressed (zipped) folder</strong>" (in Windows 7) file is normally processed on the phone (this leads me to the conclusion that the problem is not in the Android Application).</p>
<p>The code snippet for packing folder in ZIP was as follows</p>
<pre><code># make zip
try:
with zipfile.ZipFile(prefix + '.zip', 'w') as zipf:
for root, dirs, files in os.walk(prefix):
for file in files:
zipf.write(os.path.join(root, file))
# remove dir, that was packed
shutil.rmtree(prefix)
# Report about resulting
print('File ' + prefix + '.zip was created')
except:
print('Unexpected error occurred while creating file ' + prefix + '.zip')
</code></pre>
<p>After I noticed that files are not compressed I added compression option:</p>
<pre><code> zipfile.ZipFile(prefix + '.zip', 'w', zipfile.ZIP_DEFLATED)
</code></pre>
<p>but this didnât solve my problem and setting <code>True</code> value for <code>allowZip64</code> also didnât change the situation.</p>
<p>By the way a ZIP file produced with <code>zipfile.ZIP_DEFLATED</code> is about 5 kilobytes smaller than ZIP file produced by Windows and about 14 kilobytes smaller than 7-Zipâs result for the same archive content. At the same time all these ZIP files I can open for visual comparison by both 7-Zip and Windows Explorer. </p>
<p>So I have three related questions:</p>
<p>1) What may cause such strange behavior of my script with <code>zipfile</code>?</p>
<p>2) How else can I influence on <code>zipfile</code>?</p>
<p>3) How to check ZIP file created with <code>zipfile</code> to find possible structure problems or make sure there are no problems?</p>
<p>Of course, if I have to give up using <code>zipfile</code> I can use external archiver (e.g. 7-zip) for files packing, but I would like to find an elegant solution if it exists.</p>
<p><strong>UPDATE:</strong></p>
<p>In order to check content of ZIP file created with <code>zipfile</code> I made the following</p>
<pre><code># make zip
flist = []
try:
with zipfile.ZipFile(prefix + '.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(prefix):
for file in files:
zipf.write(os.path.join(root, file))
# Store item in the list
flist.append(os.path.join(root, file).replace("\\","/"))
# remove dir, that was packed
shutil.rmtree(prefix)
# Report about resulting
print('File ' + prefix + '.zip was created')
except:
print('Unexpected error occurred while creating file ' + prefix + '.zip')
# Check of zip
with closing(zipfile.ZipFile(prefix + '.zip')) as zfile:
for info in zfile.infolist():
print(info.filename + \
' (extra = ' + str(info.extra) + \
'; compress_type = ' + ('ZIP_DEFLATED' if info.compress_type == zipfile.ZIP_DEFLATED else 'NOT ZIP_DEFLATED') + \
')')
# remove item from list
if info.filename in flist:
flist.remove(info.filename)
else:
print(info.filename + ' is unexpected item')
print('Number of items that were missed:')
print(len(flist))
</code></pre>
<p>And see the following results in the output:</p>
<pre><code>File en_US_00001.zip was created
en_US_00001/en_US_00001_0001/en_US_00001_0001_big.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0001/en_US_00001_0001_info.xml (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0001/en_US_00001_0001_small.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0001/en_US_00001_0001_source.pkl (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0001/en_US_00001_0001_source.tex (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0001/en_US_00001_0001_user.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0002/en_US_00001_0002_big.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0002/en_US_00001_0002_info.xml (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0002/en_US_00001_0002_small.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0002/en_US_00001_0002_source.pkl (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0002/en_US_00001_0002_source.tex (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0002/en_US_00001_0002_user.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0003/en_US_00001_0003_big.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0003/en_US_00001_0003_info.xml (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0003/en_US_00001_0003_small.png (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0003/en_US_00001_0003_source.pkl (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0003/en_US_00001_0003_source.tex (extra = b''; compress_type = ZIP_DEFLATED)
en_US_00001/en_US_00001_0003/en_US_00001_0003_user.png (extra = b''; compress_type = ZIP_DEFLATED)
Number of items that were missed:
0
</code></pre>
<p>Thus, all that was written, then was read, but the question remains - if all that is necessary has been written? E.g. in comments Harold said about relative paths... perhaps, it is the key to the answer</p>
<p><strong>UPDATE 2</strong></p>
<p>When I replaced <code>zipfile</code> by using external <strong>7-Zip</strong> code</p>
<pre><code># make zip
subprocess.call(["7z.exe","a",prefix + ".zip", prefix])
shutil.rmtree(prefix)
# Check of zip
with closing(zipfile.ZipFile(prefix + '.zip')) as zfile:
for info in zfile.infolist():
print(info.filename)
print(' (extra = ' + str(info.extra) + '; compress_type = ' + str(info.compress_type) + ')')
print('Values for compress_type:')
print(str(zipfile.ZIP_DEFLATED) + ' = ZIP_DEFLATED')
print(str(zipfile.ZIP_STORED) + ' = ZIP_STORED')
</code></pre>
<p>produces the following result</p>
<pre><code>Creating archive en_US_00001.zip
Compressing en_US_00001\en_US_00001_0001\en_US_00001_0001_big.png
Compressing en_US_00001\en_US_00001_0001\en_US_00001_0001_info.xml
Compressing en_US_00001\en_US_00001_0001\en_US_00001_0001_small.png
Compressing en_US_00001\en_US_00001_0001\en_US_00001_0001_source.pkl
Compressing en_US_00001\en_US_00001_0001\en_US_00001_0001_source.tex
Compressing en_US_00001\en_US_00001_0001\en_US_00001_0001_user.png
Compressing en_US_00001\en_US_00001_0002\en_US_00001_0002_big.png
Compressing en_US_00001\en_US_00001_0002\en_US_00001_0002_info.xml
Compressing en_US_00001\en_US_00001_0002\en_US_00001_0002_small.png
Compressing en_US_00001\en_US_00001_0002\en_US_00001_0002_source.pkl
Compressing en_US_00001\en_US_00001_0002\en_US_00001_0002_source.tex
Compressing en_US_00001\en_US_00001_0002\en_US_00001_0002_user.png
Compressing en_US_00001\en_US_00001_0003\en_US_00001_0003_big.png
Compressing en_US_00001\en_US_00001_0003\en_US_00001_0003_info.xml
Compressing en_US_00001\en_US_00001_0003\en_US_00001_0003_small.png
Compressing en_US_00001\en_US_00001_0003\en_US_00001_0003_source.pkl
Compressing en_US_00001\en_US_00001_0003\en_US_00001_0003_source.tex
Compressing en_US_00001\en_US_00001_0003\en_US_00001_0003_user.png
Everything is Ok
en_US_00001/
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00Faf\xd2Y\xf9\xd1\x01Faf\xd2Y\xf9\xd1\x01%\xc9c\xd2Y\xf9\xd1\x01'; compress_type = 0)
en_US_00001/en_US_00001_0001/
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xbe(e\xd2Y\xf9\xd1\x01\xbe(e\xd2Y\xf9\xd1\x016\xf0c\xd2Y\xf9\xd1\x01'; compress_type = 0)
en_US_00001/en_US_00001_0001/en_US_00001_0001_big.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00G\x17d\xd2Y\xf9\xd1\x01G\x17d\xd2Y\xf9\xd1\x01G\x17d\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_info.xml
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00X>d\xd2Y\xf9\xd1\x01X>d\xd2Y\xf9\xd1\x01X>d\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_small.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00z\x8cd\xd2Y\xf9\xd1\x01ied\xd2Y\xf9\xd1\x01ied\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_source.pkl
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\x8b\xb3d\xd2Y\xf9\xd1\x01\x8b\xb3d\xd2Y\xf9\xd1\x01\x8b\xb3d\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_source.tex
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xad\x01e\xd2Y\xf9\xd1\x01\xad\x01e\xd2Y\xf9\xd1\x01\xad\x01e\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_user.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xbe(e\xd2Y\xf9\xd1\x01\xbe(e\xd2Y\xf9\xd1\x01\xbe(e\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0002/
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x005:f\xd2Y\xf9\xd1\x015:f\xd2Y\xf9\xd1\x01\xcfOe\xd2Y\xf9\xd1\x01'; compress_type = 0)
en_US_00001/en_US_00001_0002/en_US_00001_0002_big.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xe0ve\xd2Y\xf9\xd1\x01\xcfOe\xd2Y\xf9\xd1\x01\xcfOe\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_info.xml
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xf1\x9de\xd2Y\xf9\xd1\x01\xe0ve\xd2Y\xf9\xd1\x01\xe0ve\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_small.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\x02\xc5e\xd2Y\xf9\xd1\x01\x02\xc5e\xd2Y\xf9\xd1\x01\x02\xc5e\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_source.pkl
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\x13\xece\xd2Y\xf9\xd1\x01\x13\xece\xd2Y\xf9\xd1\x01\x13\xece\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_source.tex
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00$\x13f\xd2Y\xf9\xd1\x01$\x13f\xd2Y\xf9\xd1\x01$\x13f\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_user.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x005:f\xd2Y\xf9\xd1\x015:f\xd2Y\xf9\xd1\x015:f\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0003/
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xdf\xc0g\xd2Y\xf9\xd1\x01\xdf\xc0g\xd2Y\xf9\xd1\x01Faf\xd2Y\xf9\xd1\x01'; compress_type = 0)
en_US_00001/en_US_00001_0003/en_US_00001_0003_big.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00W\x88f\xd2Y\xf9\xd1\x01W\x88f\xd2Y\xf9\xd1\x01W\x88f\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_info.xml
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00h\xaff\xd2Y\xf9\xd1\x01h\xaff\xd2Y\xf9\xd1\x01h\xaff\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_small.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\x9b$g\xd2Y\xf9\xd1\x01y\xd6f\xd2Y\xf9\xd1\x01y\xd6f\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_source.pkl
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xacKg\xd2Y\xf9\xd1\x01\xacKg\xd2Y\xf9\xd1\x01\xacKg\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_source.tex
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xce\x99g\xd2Y\xf9\xd1\x01\xce\x99g\xd2Y\xf9\xd1\x01\xce\x99g\xd2Y\xf9\xd1\x01'; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_user.png
(extra = b'\n\x00 \x00\x00\x00\x00\x00\x01\x00\x18\x00\xdf\xc0g\xd2Y\xf9\xd1\x01\xdf\xc0g\xd2Y\xf9\xd1\x01\xdf\xc0g\xd2Y\xf9\xd1\x01'; compress_type = 8)
Values for compress_type:
8 = ZIP_DEFLATED
0 = ZIP_STORED
</code></pre>
<p>As I understand the most important findings are:</p>
<ul>
<li>items with info for folders (e.g. <code>en_US_00001/</code>, <code>en_US_00001/en_US_00001_0001/</code>), that were not in the ZIP produced with my usage of <code>zipfile</code></li>
<li>folders have <code>compress_type == ZIP_STORED</code>, while for files <code>compress_type == ZIP_DEFLATED</code></li>
<li><code>extra</code>s have different values (quite long strings were generated)</li>
</ul>
| 2 | 2016-08-18T08:16:46Z | 39,031,727 | <p>Based on the differences listed in UPDATE 2 of Question and examples from <a href="http://stackoverflow.com/questions/434641/how-do-i-set-permissions-attributes-on-a-file-in-a-zip-file-using-pythons-zip">other question about zipfile</a>, I have tried the following code to add directories to ZIP file and check the result:</p>
<pre><code># make zip
try:
with zipfile.ZipFile(prefix + '.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
info = zipfile.ZipInfo(prefix+'\\')
zipf.writestr(info, '')
for root, dirs, files in os.walk(prefix):
for d in dirs:
info = zipfile.ZipInfo(os.path.join(root, d)+'\\')
zipf.writestr(info, '')
for file in files:
zipf.write(os.path.join(root, file))
# remove dir, that was packed
shutil.rmtree(prefix)
# Report about resulting
print('File ' + prefix + '.zip was created')
except:
print('Unexpected error occurred while creating file ' + prefix + '.zip')
# Check zip content
with closing(zipfile.ZipFile(prefix + '.zip')) as zfile:
for info in zfile.infolist():
print(info.filename)
print(' (extra = ' + str(info.extra) + '; compress_type = ' + str(info.compress_type) + ')')
print('Values for compress_type:')
print(str(zipfile.ZIP_DEFLATED) + ' = ZIP_DEFLATED')
print(str(zipfile.ZIP_STORED) + ' = ZIP_STORED')
</code></pre>
<p>Output is </p>
<pre><code>File en_US_00001.zip was created
en_US_00001/
(extra = b''; compress_type = 0)
en_US_00001/en_US_00001_0001/
(extra = b''; compress_type = 0)
en_US_00001/en_US_00001_0002/
(extra = b''; compress_type = 0)
en_US_00001/en_US_00001_0003/
(extra = b''; compress_type = 0)
en_US_00001/en_US_00001_0001/en_US_00001_0001_big.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_info.xml
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_small.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_source.pkl
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_source.tex
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0001/en_US_00001_0001_user.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_big.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_info.xml
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_small.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_source.pkl
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_source.tex
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0002/en_US_00001_0002_user.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_big.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_info.xml
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_small.png
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_source.pkl
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_source.tex
(extra = b''; compress_type = 8)
en_US_00001/en_US_00001_0003/en_US_00001_0003_user.png
(extra = b''; compress_type = 8)
Values for compress_type:
8 = ZIP_DEFLATED
0 = ZIP_STORED
</code></pre>
<p>Adding slash to directory names (<code>+'\\'</code> or <code>+'/'</code>) appeared mandatory.</p>
<p>And the most important thing - now ZIP file is properly accepted by Android Application.</p>
| 1 | 2016-08-19T05:32:23Z | [
"python",
"python-3.x",
"zipfile"
] |
odoo 9 get field value in current record | 39,013,168 | <p>I want to add up a number and field value in current record, this is my code:</p>
<pre><code>def _add(self, cr, uid, ids, context=None):
state_id = self.pool.get('ga.cashadvance').browse(self, cr, uid, ids, self.state)
res = chr(int(state_id) + 1)
return res
class cashadvance(osv.osv):
_name = 'ga.cashadvance'
_columns = {
'id_user' : fields.many2one('res.users', string='User', required=True, readonly=True),
'description' : fields.text('Description', required=True),
'state' : fields.char('State', readonly=True, required=True),
}
def addition(self, cr, uid, ids, context=None):
return self.write(cr,uid,ids,{'state':_add(self, cr, uid, ids, context)},context=context)
</code></pre>
<p>the addition function refers to a button in view form, when I click to the button raise this error:
AttributeError: 'ga.cashadvance' object has no attribute '_ids'</p>
<p>Need help please</p>
| 1 | 2016-08-18T08:19:53Z | 39,013,814 | <p>Just write the state on every button click without so much code:</p>
<pre class="lang-py prettyprint-override"><code>class cashadvance(orm.Model):
_name = 'ga.cashadvance'
_columns = {
'id_user': fields.many2one(
'res.users', string='User', required=True, readonly=True),
'description': fields.text('Description', required=True),
'state': fields.char('State', readonly=True, required=True),
}
def addition(self, cr, uid, ids, context=None):
for adv in self.browse(cr, uid, ids, context):
new_state = chr(int(adv.state) + 1)
adv.write({'state': new_state})
return True
</code></pre>
| 1 | 2016-08-18T08:52:33Z | [
"python",
"python-2.7",
"openerp"
] |
Is there an official way to create discrete-valued range widget in GTK? | 39,013,193 | <p>From what I can see, the behavior any <code>Range</code>-based widget is defined by an <code>Adjustements</code> one.</p>
<p>Since there seems to be no official way to restrict the range to a few discrete values, I have tried a lots of ways to actually reset the values.</p>
<p>What works, <strong>but is not optimal</strong>, is simply to take the current value and determine which valid discrete value is the nearest from that continuous value and use that instead.</p>
<p>But what I would like is to visually freeze the slider to its current position until the user grabs it far enough and then change its value at once to the next valid value.</p>
<p>I want the user to understand and feel that these are discrete values. The problem with my working solution above is that the 3 users who tested the program told me that I should put more figures in the number I displayed, thinking the change was continuous.</p>
<p>NB: by "official", I mean either a "hidden" option or subclass of the <code>Adjustements</code> class if at all available. If not, any way that is reasonably efficient to achieve such a requirement (i.e. that don't use 50% of CPU for a simple slider!). In particular, I am <strong>not asking</strong> for the "ultimate best way" to do this.</p>
| 3 | 2016-08-18T08:21:32Z | 39,036,673 | <p>It seems you can just override the <code>change-value</code> signal:</p>
<pre><code>class DiscreteScale(Gtk.Scale):
def __init__(self, values, *args, **kwargs):
super().__init__(*args, **kwargs)
values.sort()
self.values= values
adjustment= self.get_adjustment()
adjustment.set_lower(values[0])
adjustment.set_upper(values[-1])
self.__changed_value_id= self.connect('change-value', self.__change_value)
def __change_value(self, scale, scroll_type, value):
# find the closest valid value
value= self.__closest_value(value)
# emit a new signal with the new value
self.handler_block(self.__changed_value_id)
self.emit('change-value', scroll_type, value)
self.handler_unblock(self.__changed_value_id)
return True #prevent the signal from escalating
def __closest_value(self, value):
return min(self.values, key=lambda v:abs(value-v))
</code></pre>
<p>A little demo:</p>
<pre><code>w= Gtk.Window()
s= DiscreteScale([0, 1, 5, 20, 22])
w.add(s)
w.set_size_request(500, 50)
w.connect('delete-event', Gtk.main_quit)
w.show_all()
Gtk.main()
</code></pre>
| 4 | 2016-08-19T10:25:50Z | [
"python",
"python-3.x",
"gtk",
"gtk3",
"gobject"
] |
__metaclass__ in Python3.5 | 39,013,249 | <p>In Python2.7 this code can work very well, <code>__getattr__</code> in <code>MetaTable</code>
will run. But in Python 3.5 it doesn't work.</p>
<pre><code>class MetaTable(type):
def __getattr__(cls, key):
temp = key.split("__")
name = temp[0]
alias = None
if len(temp) > 1:
alias = temp[1]
return cls(name, alias)
class Table(object):
__metaclass__ = MetaTable
def __init__(self, name, alias=None):
self._name = name
self._alias = alias
d = Table
d.student__s
</code></pre>
<p>But in Python 3.5 I get an attribute error instead:</p>
<pre><code>Traceback (most recent call last):
File "/Users/wyx/project/python3/sql/dd.py", line 31, in <module>
d.student__s
AttributeError: type object 'Table' has no attribute 'student__s'
</code></pre>
| 0 | 2016-08-18T08:23:44Z | 39,013,295 | <p>Python 3 <a href="https://www.python.org/dev/peps/pep-3115/" rel="nofollow">changed how you specify a metaclass</a>, <code>__metaclass__</code> is no longer checked.</p>
<p>Use <code>metaclass=...</code> in the class <em>signature</em>:</p>
<pre><code>class Table(object, metaclass=MetaTable):
</code></pre>
<p>Demo:</p>
<pre><code>>>> class MetaTable(type):
... def __getattr__(cls, key):
... temp = key.split("__")
... name = temp[0]
... alias = None
... if len(temp) > 1:
... alias = temp[1]
... return cls(name, alias)
...
>>> class Table(object, metaclass=MetaTable):
... def __init__(self, name, alias=None):
... self._name = name
... self._alias = alias
...
>>> d = Table
>>> d.student__s
<__main__.Table object at 0x10d7b56a0>
</code></pre>
<p>If you need to provide support for both Python 2 and 3 in your codebase, you can use the <a href="https://pythonhosted.org/six/#six.with_metaclass" rel="nofollow"><code>six.with_metaclass()</code> baseclass generator</a> or the <a href="https://pythonhosted.org/six/#six.add_metaclass" rel="nofollow"><code>@six.add_metaclass()</code> class decorator</a> to specify the metaclass.</p>
| 1 | 2016-08-18T08:26:04Z | [
"python",
"python-3.5",
"metaclass"
] |
why is only one thread gets executed and other is not | 39,013,256 | <pre><code>import threading,time
def auto2():
while 1:
print ("hello master")
time.sleep(2)
def auto1():
while 1:
print "hello"
time.sleep(3)
x=threading.Thread(target=auto1(),args=())
y=threading.Thread(target=auto2(),args=())
x.start()
y.start()
</code></pre>
| 0 | 2016-08-18T08:24:05Z | 39,013,306 | <pre><code>import threading, time
def auto2():
while 1:
print("hello master")
time.sleep(2)
def auto1():
while 1:
print ("hello")
time.sleep(3)
x = threading.Thread(target=auto1)
y = threading.Thread(target=auto2)
x.start()
y.start()
</code></pre>
<p>target=auto1() - > target=auto1</p>
| 0 | 2016-08-18T08:26:36Z | [
"python",
"python-multithreading"
] |
Approximating a simple sin() function with lasagne | 39,013,366 | <p>I'm trying lasagne and the nolearn NeuralNet function to approximate a simple <code>sin</code> function. After all, neural nets are proven to be universal approximators, so I wanted to try lasagne on a simple non-linear function to show that fact experimentally. This is the code:</p>
<pre><code>import lasagne
import numpy as np
from lasagne import layers
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet
import matplotlib.pylab as pylab
x=np.linspace(0,1,1000)
y=np.sin(8*x)
# Fit the dimensions and scale
x=x.reshape(1000,1).astype(np.float32)
y=y.astype(np.float32)
y=(y-np.min(y))/np.max(y)
</code></pre>
<p>We get the following function:</p>
<pre><code>pylab.plot(x,y)
pylab.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/3lqtm.png" rel="nofollow">Scaled sin function</a></p>
<p>Now we create a simple neural net with 100 hidden units to approximate the function:</p>
<pre><code>net= NeuralNet(
layers=[
('input', layers.InputLayer),
('hidden', layers.DenseLayer),
('output', layers.DenseLayer),
],
input_shape=(None,1),
hidden_num_units=100,
hidden_nonlinearity=lasagne.nonlinearities.rectify,
hidden_W=lasagne.init.GlorotUniform(),
output_num_units=1,
output_nonlinearity=None,
output_W=lasagne.init.GlorotUniform(),
update=nesterov_momentum,
update_learning_rate=0.001,
update_momentum=0.9,
regression=True,
max_epochs=500,
verbose=0,
)
net=net.fit(x,y)
</code></pre>
<p>Now we predict the <code>x</code> values with the trained net to see what we get:</p>
<pre><code>yp=net.predict(x)
pylab.plot(x,yp,hold=1)
pylab.plot(x,y)
pylab.show()
</code></pre>
<p>And this is what we get! <a href="http://i.stack.imgur.com/DwB2N.png" rel="nofollow">Approximated function</a>. It's ridiculous! And if we increment the number of hidden neurons or the training epochs nothing changes. Other types of nonlinearities just make it worse. In theory this should work much better, what am I missing?</p>
<p>Thank you very much.</p>
| 1 | 2016-08-18T08:30:21Z | 39,033,953 | <p>I finally know what was happening. I post my guess in case anyone comes by the same problem.</p>
<p>As it is known, NeuralNet from nolearn environment uses batch training. I don't exactly know how it chooses the batches, but it seems to me that it chooses them sequentially. Then, if the data is not randomized, a batch would not be statistically representative of the whole (the data is not stationary). In my case, I made <code>x=np.linspace(0,1,1000)</code>, and thus the statistical properties of each batch would be different because there's a natural order.</p>
<p>If you create the data randomly instead, i.e., <code>x=np.random.uniform(size=[1000,1])</code>, each batch would be statistically representative, independently of where it is taken from. Once you do this, you can increase the epoch of training and improve convergence to the true optima. I don't know if my guess is correct, but at least it worked for me. Nevertheless I will dig more into it.</p>
| 2 | 2016-08-19T08:00:06Z | [
"python",
"lasagne",
"nolearn",
"function-approximation"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.