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 |
---|---|---|---|---|---|---|---|---|---|
How to determine wrong data type | 39,743,969 | <p>I use the following to see if the data is an integer, if not it tells me. Is there a way to determine which one is incorrect so can change it or would i have to create the same loop for every item?</p>
<pre><code>while i_input == True:
try:
i_pointstarget=int(pointstarget.get())
i_ap1=int(ap1.get())
i_ap2=int(ap2.get())
i_ap3=int(ap3.get())
i_ap4=int(ap4.get())
i_ap5=int(ap5.get())
i_ap6=int(ap6.get())
except ValueError:
i_input=False
continue
else:
break
</code></pre>
<p>Thanks for any help :)</p>
| 0 | 2016-09-28T09:53:07Z | 39,746,263 | <p>Instead of trying to convert to <code>int</code> (btw <code>int(1.23)</code> works, returning <code>1</code>) you can also use <a href="https://docs.python.org/3/library/numbers.html" rel="nofollow">numbers</a> like</p>
<pre><code>import numbers
def is_integral(n): # actually not checking for int but also other int-equivalents
return isinstance(n,numbers.Integral)
</code></pre>
<p>if you want to check if you have a number which can loslessy be converted to an integral number (like <code>int</code>) you can do</p>
<pre><code>import numbers
def exact_integral(n): # check if n can be exactly represented as an integer
return isinstance(n,numbers.Complex) and n==round(n.real)
</code></pre>
| 0 | 2016-09-28T11:33:54Z | [
"python"
]
|
How to determine wrong data type | 39,743,969 | <p>I use the following to see if the data is an integer, if not it tells me. Is there a way to determine which one is incorrect so can change it or would i have to create the same loop for every item?</p>
<pre><code>while i_input == True:
try:
i_pointstarget=int(pointstarget.get())
i_ap1=int(ap1.get())
i_ap2=int(ap2.get())
i_ap3=int(ap3.get())
i_ap4=int(ap4.get())
i_ap5=int(ap5.get())
i_ap6=int(ap6.get())
except ValueError:
i_input=False
continue
else:
break
</code></pre>
<p>Thanks for any help :)</p>
| 0 | 2016-09-28T09:53:07Z | 39,746,473 | <p>To know the type of a variable you can use <code>isinstance(variable_name, int)</code>, this will return the Boolean value.</p>
| 0 | 2016-09-28T11:42:43Z | [
"python"
]
|
Django redirecting everything to homepage | 39,743,993 | <p>I'm stuck with a Django project, I tried to add another app called login to make a login page but for some reason the page just redirects to the homepage except for the admin page</p>
<p>For example: 127.0.0.1:8000 will go to the homepage but 127.0.0.1:8000/login will also display the homepage even though I linked another template to it.</p>
<p>Here is my code: </p>
<p>main urls.py</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('portal.urls')),
url(r'^login/', include('login.urls')),
]
</code></pre>
<p>login urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/', views.index, name="login"),
]
</code></pre>
<p>login views.py</p>
<pre><code>from django.shortcuts import render
def index(request):
return render(request, 'login/login.html')
</code></pre>
<p>portal urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^', views.index, name="portal"),
]
</code></pre>
| 1 | 2016-09-28T09:53:45Z | 39,744,138 | <p>You don't terminate the portal index URL, so it matches everything. It should be:</p>
<pre><code>url(r'^$', views.index, name="portal"),
</code></pre>
| 3 | 2016-09-28T09:58:54Z | [
"python",
"django"
]
|
Django redirecting everything to homepage | 39,743,993 | <p>I'm stuck with a Django project, I tried to add another app called login to make a login page but for some reason the page just redirects to the homepage except for the admin page</p>
<p>For example: 127.0.0.1:8000 will go to the homepage but 127.0.0.1:8000/login will also display the homepage even though I linked another template to it.</p>
<p>Here is my code: </p>
<p>main urls.py</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('portal.urls')),
url(r'^login/', include('login.urls')),
]
</code></pre>
<p>login urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/', views.index, name="login"),
]
</code></pre>
<p>login views.py</p>
<pre><code>from django.shortcuts import render
def index(request):
return render(request, 'login/login.html')
</code></pre>
<p>portal urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^', views.index, name="portal"),
]
</code></pre>
| 1 | 2016-09-28T09:53:45Z | 39,745,508 | <p>In addition, if the regex is login/$ but you enter http ://server/login, then it won't match wheras <a href="http://server/login/" rel="nofollow">http://server/login/</a> will.
You could try changing the regex to login/*$, which will match any number (even zero) / on the end of the url.</p>
<p>So http: //server/login, http: //server/login/, http: //server/login//// would all match.</p>
<p>Or if you want to be specific, login/{0,1}$ might work (though that regex syntax is from memory!)</p>
| 0 | 2016-09-28T10:56:58Z | [
"python",
"django"
]
|
Django redirecting everything to homepage | 39,743,993 | <p>I'm stuck with a Django project, I tried to add another app called login to make a login page but for some reason the page just redirects to the homepage except for the admin page</p>
<p>For example: 127.0.0.1:8000 will go to the homepage but 127.0.0.1:8000/login will also display the homepage even though I linked another template to it.</p>
<p>Here is my code: </p>
<p>main urls.py</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('portal.urls')),
url(r'^login/', include('login.urls')),
]
</code></pre>
<p>login urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/', views.index, name="login"),
]
</code></pre>
<p>login views.py</p>
<pre><code>from django.shortcuts import render
def index(request):
return render(request, 'login/login.html')
</code></pre>
<p>portal urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^', views.index, name="portal"),
]
</code></pre>
| 1 | 2016-09-28T09:53:45Z | 39,745,636 | <p>I see 2 problems here:</p>
<ol>
<li>As @DanielRoseman mentioned above, the regular expression <code>^</code> matches anything, so you should change it to <code>^$</code>. </li>
<li>When you use an <code>include</code>, the rest of the path after what the <code>include</code> matched is passed to the included pattern. Youâll want to use <code>^$</code> in your login urls.py too. </li>
</ol>
| 1 | 2016-09-28T11:02:47Z | [
"python",
"django"
]
|
Looks like base class constructor not initialized | 39,744,025 | <p>I am a newbie in python and trying my hands in oops programming here.
I am initializing base class constructor in derived class , but when trying to print its attribute in base class it gives me error<code>object has no attribute</code></p>
<pre><code>import random
import os
import sys
class Animal:
__name =""
def __init__(self,name):
self.__name = name
def toString(self):
return "{} is the animal name".format(self.__name)
def get_name(self):
return self.__name
cat = Animal("natasha")
print (cat.toString())
class Dog(Animal):
__owner = ""
def __init__(self,name,owner):
self.__owner= owner
#Animal.__init__(self,name)
super(Dog, self).__init__(name)
def toString(self):
return "{} is Animal. And owner is: {}".format(self.__name,self.__owner)
rocky = Dog("rocky","Ronchi")
print (rocky.toString())
</code></pre>
<p>What am i doing wrong here ? I tried like calling <code>super.get_name()</code> also which was a getter function instead of <code>self.__name</code> but this also did not work.I am working on python3.4 </p>
| 0 | 2016-09-28T09:54:44Z | 39,744,114 | <p>This is why you must not use double-underscore prefixes for your instance attributes. These are name mangled, and almost never do what you expect.</p>
<p>Just use <code>self.name</code> and <code>self.owner</code> everywhere.</p>
| 2 | 2016-09-28T09:57:50Z | [
"python",
"python-3.x",
"oop"
]
|
Looks like base class constructor not initialized | 39,744,025 | <p>I am a newbie in python and trying my hands in oops programming here.
I am initializing base class constructor in derived class , but when trying to print its attribute in base class it gives me error<code>object has no attribute</code></p>
<pre><code>import random
import os
import sys
class Animal:
__name =""
def __init__(self,name):
self.__name = name
def toString(self):
return "{} is the animal name".format(self.__name)
def get_name(self):
return self.__name
cat = Animal("natasha")
print (cat.toString())
class Dog(Animal):
__owner = ""
def __init__(self,name,owner):
self.__owner= owner
#Animal.__init__(self,name)
super(Dog, self).__init__(name)
def toString(self):
return "{} is Animal. And owner is: {}".format(self.__name,self.__owner)
rocky = Dog("rocky","Ronchi")
print (rocky.toString())
</code></pre>
<p>What am i doing wrong here ? I tried like calling <code>super.get_name()</code> also which was a getter function instead of <code>self.__name</code> but this also did not work.I am working on python3.4 </p>
| 0 | 2016-09-28T09:54:44Z | 39,744,480 | <p>Variables starting with double underscores are said as private. They are mangled so they cannot be used in subclasses. Using CPython 3.5, you can confirm it simply with:</p>
<pre><code>>>> rocky.__dict__
{'_Animal__name': 'rocky', '_Dog__owner': 'Ronchi'}
>>>
</code></pre>
<p>When called from <code>Dog</code> class, <code>self.__name</code> searches a <code>_Dog__name</code> attribute and cannot find it.</p>
<p>There are two common ways do deal with it:</p>
<ul>
<li>do not use private variables but simply hidden ones, that is just use simple underscore prefixes. The variable will not be displayed by help, but will not be mangled and will be accessible from subclasses</li>
<li><p>use the getter from base class:</p>
<pre><code>def toString(self):
return "{} is Animal. And owner is: {}".format(self.get_name(),self.__owner)
</code></pre>
<p>This correctly gives:</p>
<pre><code>>>> print(rocky.toString())
rocky is Animal. And owner is: Ronchi
>>>
</code></pre></li>
</ul>
| 0 | 2016-09-28T10:12:21Z | [
"python",
"python-3.x",
"oop"
]
|
Looks like base class constructor not initialized | 39,744,025 | <p>I am a newbie in python and trying my hands in oops programming here.
I am initializing base class constructor in derived class , but when trying to print its attribute in base class it gives me error<code>object has no attribute</code></p>
<pre><code>import random
import os
import sys
class Animal:
__name =""
def __init__(self,name):
self.__name = name
def toString(self):
return "{} is the animal name".format(self.__name)
def get_name(self):
return self.__name
cat = Animal("natasha")
print (cat.toString())
class Dog(Animal):
__owner = ""
def __init__(self,name,owner):
self.__owner= owner
#Animal.__init__(self,name)
super(Dog, self).__init__(name)
def toString(self):
return "{} is Animal. And owner is: {}".format(self.__name,self.__owner)
rocky = Dog("rocky","Ronchi")
print (rocky.toString())
</code></pre>
<p>What am i doing wrong here ? I tried like calling <code>super.get_name()</code> also which was a getter function instead of <code>self.__name</code> but this also did not work.I am working on python3.4 </p>
| 0 | 2016-09-28T09:54:44Z | 39,744,784 | <p>Replace your method <code>get_name</code> of <code>Animal</code> with the following code</p>
<pre><code>@property
def name(self):
return self.__name
</code></pre>
<p>Also remember to update the <code>toString</code> of <code>Dog</code> to</p>
<pre><code>def toString(self):
return "{} is Animal. And owner is: {}".format(self.name,self.__owner)
</code></pre>
<p>There're some things that I think it's worth point out if you're new to Python:</p>
<ul>
<li>Regarding getters and setters, Python's use the <code>@property</code> and <code>@property.setter</code> decorators instead of the <code>get_something</code>/<code>set_something</code> conventions in language such as Java.</li>
<li>Using <code>toString</code> is also not very Pythonic. First, method names should be in <code>snake_case</code>. Second, define a method with the signature <code>def __str__(self)</code> and return a <code>str</code>. Then you'll be able to do <code>print(rocky)</code> without having to call the <code>__str__</code> as you do for <code>toString</code>.</li>
<li>The proper way to use <code>super</code> in Python 3 is just <code>super()</code>, with no arguments passed (<a href="https://docs.python.org/3/library/functions.html#super" rel="nofollow">https://docs.python.org/3/library/functions.html#super</a>).</li>
</ul>
| 2 | 2016-09-28T10:24:31Z | [
"python",
"python-3.x",
"oop"
]
|
Resolution of the knapsack approach by bruteforce in python | 39,744,039 | <p>I'm actually trying to resolve the knapsack problem with bruteforce. I know it's not efficient at all, I just want to implement it in python.</p>
<p>The problem is it take long time. In my point of view too much time for a bruteforce. So maybe I make some mistakes in my code...</p>
<pre><code>def solve_it(input_data):
# Start the counting clock
start_time = time.time()
# Parse the input
lines = input_data.split('\n')
firstLine = lines[0].split()
item_count = int(firstLine[0])
capacity = int(firstLine[1])
items = []
for i in range(1, item_count+1):
line = lines[i]
parts = line.split()
items.append(Item(i-1, int(parts[0]), int(parts[1])))
# a trivial greedy algorithm for filling the knapsack
# it takes items in-order until the knapsack is full
value = 0
weight = 0
best_value = 0
my_list_combinations = list()
our_range = 2 ** (item_count)
print(our_range)
output = ""
for i in range(our_range):
# for exemple if item_count is 7 then 2 in binary is
# 0000010
binary = binary_repr(i, width=item_count)
# print the value every 0.25%
if (i % (our_range/400) == 0):
print("i : " + str(i) + '/' + str(our_range) + ' ' +
str((i * 100.0) / our_range) + '%')
elapsed_time_secs = time.time() - start_time
print "Execution: %s secs" % \
timedelta(seconds=round(elapsed_time_secs))
my_list_combinations = (tuple(binary))
sum_weight = 0
sum_value = 0
for item in items:
sum_weight += int(my_list_combinations[item.index]) * \
int(item.weight)
if sum_weight <= capacity:
for item in items:
sum_value += int(my_list_combinations[item.index]) * \
int(item.value)
if sum_value > best_value:
best_value = sum_value
output = 'The decision variable is : ' + \
str(my_list_combinations) + \
' with a total value of : ' + str(sum_value) + \
' for a weight of : ' + str(sum_weight) + '\n'
return output
</code></pre>
<p>Here is the file containing the 30 objects :</p>
<pre><code>30 100000 # 30 objects with a maximum weight of 100000
90000 90001
89750 89751
10001 10002
89500 89501
10252 10254
89250 89251
10503 10506
89000 89001
10754 10758
88750 88751
11005 11010
88500 88501
11256 11262
88250 88251
11507 11514
88000 88001
11758 11766
87750 87751
12009 12018
87500 87501
12260 12270
87250 87251
12511 12522
87000 87001
12762 12774
86750 86751
13013 13026
86500 86501
13264 13278
86250 86251
</code></pre>
<p>I dont show the code relative to the reading of the file because I think it's pointless... For 19 objects I'm able to solve the problem with bruteforce in 14 seconds. But for 30 objects I have calculated that it would take me roughly 15h. So I think that there is a problem in my computing...</p>
<p>Any help would be appreciated :)</p>
<p>Astrus</p>
| 0 | 2016-09-28T09:55:09Z | 39,745,354 | <p>Your issue, that solving the knapsack problem takes too long, is indeed frustrating, and it pops up in other places where algorithms are high-order polynomial or non-polynomial. You're seeing what it means for an algorithm to have exponential runtime ;) In other words, whether your python code is efficient or not, you can very easily construct a version of the knapsack problem that your computer won't be able to solve within your lifetime.</p>
<p>Exponential running time means that every time you add another object to your list, the brute-force solution will take twice as long. If you can solve for 19 objects in 14 seconds, that suggests that 30 objects will take 14 secs x (2**11) = 28672 secs = about 8 hours. To do 31 objects might take about 16 hours. Etc.</p>
<p>There are dynamic programming approaches to the knapsack problem which trade off runtime for memory (<a href="https://en.wikipedia.org/wiki/Knapsack_problem#Solving" rel="nofollow">see the Wikipedia page</a>), and there are numerical optimisers which are tuned to solve constraint-based problems very quickly (<a href="https://en.wikipedia.org/wiki/Knapsack_problem#Software" rel="nofollow">again, Wikipedia</a>), but none of this really alters the fact that finding exact solutions to the knapsack problem is just plain hard.</p>
<p>TL;DR: You're able to solve for 19 objects in a reasonable amount of time, but not for 30 (or 100 objects). This is a property of the problem you're solving, and not a shortcoming with your Python code.</p>
| 0 | 2016-09-28T10:49:59Z | [
"python",
"brute-force",
"knapsack-problem"
]
|
Index into vector field in 2 or 3 dimensions | 39,744,318 | <p>I have <code>vecfield</code> which is an <code>ndarray</code> with <code>m</code> entries for each spatial location in a (discrete) 2 or 3 dimensional space with shape <code>(w, h)</code> or <code>(w, h, d)</code>. Now I get an <code>ndarray</code> with a list of indices <code>(i, j)</code> or <code>(i, j, k)</code> and I'd like to read the <code>m</code> entries corresponding to each index.</p>
<p>Code (for 2D) is probably more helpful:</p>
<pre><code>vecfield = np.zeros([w, h, m])
fill_me_with_data(vecfield)
idx = generate_indices()
# idx is now for example ndarray with [[0, 0], [9, 8], [15, 6], [9, 1]]
result = vecfield[idx, :]
# result should now be 4 x m (4 because 'idx' has 4 indices)
</code></pre>
<p>It seems that idx gets "linearized" and then used as index, so it does not work that way. <strong>How can I achieve what I want?</strong></p>
| 0 | 2016-09-28T10:05:47Z | 39,744,424 | <p>You should have a read about the way numpy advanced indexing works <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a>. I think what you want is:</p>
<pre><code>vecfield[zip(idx)]
</code></pre>
<p><code>zip(idx)</code> returns the list of first components followed by the list of second components, which is what you need to pass for advanced indexing.</p>
| 1 | 2016-09-28T10:10:03Z | [
"python",
"numpy"
]
|
Index into vector field in 2 or 3 dimensions | 39,744,318 | <p>I have <code>vecfield</code> which is an <code>ndarray</code> with <code>m</code> entries for each spatial location in a (discrete) 2 or 3 dimensional space with shape <code>(w, h)</code> or <code>(w, h, d)</code>. Now I get an <code>ndarray</code> with a list of indices <code>(i, j)</code> or <code>(i, j, k)</code> and I'd like to read the <code>m</code> entries corresponding to each index.</p>
<p>Code (for 2D) is probably more helpful:</p>
<pre><code>vecfield = np.zeros([w, h, m])
fill_me_with_data(vecfield)
idx = generate_indices()
# idx is now for example ndarray with [[0, 0], [9, 8], [15, 6], [9, 1]]
result = vecfield[idx, :]
# result should now be 4 x m (4 because 'idx' has 4 indices)
</code></pre>
<p>It seems that idx gets "linearized" and then used as index, so it does not work that way. <strong>How can I achieve what I want?</strong></p>
| 0 | 2016-09-28T10:05:47Z | 39,752,799 | <pre><code>In [258]: vec=np.arange(24).reshape(4,3,2)
In [263]: idx=np.array([[0,0],[1,1],[3,2]])
In [264]: idx.shape
Out[264]: (3, 2)
In [265]: vec[idx,:].shape
Out[265]: (3, 2, 3, 2)
</code></pre>
<p>Indexing directly with <code>idx</code> effectively replaces that 1st dimension (of size 4) with this (3,2) array. In other words, it picks <code>vec[i,:,:]</code> for all 6 values in <code>idx</code>.</p>
<p>What Divakar suggested:</p>
<pre><code>In [266]: vec[idx[:,0], idx[:,1],:]
Out[266]:
array([[ 0, 1],
[ 8, 9],
[22, 23]])
</code></pre>
<p>This uses the 1st col of <code>idx</code> to index the 1st dimension, and the 2nd column to index the 2nd dimension.</p>
<p>List zip also works, but needs a <code>*</code>:</p>
<pre><code>In [267]: list(zip(*idx))
Out[267]: [(0, 1, 3), (0, 1, 2)]
In [268]: vec[list(zip(*idx))]
Out[268]:
array([[ 0, 1],
[ 8, 9],
[22, 23]])
</code></pre>
<p>Like the first answer, it indexes the 1st dim with (0,1,3). It works if <code>idx</code> is a list of lists rather than an array. An array equivalent would be:</p>
<pre><code>In [272]: tuple(idx.T)
Out[272]: (array([0, 1, 3]), array([0, 1, 2]))
</code></pre>
<p>In sum, to pick <code>n</code> items in 2 dimensions, you need 2 <code>n</code> element lists/arrays. </p>
| 0 | 2016-09-28T16:19:23Z | [
"python",
"numpy"
]
|
Python, Pygame, Class object no longer callable | 39,744,404 | <p>I am writing a game using Pygame, now I am having this issue where I wanted to add a spawn timer on my monsters in the game. Now the timer works fine and the first spawn wave gets made and everything is great and terrific until the second wave where it says:</p>
<pre><code>Monster1 = Monster()
</code></pre>
<blockquote>
<p>TypeError: 'Monster' object is not callable</p>
</blockquote>
<p>Now this I don't get, since it already called it in the round before then. </p>
<p>I went over my text plenty of times just to see if I am changing any features in the the class or making it so that it shouldn't be callable anymore but I just don't get it.</p>
<p>This loop makes spawns the monsters</p>
<pre><code>while Game:
if time.clock() - WaveTimer > 10:
WaveTimer = time.clock()
print "The Moon is full"
for i in range(3*SpawnRate):
Monster1 = Monster()
monster_list.add(Monster1)
character_list.add(Monster1)
SpawnRate += 1
</code></pre>
<p>This is the Monster class</p>
<pre><code>class Monster(Character):
Current_HP = 50
Max_Hp = 50
walking_frame = []
fighting_frame = []
hit_frame = []
Fighting = False
Flag = True
frame1= 0
LastFrame1 = 0
TimeBetweenAtkFrames = 0.1
X_Speed = 0
Y_Speed = 0
damaged = False
RecordedAni = True
damagedspeed = 1
image_file = "C:/Users/Gideon/PycharmProjects/untitled1/Sprite Images/All.png"
sprite_sheet = SpriteSheet(image_file)
hitimage = sprite_sheet.get_image(96, 336, 48, 48)
hitimage = pygame.transform.scale(hitimage, (50, 50))
for i in range(5):
image = sprite_sheet.get_image(i * 48, 288, 48, 48)
fighting_frame.append(image)
for i in range(4):
image = sprite_sheet.get_image(i * 48, 144, 48, 48) # Temp
walking_frame.append(image)
for i in range(4):
image = sprite_sheet.get_image(i * 48, 192, 48, 48) # Temp
walking_frame.append(image)
image = sprite_sheet.get_image(0, 144, 48, 48)
image = pygame.transform.scale(image, (50, 50))
orgimage = image
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.Loc_x = random.randrange(20,700)
self.Loc_y = random.randrange(20,100) # temp
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = [self.Loc_x, self.Loc_y]
for i in range (2):
image = self.sprite_sheet.get_image(i * 48, 336, 48, 48)
self.hit_frame.append(image)
i += 1
def move(self,character):
if self.Alive:
if self.Current_HP < self.Max_Hp:
self.damagedspeed = 2
if character.Loc_x > self.Loc_x + 25:
self.X_Speed = 1.5 * self.damagedspeed
self.Loc_x += self.X_Speed
if character.Loc_x < self.Loc_x - 25:
self.X_Speed = 1.5 * self.damagedspeed
self.Loc_x -= self.X_Speed
if character.Loc_y > self.Loc_y + 25:
self.Y_Speed = 1.5 * self.damagedspeed
self.Loc_y += self.Y_Speed
if character.Loc_y < self.Loc_y - 25:
self.Y_Speed = 1.5 * self.damagedspeed
self.Loc_y -= self.Y_Speed
if (self.Flag):
self.Animation()
wall_hit_list = pygame.sprite.spritecollide(self, CollideList, False)
for wall in wall_hit_list:
if self.X_Speed > 0:
self.X_Speed = 0
self.Loc_x = self.Loc_x - 5
if self.X_Speed < 0:
self.X_Speed = 0
self.Loc_x = self.Loc_x + 5
if self.Y_Speed > 0:
self.Y_Speed = 0
self.Loc_y = self.Loc_y - 5
if self.Y_Speed < 0:
self.Y_Speed = 0
self.Loc_y = self.Loc_y + 5
self.FightAnimation(character)
self.image = pygame.transform.rotate(self.orgimage, self.Angle)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = [self.Loc_x, self.Loc_y]
self.X_Speed = 0
self.Y_Speed = 0
def FightAnimation(self,character):
# Monster Fight Animation
if character.Loc_x <= self.Loc_x + 25 and character.Loc_x >= self.Loc_x - 25:
if character.Loc_y <= self.Loc_y + 25 and character.Loc_y >= self.Loc_y - 25:
if(self.Fighting == False):
self.LastFrame1 = time.clock()
self.Fighting = True
if (self.frame1 < len(self.fighting_frame)):
self.Flag = False
self.image = self.fighting_frame[self.frame1]
self.image = pygame.transform.scale(self.image, (60, 60))
self.orgimage = self.image
if (self.frame1 == 3):
character.Current_HP -= 20
self.frame1 += 1
else:
self.frame1 = 0
else:
if (self.frame1 != 0):
self.frame1 = 0
self.Flag = True
else:
if (self.frame1 != 0):
self.frame1 = 0
self.image = self.fighting_frame[self.frame1]
self.image = pygame.transform.scale(self.image, (60, 60))
self.orgimage = self.image
self.Flag = True
if self.Fighting and time.clock() - self.LastFrame1 > self.TimeBetweenAtkFrames:
self.Fighting = False
</code></pre>
<p>If there is anything else you'd need to know just tell me and I will add it
If this is really messy I am sorry its the first time I am using StackOverFlow website :$</p>
| 0 | 2016-09-28T10:09:00Z | 39,744,560 | <p>Somewhere in your code, you "overwrite" the name <code>Monster</code>, which then no longer points to your class.</p>
<p>Make sure you're not doing a <code>Monster = whatever</code> anywhere in your code.</p>
<p>Also, note that <code>Current_HP</code>, <code>Max_Hp</code> etc. are class members, not instance members, so if you chance <code>Current_HP</code> on a <code>Monster</code> instance, you change it for <em>all</em> <code>Monster</code> instances.</p>
| 1 | 2016-09-28T10:15:10Z | [
"python",
"pygame"
]
|
Python enable logging for executable during run time | 39,744,546 | <p>I've created a python module with logging library displaying information. Example of logging output would be...</p>
<pre><code>2016-09-28 02:54:39,089 - INFO - dataServer - Listening for incoming connections...
2016-09-28 02:54:41,089 - INFO - dataServer - Listening for incoming connections...
</code></pre>
<p>I've used pyinstaller to generate an executable from the python module. I was wondering if there was a way to enable the logging to display on command prompt when the executable is executed from the command prompt. I know I log to a file but I want to be able to see the logging information in real time.</p>
| 0 | 2016-09-28T10:14:36Z | 39,746,686 | <p>You must have added a <em>FileHandler</em> to output the content to a file. Similarly to output the content to console add <em>StreamHandler</em> in this way <strong>sh = logging.StreamHandler(sys.stdout)</strong> and add this handler to logger by <strong>logger.addHandler(sh)</strong></p>
<p>Hope this helps, cheers.</p>
| 1 | 2016-09-28T11:52:19Z | [
"python",
"logging",
"exe",
"pyinstaller"
]
|
Odoo ERP how to save lines when I press "Save & Close" button from Pop Up window? | 39,744,579 | <p>One of the most annoying feature of Open ERP is:<br>
I have to press main <strong>Save</strong> <em>button(picture 2, item 3)</em> on left top corner even though I already pressed <strong>Save and Close</strong> <em>picture 1, item 1</em> from Pop Up window of products.<br>
I included screenshot from Warehouse module as example. Please assume 'stock.picking' is already created, so it wouldn't cause integrity problem.</p>
<blockquote>
<p>I feel last step is redundant.<br>
Is it possible to save products lines without having to press <strong>Save</strong> button <em>picture 2, item 3</em>?<br>
Is it possible to override <strong>Save & Close button</strong>?<br>
Is it possible to call <strong>Save</strong> button when I press <strong>Save & Close button</strong>?</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/xisBr.png" rel="nofollow"><img src="http://i.stack.imgur.com/xisBr.png" alt="Save and Close button"></a>
<a href="http://i.stack.imgur.com/2QtvA.png" rel="nofollow"><img src="http://i.stack.imgur.com/2QtvA.png" alt="Main Save button"></a></p>
| 1 | 2016-09-28T10:15:40Z | 39,784,432 | <p>You can't save One2many record without saving parent form.
As child(one2many) is dependent on Parent Form Class. and making any shortcut for saving one2many record without saving parent can affect system badly.</p>
<p>So Please follow the standard process.</p>
| 0 | 2016-09-30T05:40:30Z | [
"python",
"openerp"
]
|
Serve protected media files with django | 39,744,587 | <p>I'd like Django to serve some media files (e.g. user-uploaded files) only for logged-in users. Since my site is quite low-traffic, I think I will keep things simple and do not use <code>django-sendfile</code> to tell Nginx when to serve a file. Instead I'll let Django/Gunicorn do the job. To me this seems a lot simpler and for a low traffic site this maybe more secure.</p>
<p>But what is the best way to organize the file storage location? Media files are all stored below <code>MEDIA_ROOT</code> and this directory is served by Nginx in production. If I upload my files to <code>MEDIA_ROOT/protected/</code> I have to tell Nginx not to serve the files in the subdirectory <code>protected</code>.</p>
<p>But is this a good idea? It seems a litte risky to me to allow Nginx access <code>/media/</code> in the first place and then protect the subdirectory <code>/media/protected/</code>. Wouldn't it be better not to use a subdirectory of <code>MEDIA_ROOT</code> to store protected files? </p>
<p>But if I try something like this quick-and-dirty in my model:</p>
<pre><code>upload_to='../protected/documents/%Y/%m/'
</code></pre>
<p>Django complains:</p>
<pre><code>SuspiciousFileOperation at /admin/core/document/add/
The joined path (/home/me/projects/project/protected/documents/2016/09/test.file) is located outside of the base path component (/home/me/projects/project/media)
</code></pre>
<p>So I thing it is not good practice to "leave" the <code>MEDIA_ROOT</code>.</p>
<p>What is the best solution to store and serve protected media files?</p>
| 0 | 2016-09-28T10:16:03Z | 39,749,214 | <p>I now came up with the following solution:</p>
<p>I have this in my Django settings:</p>
<pre><code>MEDIA_ROOT = "/projects/project/media/"
MEDIA_URL = "/media/
</code></pre>
<p>In my models I do either:</p>
<pre><code>document = models.FileField(upload_to="public/documents")
</code></pre>
<p>or</p>
<pre><code>document = models.FileField(upload_to="protected/documents")
</code></pre>
<p>This way, I now have the two subdirectories 'public' and 'protected' in my media files directory.</p>
<p>Nginx or Djangos development server only serves the files in the 'public' subdirectory.</p>
<p>For Djangos development server:</p>
<pre><code>if os.environ["ENVIRONMENT_TYPE"] == 'development':
urlpatterns += static(settings.MEDIA_URL + "public/", document_root=settings.MEDIA_ROOT + "public/")
</code></pre>
<p>And for Nginx (used in production):</p>
<pre><code>location /media/public/ {
alias /projects/project/media/public/;
}
</code></pre>
<p>When I want to serve a protected document, I do the following:</p>
<p>In urls.py:</p>
<pre><code>url(r'^media/protected/documents/(?P<file>.*)$', core.views.serve_protected_document, name='serve_protected_document'),
</code></pre>
<p>And in views.py:</p>
<pre><code>@login_required()
def serve_protected_document(request, file):
document = get_object_or_404(ProtectedDocument, file="protected/documents/" + file)
# Split the elements of the path
path, file_name = os.path.split(file)
response = FileResponse(document.file,)
response["Content-Disposition"] = "attachment; filename=" + file_name
return response
</code></pre>
<p>I would appreciate any comments! Are there better ways to implement this?</p>
| 0 | 2016-09-28T13:38:30Z | [
"python",
"django",
"python-3.x",
"nginx",
"nginx-location"
]
|
How to create a Django superuser if it doesn't exist non-interactively? | 39,744,593 | <p>I want to automate creation of Django users via a Bash script. I found this snippet which almost suits my needs: </p>
<pre><code>echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" |\
python manage.py shell
</code></pre>
<p>How can I modify it so that it's a nop if the user already exists?</p>
| 0 | 2016-09-28T10:16:22Z | 39,744,835 | <p>you can use <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#get-or-create" rel="nofollow">get_or_create()</a>. If it exists it will do nothing, else it will create one.</p>
<p>You'd have to set the <code>is_staff</code> and <code>is_superuser</code> to <code>True</code> manually</p>
| 0 | 2016-09-28T10:26:39Z | [
"python",
"django",
"django-users"
]
|
How to create a Django superuser if it doesn't exist non-interactively? | 39,744,593 | <p>I want to automate creation of Django users via a Bash script. I found this snippet which almost suits my needs: </p>
<pre><code>echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" |\
python manage.py shell
</code></pre>
<p>How can I modify it so that it's a nop if the user already exists?</p>
| 0 | 2016-09-28T10:16:22Z | 39,745,093 | <p>You can use <code>filter()</code> and <code>exists()</code> to check whether the a user with that username exists before you create it.</p>
<pre><code>if not User.objects.filter(username="admin").exists():
User.objects.create_superuser('admin', 'admin@example.com', 'pass')
</code></pre>
| 0 | 2016-09-28T10:39:01Z | [
"python",
"django",
"django-users"
]
|
How to create a Django superuser if it doesn't exist non-interactively? | 39,744,593 | <p>I want to automate creation of Django users via a Bash script. I found this snippet which almost suits my needs: </p>
<pre><code>echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" |\
python manage.py shell
</code></pre>
<p>How can I modify it so that it's a nop if the user already exists?</p>
| 0 | 2016-09-28T10:16:22Z | 39,745,576 | <p>Using some <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/" rel="nofollow">QuerySet API</a> methods and a heredoc for readability:</p>
<pre><code>cat <<EOF | python manage.py shell
from django.contrib.auth.models import User
User.objects.filter(username="admin").exists() or \
User.objects.create_superuser("admin", "admin@example.com", "pass")
EOF
</code></pre>
<p>Note that you should use the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_superuser" rel="nofollow"><code>create_superuser()</code></a> helper function to create superusers instead of generic <code>User()</code> methods as it takes care of setting the password properly. </p>
| 0 | 2016-09-28T11:00:28Z | [
"python",
"django",
"django-users"
]
|
Why Flask Migrate doesn't create an empty migration file? | 39,744,688 | <p>I am using Flask, Flask-SqlAlchemy and Flask-Migrate to manage my models. And I just realize that in my latest database state, when I create a new migration file, <code>python manage.py db migrate -m'test migration</code>, it will not create an empty migration file. Instead it tries to create and drop several unique key and foreign key constraints.</p>
<p>Any ideas why it behaves like this?</p>
| 1 | 2016-09-28T10:20:32Z | 39,761,658 | <p>If you have made no changes to your model from the current migration, but you get a non-empty migration file generated, then it suggests for some reason your models became out of sync with the database, and the contents of this new migration are just the things that are mismatched.</p>
<p>If you say that the migration contains code that drops some constraints and add some other ones, it makes me think that the constraint names have probable changed, or maybe you upgraded your SQLAlchemy version to a newer version that generates constraints with different names.</p>
| 1 | 2016-09-29T04:51:56Z | [
"python",
"flask-sqlalchemy",
"flask-migrate"
]
|
Python: shared methods and attributes in multiple inheritance | 39,744,693 | <p>I simply want to create a class which inherits attributes and methods from two parents. Let's just say the two parent classes are</p>
<pre><code>class A(object):
def __init__(self, a):
self.a = a
def method_a(self):
return self.a + 10
class B(object):
def __init__(self, b):
self.b = b
def method_b(self):
return self.b + 20
</code></pre>
<p>Then I am not sure how to create a subclass C which inherits both methods and attributes from its parents. I can do something like this, but I am quite sure this is not very pythonic...</p>
<pre><code>class C(A, B):
def __init__(self, a, b):
A.__init__(self, a=a)
B.__init__(self, b=b)
</code></pre>
<p>then I can do this without a problem</p>
<pre><code>my_class = C(a=1, b=2)
print(my_class.a)
print(my_class.b)
print(my_class.method_a())
print(my_class.method_b())
</code></pre>
<p>I don't know how to set up <code>super</code> to inherit methods and attributes from both parents and I would appreciate any help! And by the way: Classes A and B should not depend on each other.</p>
| -2 | 2016-09-28T10:20:44Z | 39,745,662 | <p>As far as I know, the way <code>super</code> works is that, based on the list of superclasses declared at the beginning of the subclass, an <code>mro</code> (method resolution order) list will be worked out. When you call <code>supper</code> (Python 3), the <code>__init__</code> of the first class in the <code>mro</code> list will be called. That <code>__init__</code> is also expected to contain another <code>super()</code> so that the <code>__init__</code> of the next class in the <code>mro</code> also gets called.</p>
<p>In your case, the <code>mro</code> list should be <code>[A, B]</code>. So the <code>__init__</code> of <code>A</code> must contain an invocation of <code>super</code> so that the <code>__init__</code> of <code>B</code> is also get called.</p>
<p>The problems here are:</p>
<ul>
<li>You want <code>A</code> and <code>B</code> not to depend of each other. The use of <code>super</code> needs an <code>mro</code> list, which does not satisfy this requirement as I explained above.</li>
<li>The <code>__init__</code> of <code>C</code> has 2 parameters while those of <code>A</code> and <code>B</code> have only 1. You may be able to pass <code>a</code> to <code>A</code> but I don't know if there's a way for you to pass <code>b</code> to <code>B</code>.</li>
</ul>
<p>So it seems to me that <code>super</code> cannot help in this situation.</p>
| 0 | 2016-09-28T11:04:19Z | [
"python",
"inheritance"
]
|
IndexError when using Scrapy for absolute links | 39,744,845 | <p>I am scraping a webpage from Wikipedia (particularly <a href="https://en.wikipedia.org/wiki/Category:2013_films" rel="nofollow">this</a> one) using a Python library called <a href="https://doc.scrapy.org/en/1.2/" rel="nofollow">Scrapy</a>. Here was the original code which successfully crawled the page:</p>
<pre><code>import scrapy
from wikipedia.items import WikipediaItem
class MySpider(scrapy.Spider):
name = "wiki"
allowed_domains = ["en.wikipedia.org/"]
start_urls = [
'https://en.wikipedia.org/wiki/Category:2013_films',
]
def parse(self, response):
titles = response.xpath('//div[@id="mw-pages"]//li')
items = []
for title in titles:
item = WikipediaItem()
item["title"] = title.xpath("a/text()").extract()
item["url"] = title.xpath("a/@href").extract()
items.append(item)
return items
</code></pre>
<p>Then in the terminal, I ran <code>scrapy crawl wiki -o wiki.json -t json</code> to output the data to a JSON file. While the code worked, the links assigned to the "url" keys were all relative links. (i.e.: <code>{"url": ["/wiki/9_Full_Moons"], "title": ["9 Full Moons"]}</code>).</p>
<p>Instead of <em>/wiki/9_Full_Moons</em>, I needed <em><a href="http://en.wikipedia.org/wiki/9_Full_Moons" rel="nofollow">http://en.wikipedia.org/wiki/9_Full_Moons</a></em>. So I modified the above mentioned code to import the <strong>urljoin</strong> from the urlparse library. I also modified my <code>for</code> loop to look like this instead:</p>
<pre><code>for title in titles:
item = WikipediaItem()
url = title.xpath("a/@href").extract()
item["title"] = title.xpath("a/text()").extract()
item["url"] = urljoin("http://en.wikipedia.org", url[0])
items.append(item)
return(items)
</code></pre>
<p>I believed this was the correct approach since the type of data assigned to the <code>url</code> key is enclosed in brackets (which would entail a list, right?) so to get the string inside it, I typed <strong>url[0]</strong>. However, this time I got an IndexError that looked like this:</p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>Can someone help explain where I went wrong?</p>
| 0 | 2016-09-28T10:27:11Z | 39,745,183 | <p>I think you can just concatenate the two strings instead of using <code>urljoin</code>. Try this:</p>
<pre><code>for title in titles:
item = WikipediaItem()
item["title"] = title.xpath("a/text()").extract()
item["url"] = "http://en.wikipedia.org" + title.xpath("a/@href").extract()[0]
items.append(item)
return(items)
</code></pre>
| 0 | 2016-09-28T10:42:29Z | [
"python",
"json",
"xpath",
"scrapy"
]
|
IndexError when using Scrapy for absolute links | 39,744,845 | <p>I am scraping a webpage from Wikipedia (particularly <a href="https://en.wikipedia.org/wiki/Category:2013_films" rel="nofollow">this</a> one) using a Python library called <a href="https://doc.scrapy.org/en/1.2/" rel="nofollow">Scrapy</a>. Here was the original code which successfully crawled the page:</p>
<pre><code>import scrapy
from wikipedia.items import WikipediaItem
class MySpider(scrapy.Spider):
name = "wiki"
allowed_domains = ["en.wikipedia.org/"]
start_urls = [
'https://en.wikipedia.org/wiki/Category:2013_films',
]
def parse(self, response):
titles = response.xpath('//div[@id="mw-pages"]//li')
items = []
for title in titles:
item = WikipediaItem()
item["title"] = title.xpath("a/text()").extract()
item["url"] = title.xpath("a/@href").extract()
items.append(item)
return items
</code></pre>
<p>Then in the terminal, I ran <code>scrapy crawl wiki -o wiki.json -t json</code> to output the data to a JSON file. While the code worked, the links assigned to the "url" keys were all relative links. (i.e.: <code>{"url": ["/wiki/9_Full_Moons"], "title": ["9 Full Moons"]}</code>).</p>
<p>Instead of <em>/wiki/9_Full_Moons</em>, I needed <em><a href="http://en.wikipedia.org/wiki/9_Full_Moons" rel="nofollow">http://en.wikipedia.org/wiki/9_Full_Moons</a></em>. So I modified the above mentioned code to import the <strong>urljoin</strong> from the urlparse library. I also modified my <code>for</code> loop to look like this instead:</p>
<pre><code>for title in titles:
item = WikipediaItem()
url = title.xpath("a/@href").extract()
item["title"] = title.xpath("a/text()").extract()
item["url"] = urljoin("http://en.wikipedia.org", url[0])
items.append(item)
return(items)
</code></pre>
<p>I believed this was the correct approach since the type of data assigned to the <code>url</code> key is enclosed in brackets (which would entail a list, right?) so to get the string inside it, I typed <strong>url[0]</strong>. However, this time I got an IndexError that looked like this:</p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>Can someone help explain where I went wrong?</p>
| 0 | 2016-09-28T10:27:11Z | 39,745,959 | <p>On your first iteration of code with relative links, you used the <code>xpath</code> method: <code>item["url"] = title.xpath("a/@href").extract()</code>
The object returned is (I assume) a list of strings, so indexing it would be valid.</p>
<p>In the new iteration, you used the <code>select</code> method: <code>url = title.select("a/@href").extract()</code> Then you treated the returned object as an iterable, with <code>url[0]</code>. Check what the <code>select</code> method returns, maybe it's a list, like in the previous example.</p>
<p>P.S.: <a href="http://en.wikipedia.org/wiki/IPython" rel="nofollow">IPython</a> is your friend.</p>
| 0 | 2016-09-28T11:19:23Z | [
"python",
"json",
"xpath",
"scrapy"
]
|
IndexError when using Scrapy for absolute links | 39,744,845 | <p>I am scraping a webpage from Wikipedia (particularly <a href="https://en.wikipedia.org/wiki/Category:2013_films" rel="nofollow">this</a> one) using a Python library called <a href="https://doc.scrapy.org/en/1.2/" rel="nofollow">Scrapy</a>. Here was the original code which successfully crawled the page:</p>
<pre><code>import scrapy
from wikipedia.items import WikipediaItem
class MySpider(scrapy.Spider):
name = "wiki"
allowed_domains = ["en.wikipedia.org/"]
start_urls = [
'https://en.wikipedia.org/wiki/Category:2013_films',
]
def parse(self, response):
titles = response.xpath('//div[@id="mw-pages"]//li')
items = []
for title in titles:
item = WikipediaItem()
item["title"] = title.xpath("a/text()").extract()
item["url"] = title.xpath("a/@href").extract()
items.append(item)
return items
</code></pre>
<p>Then in the terminal, I ran <code>scrapy crawl wiki -o wiki.json -t json</code> to output the data to a JSON file. While the code worked, the links assigned to the "url" keys were all relative links. (i.e.: <code>{"url": ["/wiki/9_Full_Moons"], "title": ["9 Full Moons"]}</code>).</p>
<p>Instead of <em>/wiki/9_Full_Moons</em>, I needed <em><a href="http://en.wikipedia.org/wiki/9_Full_Moons" rel="nofollow">http://en.wikipedia.org/wiki/9_Full_Moons</a></em>. So I modified the above mentioned code to import the <strong>urljoin</strong> from the urlparse library. I also modified my <code>for</code> loop to look like this instead:</p>
<pre><code>for title in titles:
item = WikipediaItem()
url = title.xpath("a/@href").extract()
item["title"] = title.xpath("a/text()").extract()
item["url"] = urljoin("http://en.wikipedia.org", url[0])
items.append(item)
return(items)
</code></pre>
<p>I believed this was the correct approach since the type of data assigned to the <code>url</code> key is enclosed in brackets (which would entail a list, right?) so to get the string inside it, I typed <strong>url[0]</strong>. However, this time I got an IndexError that looked like this:</p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>Can someone help explain where I went wrong?</p>
| 0 | 2016-09-28T10:27:11Z | 39,747,349 | <p>So after mirroring the code to the example given in the documentation <strong><a href="https://doc.scrapy.org/en/latest/topics/spiders.html" rel="nofollow">here</a></strong>, I was able to get the code to work:</p>
<pre><code>def parse(self, response):
for text in response.xpath('//div[@id="mw-pages"]//li/a/text()').extract():
yield WikipediaItem(title=text)
for href in response.xpath('//div[@id="mw-pages"]//li/a/@href').extract():
link = urljoin("http://en.wikipedia.org", href)
yield WikipediaItem(url=link)
</code></pre>
<p>If anyone needs further clarification on how the <strong>Items</strong> class works, <strong><a href="https://doc.scrapy.org/en/latest/topics/items.html" rel="nofollow">the documentation is here</a></strong>. </p>
<p>Furthermore, although the code works, it won't pair the title with its respective link. So it will give you </p>
<blockquote>
<p>TITLE, TITLE, TITLE, LINK, LINK, LINK</p>
</blockquote>
<p>instead of </p>
<blockquote>
<p>TITLE, LINK, TITLE, LINK, TITLE, LINK</p>
</blockquote>
<p>(the latter being probably the more desired result) â but that's for another question. If anyone has a proposed solution that works better than mine, I'll be more than happy to listen to your answers! Thanks. </p>
| 0 | 2016-09-28T12:20:27Z | [
"python",
"json",
"xpath",
"scrapy"
]
|
IndexError when using Scrapy for absolute links | 39,744,845 | <p>I am scraping a webpage from Wikipedia (particularly <a href="https://en.wikipedia.org/wiki/Category:2013_films" rel="nofollow">this</a> one) using a Python library called <a href="https://doc.scrapy.org/en/1.2/" rel="nofollow">Scrapy</a>. Here was the original code which successfully crawled the page:</p>
<pre><code>import scrapy
from wikipedia.items import WikipediaItem
class MySpider(scrapy.Spider):
name = "wiki"
allowed_domains = ["en.wikipedia.org/"]
start_urls = [
'https://en.wikipedia.org/wiki/Category:2013_films',
]
def parse(self, response):
titles = response.xpath('//div[@id="mw-pages"]//li')
items = []
for title in titles:
item = WikipediaItem()
item["title"] = title.xpath("a/text()").extract()
item["url"] = title.xpath("a/@href").extract()
items.append(item)
return items
</code></pre>
<p>Then in the terminal, I ran <code>scrapy crawl wiki -o wiki.json -t json</code> to output the data to a JSON file. While the code worked, the links assigned to the "url" keys were all relative links. (i.e.: <code>{"url": ["/wiki/9_Full_Moons"], "title": ["9 Full Moons"]}</code>).</p>
<p>Instead of <em>/wiki/9_Full_Moons</em>, I needed <em><a href="http://en.wikipedia.org/wiki/9_Full_Moons" rel="nofollow">http://en.wikipedia.org/wiki/9_Full_Moons</a></em>. So I modified the above mentioned code to import the <strong>urljoin</strong> from the urlparse library. I also modified my <code>for</code> loop to look like this instead:</p>
<pre><code>for title in titles:
item = WikipediaItem()
url = title.xpath("a/@href").extract()
item["title"] = title.xpath("a/text()").extract()
item["url"] = urljoin("http://en.wikipedia.org", url[0])
items.append(item)
return(items)
</code></pre>
<p>I believed this was the correct approach since the type of data assigned to the <code>url</code> key is enclosed in brackets (which would entail a list, right?) so to get the string inside it, I typed <strong>url[0]</strong>. However, this time I got an IndexError that looked like this:</p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>Can someone help explain where I went wrong?</p>
| 0 | 2016-09-28T10:27:11Z | 39,772,731 | <p>For better clarification, i am going to modify above code,</p>
<pre><code>for title in titles:
item = WikipediaItem()
item["title"] = title.xpath("a/text()").extract()
item["url"] = "http://en.wikipedia.org" + title.xpath("a/@href").extract()[0]
items.append(item)
return(items)
</code></pre>
| 0 | 2016-09-29T14:13:03Z | [
"python",
"json",
"xpath",
"scrapy"
]
|
Flask Registration Form Condition if elif else doesn't work | 39,745,076 | <p>When I try to register an user, I don't know why, but if the email I'm trying to register does not exist in the db, the for loop ends, though there's an elif end else statement.</p>
<p>Someone know why?</p>
<p>This is the web.py file</p>
<pre><code>from flask import Flask, session, redirect, url_for, escape, request, render_template
from wtforms import Form, BooleanField, TextField, PasswordField, validators
import MySQLdb
import logging
app = Flask(__name__)
db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="usbw", port=3307, db="tourme")
cur = db.cursor()
@app.route('/register/', methods=["GET","POST"])
def register():
email_msg = None
success_msg = None
pass_msg = None
test = None
try:
if request.method == 'POST':
id_id = None
username = request.form['name']
lastname = request.form['lastname']
email = request.form['email']
password = request.form['password']
repeat = request.form['repeat']
cur = db.cursor()
cur.execute("SELECT * FROM users WHERE email = (%s)", [email])
for row in cur.fetchall():
if row[1] == email:
email_msg = "This e-mail already exist: " + row[1]
elif password == repeat:
cur.execute("INSERT INTO users VALUES (%s,%s,%s,%s,%s)", (id_id,email,username,lastname,password))
db.commit()
success_msg = "Bravo"
db.close()
else:
pass_msg = "Password must match"
return render_template("register.html", email_msg=email_msg, success_msg=success_msg, pass_msg=pass_msg)
except Exception as e:
return(str(e))
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>And this is the template</p>
<pre><code><div class="register">
<form action="" method="POST">
<div class="input-group">
<span class="input-group-addon" id="basic-addon3">Your Username</span>
<input type="text" class="form-control" name="name" aria-describedby="basic-addon3">
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3">Your Lastname</span>
<input type="text" class="form-control" name="lastname" aria-describedby="basic-addon3">
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3">Email</span>
<input type="email" class="form-control" name="email" aria-describedby="basic-addon3">
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3">Your Password</span>
<input type="password" class="form-control" name="password" aria-describedby="basic-addon3">
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3">Repeat Password</span>
<input type="password" class="form-control" name="repeat" aria-describedby="basic-addon3">
</div>
<br>
<input type="Submit" value="Register" class="btn btn-default btn-sm">
</form>
{% if success_msg %}
<p class=success_msg><strong>Message:</strong> {{ success_msg }}
{% endif %}
{% if email_msg %}
<p class=success_msg><strong>Error:</strong> {{ email_msg }}
{% endif %}
{% if pass_msg %}
<p class=pass_msg><strong>Error:</strong> {{ pass_msg }}
{% endif %}
<br>
<a href="{{ url_for('index') }}">Home</a>
</div>
</code></pre>
<p>Thanks a lot for your help!</p>
| -2 | 2016-09-28T10:38:17Z | 39,747,839 | <p>Like I said in the comment, this is hardly a programming problem, it's a logic problem.</p>
<pre><code>cur.execute("SELECT * FROM users WHERE email = (%s)", [email])
</code></pre>
<p>That will give you all users that already use this email. So there are 2 possibilities : </p>
<ol>
<li>There is at least one user (hopefully you put a unique constraint on email so there is exactly one) that uses this email. Since the queryset is not empty, you enter the loop, obviously you also enter the if, since you compare the row to the email you used on the request to get the row. Finally you get the expected behavior.</li>
<li>No user have this email. Well then, the problem is the queryset comes up empty, so you don't enter the loop and subsequently you never reach your <code>INSERT INTO</code>. That's the logic problem : your insert should happen only if the queryset is empty but if it is, your code can't reach the insert.</li>
</ol>
<p>I don't know how you tried without loop but this should works :</p>
<pre><code>cur.execute("SELECT * FROM users WHERE email = (%s)", [email])
if cur.fetchone():
email_msg = '...'
elif password == repeat:
cur.execute('...')
else:
pass_msg = '...'
</code></pre>
| 2 | 2016-09-28T12:40:01Z | [
"python",
"if-statement",
"flask"
]
|
ValueError: I/O operation on closed file - Already googled | 39,745,167 | <p>What is wrong with this error message? I googled for it and i still have no idea</p>
| -2 | 2016-09-28T10:41:50Z | 39,745,242 | <p>This is where you open the file:</p>
<pre><code>with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out:
</code></pre>
<p>The <code>with</code> block establishes the context. As soon as this context is left, the file will be closed. This:</p>
<pre><code>writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, ', '.join(ingredients), totalprinter.group(1)])
</code></pre>
<p>â¦is outside the <code>with</code> block. The file has been closed by the time the program reaches this statement, because the <code>with</code> block has ended.</p>
<p>Indent the <code>write.writerow</code> to be within the <code>with</code> block.</p>
| 0 | 2016-09-28T10:44:44Z | [
"python"
]
|
JIRA API error when trying to pull details when field is empty | 39,745,246 | <p>I am using the JIRA API to pull ticket details and put it in a separate database that I can connect Tableau to.
My problem is that when pulling in a ticket details (using python) where e.g. it has no priority, that I get an error.
How do I get around that error? How can I handle this error?</p>
<p>Just currently testing by printing the details on-screen:</p>
<pre><code>for issue in issues:
if verbose:
print( "issue.key: ", issue.key );
print( "issue.fields.project.id: ", issue.fields.project.id );
</code></pre>
<p>The error I get is:</p>
<blockquote>
<p>cursor.execute(sql_stmt, (issue.key, issue.fields.issuetype.name,
issue.fields.project.name, issue.fields.summary,
issue.fields.updated,issue.fields.priority.name)) AttributeError: type
object 'PropertyHolder' has no attribute 'priority</p>
</blockquote>
| 0 | 2016-09-28T10:44:53Z | 39,745,502 | <p>Catch the AttributeError</p>
<pre><code>for issue in issues:
if verbose:
try:
print( "issue.key: ", issue.key );
print( "issue.fields.project.id: ", issue.fields.project.id );
except AttributeError:
pass
</code></pre>
| 1 | 2016-09-28T10:56:42Z | [
"python",
"jira",
"jira-rest-api"
]
|
JIRA API error when trying to pull details when field is empty | 39,745,246 | <p>I am using the JIRA API to pull ticket details and put it in a separate database that I can connect Tableau to.
My problem is that when pulling in a ticket details (using python) where e.g. it has no priority, that I get an error.
How do I get around that error? How can I handle this error?</p>
<p>Just currently testing by printing the details on-screen:</p>
<pre><code>for issue in issues:
if verbose:
print( "issue.key: ", issue.key );
print( "issue.fields.project.id: ", issue.fields.project.id );
</code></pre>
<p>The error I get is:</p>
<blockquote>
<p>cursor.execute(sql_stmt, (issue.key, issue.fields.issuetype.name,
issue.fields.project.name, issue.fields.summary,
issue.fields.updated,issue.fields.priority.name)) AttributeError: type
object 'PropertyHolder' has no attribute 'priority</p>
</blockquote>
| 0 | 2016-09-28T10:44:53Z | 39,747,370 | <p>Thanks @Karimtabet.
It seems though that the following worked better:</p>
<pre><code>if verbose:
try:
print( "issue.key: ", issue.key );
print( "issue.fields.project.id: ", issue.fields.project.id );
except AttributeError:
key = None
</code></pre>
| 0 | 2016-09-28T12:21:29Z | [
"python",
"jira",
"jira-rest-api"
]
|
Python logs working on one pycharm and not on another | 39,745,322 | <p>I've created this python script to help me create log files while running my script and it works perfectly in my own machine. But for some reason the exact code does not work on other machines.
In my machine it shows the logs in pycharm console and also saves them in a file. In other machines it doesn't do anything except for creating a blank file.</p>
<p>What am I doing wrong?</p>
<pre><code>log = logging.getLogger('Logger Name')
try:
logger_file_name = new_file_name()
handler = logging.FileHandler(logger_file_name)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)
log.info(logger_file_name+ ' File will be used for Saving Logs')
main()
except Exception as err:
log.debug("An Error was found which was not caught")
log.exception(err)
</code></pre>
| 0 | 2016-09-28T10:48:12Z | 39,803,396 | <p>Try to explicitly set the logging level, for example:</p>
<pre><code>log.setLevel(logging.DEBUG)
</code></pre>
<p>Otherwise you're relying on the default value which <em>might</em> be different on different python versions that may be installed on different machines. For example on 2.7.12 the default level is set to <code>WARNING</code> and the <code>log.info()</code> messages won't show up - just as you observed. </p>
<p>From the 2.7.12 logging doc's <a href="https://docs.python.org/2/howto/logging.html#a-simple-example" rel="nofollow">A simple example section</a>:</p>
<blockquote>
<pre><code>import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
</code></pre>
<p>If you type these lines into a script and run it, youâll see:</p>
<pre><code>WARNING:root:Watch out!
</code></pre>
<p>printed out on the console. The <code>INFO</code> message doesnât appear because
the default level is <code>WARNING</code>...</p>
</blockquote>
| 0 | 2016-10-01T05:38:02Z | [
"python",
"logging",
"pycharm"
]
|
Python 2.7 Anaconda2 installed in windows | 39,745,371 | <p>My Python 2 environmental path:</p>
<pre><code>C:\Python27
C:\Python27\Scripts
</code></pre>
<p>My Python 3 environmental path:</p>
<pre><code>C:\Python35
C:\Python35\Scripts
</code></pre>
<p>I set the environmental path for Anaconda2</p>
<pre><code>C:\Users\User\Anaconda2\Scripts
C:\Users\User\Anaconda2
</code></pre>
<p>But when i typed python to enter the shell in cmd (C:\Users\user)</p>
<p>Importing the module of Anaconda like numpy or matplotlib</p>
<pre><code>C:\Users\User>python
</code></pre>
<blockquote>
<p>Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.</p>
</blockquote>
<pre><code>>>> import numpy
</code></pre>
<blockquote>
<p>Traceback (most recent call last):
File "", line 1, in
ImportError: No module named numpy</p>
</blockquote>
<pre><code>C:\Users\User>cd Anaconda2
C:\Users\User\Anaconda2>python
</code></pre>
<blockquote>
<p>Python 2.7.12 |Anaconda 4.1.1 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: <a href="http://continuum.io/thanks" rel="nofollow">http://continuum.io/thanks</a> and <a href="https://anaconda.org" rel="nofollow">https://anaconda.org</a></p>
</blockquote>
<pre><code>>>> import numpy
>>>
</code></pre>
<p>So i don't know </p>
<p>1.Why my module can't import while not in Anaconda2</p>
<p>2.It is said that the path of Python2 will overrdie the Python,so how to enter in the Python35 shell?</p>
<p>thanks everybody</p>
| 0 | 2016-09-28T10:50:50Z | 39,745,580 | <p>Each Python installation has its own libraries. As you will see, you are not running the same Python 2.7 interpreter when you run with Anaconda active as you are without (I assume that's either the system Python or one you installed yourself).</p>
<p>Libraries installed in one interpreter aren't available to others. You should consider learning about <a href="http://conda.pydata.org/docs/using/envs.html" rel="nofollow">conda environments</a> to allow you to manage multiple projects easily.</p>
<p>The command <code>deactivate</code> should terminate the Anaconda environment, and if the Python 3 interpreter is first on your PATH you should then be able to run it. Another way would be to explicitly use the command</p>
<pre><code>C:\Python35\python
</code></pre>
<p>which should work even with Anaconda active.</p>
<p><em>Caution</em>: it's a long time since I used Windows, and I don't have current information on getting multiple Pythons to live happily together on Windows.</p>
| 0 | 2016-09-28T11:00:34Z | [
"python",
"anaconda"
]
|
How to parse different parts of a JSON file in Python? | 39,745,396 | <p>I'm making a program in Python that gets bus times from a server and prints them. The JSON file looks like this:</p>
<pre><code>{
"errorcode": "0",
"errormessage": "",
"numberofresults": 4,
"stopid": "175",
"timestamp": "28/09/2016 10:32:44",
"results": [
{
"arrivaldatetime": "28/09/2016 10:43:36",
"duetime": "10",
"departuredatetime": "28/09/2016 10:43:36",
"departureduetime": "10",
"scheduledarrivaldatetime": "28/09/2016 10:44:00",
"scheduleddeparturedatetime": "28/09/2016 10:44:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile AnraÃ",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 09:44:49",
"monitored": "true"
},
{
"arrivaldatetime": "28/09/2016 10:43:56",
"duetime": "11",
"departuredatetime": "28/09/2016 10:43:56",
"departureduetime": "11",
"scheduledarrivaldatetime": "28/09/2016 10:14:00",
"scheduleddeparturedatetime": "28/09/2016 10:14:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile AnraÃ",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 10:32:40",
"monitored": "true"
}, {
"errorcode": "0",
"errormessage": "",
"numberofresults": 4,
"stopid": "175",
"timestamp": "28/09/2016 10:32:44",
"results": [
{
"arrivaldatetime": "28/09/2016 10:43:36",
"duetime": "10",
"departuredatetime": "28/09/2016 10:43:36",
"departureduetime": "10",
"scheduledarrivaldatetime": "28/09/2016 10:44:00",
"scheduleddeparturedatetime": "28/09/2016 10:44:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile AnraÃ",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 09:44:49",
"monitored": "true"
},
{
"arrivaldatetime": "28/09/2016 10:43:56",
"duetime": "11",
"departuredatetime": "28/09/2016 10:43:56",
"departureduetime": "11",
"scheduledarrivaldatetime": "28/09/2016 10:14:00",
"scheduleddeparturedatetime": "28/09/2016 10:14:00",
"destination": "Kimmage",
"destinationlocalized": "Camaigh",
"origin": "Harristown",
"originlocalized": "Baile AnraÃ",
"direction": "Outbound",
"operator": "bac",
"additionalinformation": "",
"lowfloorstatus": "no",
"route": "83",
"sourcetimestamp": "28/09/2016 10:32:40",
"monitored": "true"
},
</code></pre>
<p>I have no problem returning the first block e.g <code>numberofresults</code> by using </p>
<pre><code> info = json.load(req)
print info["numberofresults"]
</code></pre>
<p>However, when I try the same thing with <code>duetime</code> it returns:</p>
<pre><code>File "bus.py", line 10, in <module>
print info["route"]
KeyError: 'route'
</code></pre>
<p>I think this is because the same key turns up multiple times for different buses in the JSON file. How do I specify which bus I want Python to get info for?</p>
<p>File "bus.py", line 10, in
print info['results']['routes']
TypeError: list indices must be integers, not str</p>
<p>EDIT: Managed to get it working by using <code>print info["results"][0]["route"]</code> etc. Thanks all.</p>
| -2 | 2016-09-28T10:52:02Z | 39,745,511 | <pre><code>print info['results']['routes']
</code></pre>
<p>Try above.</p>
| 0 | 2016-09-28T10:57:04Z | [
"python",
"json",
"parsing",
"python-requests"
]
|
Python: classify text into the categories | 39,745,431 | <p>I have a part of training set</p>
<pre><code>url category
ebay.com/sch/Mens-Clothing-/1059/i.html?_from=R40&LH_BIN=1&Bottoms%2520Size%2520%2528Men%2527s%2529=33&Size%2520Type=Regular&_nkw=ÐжинÑÑ&_dcat=11483&Inseam=33&rt=nc&_trksid=p2045573.m1684 Ðнлайн-магазин
google.ru/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=%D0%BA%D0%BA%D1%83%D0%BF%D0%BE%D0%BD%D1%8B%20aliexpress%202016 Search
google.ru/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#newwindow=1&q=%D0%BA%D1%83%D0%BF%D0%BE%D0%BD%D1%8B+aliexpress+2016 Search
google.ru/search?q=авиÑо&oq=авиÑо&aqs=chrome..69i57j0l5.1608j0j7&sourceid=chrome&es_sm=122&ie=UTF-8 Search
irecommend.ru/content/kogda-somnenii-byt-ne-mozhet-tolko-klear-blyu-pomozhet ФоÑÑÐ¼Ñ Ð¸ оÑзÑвÑ
ebay.com/sch/Mens-Clothing-/1059/i.html?_from=R40&LH_BIN=1&Bottoms%2520Size%2520%2528Men%2527s%2529=33&Size%2520Type=Regular&_dcat=11483&Inseam=33&_nkw=ÐжинÑÑ&_sop=15 Ðнлайн-магазин
ebay.com/sch/Mens-Clothing-/1059/i.html?_from=R40&LH_BIN=1&Bottoms%2520Size%2520%2528Men%2527s%2529=33&Size%2520Type=Regular&_dcat=11483&Inseam=33&_nkw=ÐжинÑÑ&_sop=15 Ðнлайн-магазин
irecommend.ru/content/gramotnyi-razvod-na-dengi-bolshe-ne-kuplyu-vret ФоÑÑÐ¼Ñ Ð¸ оÑзÑвÑ
google.ru/search?q=ÑндекÑ&oq=ÑндекÑ&aqs=chrome..69i57j69i61l3j69i59l2.1383j0j1&sourceid=chrome&es_sm=93&ie=UTF-8 Search
google.ru/search?q=авиÑо&oq=авиÑо&aqs=chrome..69i57j69i59j69i60.1095j0j1&sourceid=chrome&es_sm=93&ie=UTF-8 Search
otzovik.com/review_1399716.html#debug ФоÑÑÐ¼Ñ Ð¸ оÑзÑвÑ
svyaznoy.ru Ðнлайн-магазин
mvideo.ru/smartfony-sotovye-telefony/apple-iphone-2927 Ðнлайн-магазин
mvideo.ru/promo/rassrochka-0-0-12-mark24197850/f/category=iphone-914?sort=priceLow&_=1453896710474&categoryId=10 Ðнлайн-магазин
svyaznoy.ru/catalog/phone/224/tag/windows-phone Ðнлайн-магазин
google.it/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=%D0%B5%D0%B2%D1%80%D0%BE%D1%81%D0%B5%D1%82%D1%8C Search
vk.com Social network
</code></pre>
<p>it's a connection between <code>url</code> and <code>category</code>
And also I have test set and I need to get category to every url.</p>
<pre><code>url
vk.com/topic-102849764_32295213
stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set
google.ru/search?q=learning+sample&oq=learning+sample&aqs=chrome..69i57.4063j0j1&sourceid=chrome&ie=UTF-8#newwindow=1&q=machine+learning+test+and+learn
facebook.com
locals.ru
tvzvezda.ru/news/vstrane_i_mire/content/201609261038-k6n1.htm
</code></pre>
<p>I don't know, what algorithm should I use to solve this task.
I need the best way to get the most accuracy.
And I think it's a problem, that I have multiple categories.</p>
<p>I try first parse html tag <code>title</code>, because I think, that I can's determine category only with <code>url</code>.</p>
| 1 | 2016-09-28T10:53:14Z | 39,745,701 | <p>Basically you will classify strings into categories. Therefore you will to use a classifier. But you will not just use one classifier but rather test several and chose the most accurate. </p>
<p>Yet firstly, you will have to think about features of each url. I expect that you will not achieve great accuracy if you are simply feeding the url as a string and as the only feature.</p>
<p>Rather you will preprocess each url to extract features. The choice of relevant/useful features strongly depends on the domain. A feature could be:</p>
<p>simple features</p>
<ul>
<li><p>the first word until the dot such as: facebook for "facebook.com" </p></li>
<li><p>the length of the whole string</p></li>
</ul>
<p>complex features</p>
<p>imagine you define keywords for each cluster such as for "online-shopping"-cluster you will define [promo, buy, shop, sell, price], then you can compute the number of keywords which occur in the string for each cluster as a feature</p>
<p>Therefore, you will have to continue firstly with <strong>feature-engineering</strong> and secondly with a comparing classifier performance. </p>
<p>Additional input: </p>
<p><a href="http://stackoverflow.com/questions/26456904/how-to-classify-urls-what-are-urls-features-how-to-select-and-extract-features">Similiar question on SO (regarding URL features)</a></p>
<p><a href="http://blog.christianperone.com/2011/09/machine-learning-text-feature-extraction-tf-idf-part-i/" rel="nofollow">Text feature extraction</a></p>
<p><a href="https://www.comp.nus.edu.sg/~kanmy/papers/cp689-kan.pdf" rel="nofollow">Fast Webpage Classification Using URL Features</a></p>
<p>EDIT: An example</p>
<pre><code>url = "irecommend.ru/content/kogda-somnenii-byt-ne-mozhet-tolko-klear-blyu-pomozhet"
f1 = len(url) = 76
f2 = base = str(url).split("/",1)[0] = "irecommend.ru"
f3 = segments = str(a).count("/") = 2
</code></pre>
<p>more solutions from <a href="http://stackoverflow.com/questions/6969268/counting-letters-numbers-and-punctuation-in-a-string">here</a> by <a href="http://stackoverflow.com/users/997301/eiyrio%C3%BC-von-kauyf">Eiyrioü von Kauyf</a></p>
<pre><code>import string
count = lambda l1,l2: sum([1 for x in l1 if x in l2])
f4 = count_punctuation = count(a,set(string.punctuation))
f5 = count_ascii = count(a,set(string.ascii_letters))
</code></pre>
<p>Yet all these examples are very simple features, which do not cover the semantic content of the URL. Depending on the depth/sophistication of your target variables (clusters), you might need to use features n-gram based features such as in <a href="https://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwjgrsC2i7TPAhWKaRQKHUfLBD4QFggvMAA&url=http%3A%2F%2Fwww.springer.com%2Fcda%2Fcontent%2Fdocument%2Fcda_downloaddocument%2F9783319258393-c2.pdf%3FSGWID%3D0-0-45-1533089-p177762447&usg=AFQjCNHJeV8TIhj1ylnkG0aMWIZoNJK4bA&cad=rja" rel="nofollow">here</a></p>
| 2 | 2016-09-28T11:06:30Z | [
"python",
"url",
"machine-learning",
"scikit-learn",
"text-classification"
]
|
How to keep specific element indexs in an array | 39,745,545 | <p>Suppose I have two arrays:</p>
<pre><code>a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [2,5,7]
</code></pre>
<p>And I want to keep the elements indexed in a that are listed in b so the 2nd, 5th and 7th index of a:</p>
<pre><code>a_new = [4, 25, 49]
</code></pre>
<p>I will then plot b against a_new / perform analysis on it.</p>
<p>For my application, a is a long series of simulated data, and b is a time series of when I want to sample from this data.</p>
<p>Thanks</p>
| -1 | 2016-09-28T10:58:52Z | 39,746,059 | <p>There are two possible problems that you may be encountering, both of which have been somewhat mentioned in the comments. From what I see, you either have a problem reading the or you have an invalid index in <code>b</code>.</p>
<p>For the former, you may actually want</p>
<pre><code>a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [2,5,7]
</code></pre>
<p>To produce:</p>
<pre><code>a_new = [9, 36, 64]
</code></pre>
<p>Since you always count starting from zero:</p>
<pre><code>[1, 4, 9, 16, 25, 36, 49, 64, 81]
0 1 2 3 4 5 6 7 8
</code></pre>
<p>Hence, leading to an <a href="http://xyproblem.info/" rel="nofollow">XY problem</a>, where you try to solve a problem <em>your way</em> which is the wrong way. Therefore, it wastes our time to try to fix a problem that doesn't work since it is actually something else.</p>
<p>However, for the latter, you may have an anomaly in your <code>b</code> list. The way to index the list (given in the comments) as you wanted is using <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>a_new = [a[i-1] for i in b]
</code></pre>
<p>What this does is:</p>
<pre><code>a_new = []
for i in b:
a_new.append(a[i-1])
</code></pre>
<p>Hence, when <code>i</code> is larger than or equal to <code>len(a)</code>, it evaluates to an invalid index:</p>
<pre><code>>>> a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> len(a)
9
>>> a[9]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code></pre>
| 1 | 2016-09-28T11:24:10Z | [
"python",
"arrays",
"list",
"indexing"
]
|
How to keep specific element indexs in an array | 39,745,545 | <p>Suppose I have two arrays:</p>
<pre><code>a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [2,5,7]
</code></pre>
<p>And I want to keep the elements indexed in a that are listed in b so the 2nd, 5th and 7th index of a:</p>
<pre><code>a_new = [4, 25, 49]
</code></pre>
<p>I will then plot b against a_new / perform analysis on it.</p>
<p>For my application, a is a long series of simulated data, and b is a time series of when I want to sample from this data.</p>
<p>Thanks</p>
| -1 | 2016-09-28T10:58:52Z | 39,746,820 | <p>First remember that the first element of an array (or in this case a list) is number 0 and not number 1:</p>
<pre><code>a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
a[0] = 1 # How to adress the first element
a[1] = 4 # How to adress the second element
a[2] = 9 # ...
</code></pre>
<p>So the elements you want (as specified in the array b) are:</p>
<pre><code>a[1] = 4 # a[1] is the same as a[2 - 1] (note that b[0] = 2)
a[4] = 25 # a[4] is the same as a[5 - 1] (note that b[1] = 5)
a[6] = 49 # a[6] is the same as a[7 - 1] (note that b[2] = 7)
</code></pre>
<p>So you can also access the elements this way:</p>
<pre><code>a[ b[0] - 1 ] = 4 # Same as a[1] which is the second element
a[ b[1] - 1 ] = 25 # Same as a[4] which is the fifth element
a[ b[2] - 1 ] = 49 # Same as a[6] which is the seventh element
</code></pre>
<p>This can be wrapped up in a for-loop:</p>
<pre><code>a_new = [] # Start with an empty list
for index in b: # index in b are all elements in b, thus: b[0] = 2, b[1] = 5 and b[2] = 7
a_new.append(a[ index - 1])
</code></pre>
<p>This loop will put the elements <code>a[2 - 1]</code> (4), <code>a[5 - 1]</code> (25) and <code>a[7 - 1]</code> (49) into the list<code>a_new</code>.
<br><br>
But there is a shorter way to write that loop:</p>
<pre><code>a_new = [ a[ index - 1] for index in b ]
</code></pre>
<p>Basically, you say <code>a_new = [ ... ]</code>, so <code>a_new</code> is a list, and the <code>...</code> inside will specify, what the list will be filled with. In this case, it will be the elements that the for-loop produces, note that <code>a[ index - 1] for index in b</code> is the same for-loop as in the first example, written in a compact way.
<br><br>
<strong>What if you get an list index out of range error?</strong>
<br>
Your list<code>a</code> contains 9 elements, so the first element is <code>a[0]</code> and the last is <code>a[8]</code>. If you try to access any other element in a list, for example <code>a[12]</code>, you will get a "list index out of range" error.
<br>
That means: the list b should only contain numbers between 1 and 9 (the length of the list, which you can find out this way <code>len[a] = 9</code>).
<br><br>
<strong>I would recommend</strong>, that you change your list b to <code>b = [1, 4, 6]</code>, since the fifth element of an array is actually adressed like <code>a[4]</code> and not <code>a[5]</code>.
<br>
The code will be a bit easier:</p>
<pre><code>a_new = [ a[index] for index in b ]
</code></pre>
<p>If you don't want errors to happen, the values in b should then be between 0 and 8 (which is <code>len(a) - 1</code>), since <code>a[0]</code> is the first and <code>a[8]</code> is the last element, and only elements between that exist!</p>
| 2 | 2016-09-28T11:58:51Z | [
"python",
"arrays",
"list",
"indexing"
]
|
Is there a pythonic way of permuting a list of list? | 39,745,571 | <p>I have a list of lists containing unique strings and I want to produce an arbitrary number of different ways of sorting it. The list might look like the following:</p>
<pre><code>list = [[a], [b,c], [d], [e,f,g]]
</code></pre>
<p>The order of the lists need to be the same but I want to shuffle the ordering within a list and then have them in a single list, e.g</p>
<pre><code>list1 = [a,b,c,d,e,f,g]
list2 = [a,c,b,d,f,e,g]
...
...
listN = [a,c,b,d,f,g,e]
</code></pre>
<p>What is a good pythonic way of achieving this? I'm on python 2.7.</p>
| 1 | 2016-09-28T10:59:55Z | 39,745,708 | <p>You can flatten the list then simply generate its permutations:</p>
<pre><code>from itertools import chain, permutations
li = [['a'], ['b','c'], ['d'], ['e','f','g']]
flattened = list(chain.from_iterable(li))
for perm in permutations(flattened, r=len(flattened)):
print(perm)
>> ('a', 'b', 'c', 'd', 'e', 'f', 'g')
('a', 'b', 'c', 'd', 'e', 'g', 'f')
('a', 'b', 'c', 'd', 'f', 'e', 'g')
('a', 'b', 'c', 'd', 'f', 'g', 'e')
('a', 'b', 'c', 'd', 'g', 'e', 'f')
('a', 'b', 'c', 'd', 'g', 'f', 'e')
('a', 'b', 'c', 'e', 'd', 'f', 'g')
('a', 'b', 'c', 'e', 'd', 'g', 'f')
('a', 'b', 'c', 'e', 'f', 'd', 'g')
...
...
...
</code></pre>
| -1 | 2016-09-28T11:06:47Z | [
"python",
"list",
"python-2.7",
"permutation"
]
|
Is there a pythonic way of permuting a list of list? | 39,745,571 | <p>I have a list of lists containing unique strings and I want to produce an arbitrary number of different ways of sorting it. The list might look like the following:</p>
<pre><code>list = [[a], [b,c], [d], [e,f,g]]
</code></pre>
<p>The order of the lists need to be the same but I want to shuffle the ordering within a list and then have them in a single list, e.g</p>
<pre><code>list1 = [a,b,c,d,e,f,g]
list2 = [a,c,b,d,f,e,g]
...
...
listN = [a,c,b,d,f,g,e]
</code></pre>
<p>What is a good pythonic way of achieving this? I'm on python 2.7.</p>
| 1 | 2016-09-28T10:59:55Z | 39,745,867 | <pre><code>from itertools import permutations, product
L = [['a'], ['b','c'], ['d'], ['e', 'f', 'g']]
for l in product(*map(lambda l: permutations(l), L)):
print([item for s in l for item in s])
</code></pre>
<p>produces:</p>
<pre><code>['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'g', 'f']
['a', 'b', 'c', 'd', 'f', 'e', 'g']
['a', 'b', 'c', 'd', 'f', 'g', 'e']
['a', 'b', 'c', 'd', 'g', 'e', 'f']
['a', 'b', 'c', 'd', 'g', 'f', 'e']
['a', 'c', 'b', 'd', 'e', 'f', 'g']
['a', 'c', 'b', 'd', 'e', 'g', 'f']
['a', 'c', 'b', 'd', 'f', 'e', 'g']
['a', 'c', 'b', 'd', 'f', 'g', 'e']
['a', 'c', 'b', 'd', 'g', 'e', 'f']
['a', 'c', 'b', 'd', 'g', 'f', 'e']
</code></pre>
| 2 | 2016-09-28T11:14:45Z | [
"python",
"list",
"python-2.7",
"permutation"
]
|
Is there a pythonic way of permuting a list of list? | 39,745,571 | <p>I have a list of lists containing unique strings and I want to produce an arbitrary number of different ways of sorting it. The list might look like the following:</p>
<pre><code>list = [[a], [b,c], [d], [e,f,g]]
</code></pre>
<p>The order of the lists need to be the same but I want to shuffle the ordering within a list and then have them in a single list, e.g</p>
<pre><code>list1 = [a,b,c,d,e,f,g]
list2 = [a,c,b,d,f,e,g]
...
...
listN = [a,c,b,d,f,g,e]
</code></pre>
<p>What is a good pythonic way of achieving this? I'm on python 2.7.</p>
| 1 | 2016-09-28T10:59:55Z | 39,745,940 | <pre><code>from itertools import chain, permutations
your_list = [[a], [b,c], [d], [e,f,g]]
flattened = chain.from_iterable(your_list)
perms = permutations(flattened)
for perm in perms:
print perm
</code></pre>
<p>References:</p>
<ul>
<li><a href="https://docs.python.org/2/library/itertools.html#itertools.permutations" rel="nofollow">permutations in Python 2</a></li>
<li><a href="https://docs.python.org/2/library/itertools.html#itertools.chain" rel="nofollow">chain in Python 2</a></li>
</ul>
| -1 | 2016-09-28T11:18:04Z | [
"python",
"list",
"python-2.7",
"permutation"
]
|
Is there a pythonic way of permuting a list of list? | 39,745,571 | <p>I have a list of lists containing unique strings and I want to produce an arbitrary number of different ways of sorting it. The list might look like the following:</p>
<pre><code>list = [[a], [b,c], [d], [e,f,g]]
</code></pre>
<p>The order of the lists need to be the same but I want to shuffle the ordering within a list and then have them in a single list, e.g</p>
<pre><code>list1 = [a,b,c,d,e,f,g]
list2 = [a,c,b,d,f,e,g]
...
...
listN = [a,c,b,d,f,g,e]
</code></pre>
<p>What is a good pythonic way of achieving this? I'm on python 2.7.</p>
| 1 | 2016-09-28T10:59:55Z | 39,746,045 | <p>You can do this by taking the Cartesian product of the permutations of the sub-lists, and then flattening the resulting nested tuples. </p>
<pre><code>from itertools import permutations, product, chain
lst = [['a'], ['b', 'c'], ['d'], ['e', 'f', 'g']]
for t in product(*[permutations(u) for u in lst]):
print([*chain.from_iterable(t)])
</code></pre>
<p><strong>output</strong></p>
<pre><code>['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'g', 'f']
['a', 'b', 'c', 'd', 'f', 'e', 'g']
['a', 'b', 'c', 'd', 'f', 'g', 'e']
['a', 'b', 'c', 'd', 'g', 'e', 'f']
['a', 'b', 'c', 'd', 'g', 'f', 'e']
['a', 'c', 'b', 'd', 'e', 'f', 'g']
['a', 'c', 'b', 'd', 'e', 'g', 'f']
['a', 'c', 'b', 'd', 'f', 'e', 'g']
['a', 'c', 'b', 'd', 'f', 'g', 'e']
['a', 'c', 'b', 'd', 'g', 'e', 'f']
['a', 'c', 'b', 'd', 'g', 'f', 'e']
</code></pre>
<p>If you need to do this in Python 2, you can replace the print line with this: </p>
<pre><code>print list(chain.from_iterable(t))
</code></pre>
<hr>
<p>Here's a more compact version, inspired by ewcz's answer:</p>
<pre><code>for t in product(*map(permutations, lst)):
print list(chain.from_iterable(t))
</code></pre>
| 3 | 2016-09-28T11:23:28Z | [
"python",
"list",
"python-2.7",
"permutation"
]
|
Is there a pythonic way of permuting a list of list? | 39,745,571 | <p>I have a list of lists containing unique strings and I want to produce an arbitrary number of different ways of sorting it. The list might look like the following:</p>
<pre><code>list = [[a], [b,c], [d], [e,f,g]]
</code></pre>
<p>The order of the lists need to be the same but I want to shuffle the ordering within a list and then have them in a single list, e.g</p>
<pre><code>list1 = [a,b,c,d,e,f,g]
list2 = [a,c,b,d,f,e,g]
...
...
listN = [a,c,b,d,f,g,e]
</code></pre>
<p>What is a good pythonic way of achieving this? I'm on python 2.7.</p>
| 1 | 2016-09-28T10:59:55Z | 39,746,162 | <p>This might not be the most elegant solution, but I think it does what you want</p>
<pre><code>from itertools import permutations
import numpy as np
def fac(n):
if n<=1:
return 1
else:
return n * fac(n-1)
lists = [['a'], ['b','c'], ['d'], ['e','f','g']]
combined = [[]]
for perm in [permutations(l,r=len(l)) for l in lists]:
expanded = []
for e in list(perm):
expanded += [list(l) + list(e) for l in combined]
combined = expanded
## check length
print np.prod(map(fac,map(len,lists))), len(combined)
print '\n'.join(map(str,combined))
</code></pre>
| 0 | 2016-09-28T11:29:14Z | [
"python",
"list",
"python-2.7",
"permutation"
]
|
Setting a row index on and querying a pandas dataframe with multi-index columns | 39,745,627 | <p>Starting from a <code>pandas</code> dataframe with a multi-dimensional column heading structure such as the following, is there a way I can transform the <code>Area Names</code> and <code>Area Codes</code> headings so they span each level (i.e. so single <code>Area Names</code> and <code>Area Codes</code> labels spanning the multiple column heading rows?</p>
<p><a href="http://i.stack.imgur.com/6MrXt.png" rel="nofollow"><img src="http://i.stack.imgur.com/6MrXt.png" alt="Multidimensional column heading table"></a></p>
<p>If so, how could I then run a query on the column to just return the row corresponding to a particular value (e.g. an <em>Area Code</em> of <em>E06000047</em>), or the <em>Low</em> and <em>Very High</em> values for <em>ENGLAND</em> in <em>2012/13</em>?</p>
<p>I wonder if it would be easier to define a row index based on either <em>Area Code</em> or <em>Area Names</em>, or a two column row index <code>['*Area Code*', '*Area Names*']</code>. And if so, how can I do this from the current table? <code>set_index</code> seems to balk at this using the current structure?</p>
<p>Code fragment to create the above:</p>
<pre><code>import pandas as pd
df= pd.DataFrame({('2011/12*', 'High', '7-8'): {3: 49.83,
5: 50.01,
7: 48.09,
8: 43.58,
9: 44.19},
('2011/12*', 'Low', '0-4'): {3: 6.51, 5: 6.53, 7: 6.49, 8: 6.41, 9: 6.12},
('2011/12*', 'Medium', '5-6'): {3: 17.44,
5: 17.59,
7: 18.11,
8: 19.23,
9: 20.01},
('2011/12*', 'Very High', '9-10'): {3: 26.22,
5: 25.87,
7: 27.32,
8: 30.78,
9: 29.68},
('2012/13*', 'High', '7-8'): {3: 51.16,
5: 51.35,
7: 48.47,
8: 44.67,
9: 49.39},
('2012/13*', 'Low', '0-4'): {3: 5.71, 5: 5.74, 7: 6.73, 8: 8.42, 9: 6.51},
('2012/13*', 'Medium', '5-6'): {3: 17.1,
5: 17.29,
7: 18.46,
8: 20.23,
9: 15.81},
('2012/13*', 'Very High', '9-10'): {3: 26.03,
5: 25.62,
7: 26.34,
8: 26.68,
9: 28.3},
('Area Codes', 'Area Codes', 'Area Codes'): {3: 'K02000001',
5: 'E92000001',
7: 'E12000001',
8: 'E06000047',
9: 'E06000005'},
('Area Names', 'Area Names', 'Area Names'): {3: 'UNITED KINGDOM',
5: 'ENGLAND',
7: 'NORTH EAST',
8: 'County Durham',
9: 'Darlington'}})
</code></pre>
| 1 | 2016-09-28T11:02:25Z | 39,745,756 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> with tuples for set by <code>MultiIndex</code>:</p>
<pre><code>df.set_index([('Area Codes','Area Codes','Area Codes'),
('Area Names','Area Names','Area Names')], inplace=True)
df.index.names = ['Area Codes','Area Names']
print (df)
2011/12* 2012/13* \
High Low Medium Very High High Low
7-8 0-4 5-6 9-10 7-8 0-4
Area Codes Area Names
K02000001 UNITED KINGDOM 49.83 6.51 17.44 26.22 51.16 5.71
E92000001 ENGLAND 50.01 6.53 17.59 25.87 51.35 5.74
E12000001 NORTH EAST 48.09 6.49 18.11 27.32 48.47 6.73
E06000047 County Durham 43.58 6.41 19.23 30.78 44.67 8.42
E06000005 Darlington 44.19 6.12 20.01 29.68 49.39 6.51
Medium Very High
5-6 9-10
Area Codes Area Names
K02000001 UNITED KINGDOM 17.10 26.03
E92000001 ENGLAND 17.29 25.62
E12000001 NORTH EAST 18.46 26.34
E06000047 County Durham 20.23 26.68
E06000005 Darlington 15.81 28.30
</code></pre>
<p>Then need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a>, because:</p>
<blockquote>
<p>KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)'</p>
</blockquote>
<pre><code>df.sort_index(inplace=True)
</code></pre>
<p>Last use selecting by <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow">slicers</a>:</p>
<pre><code>idx = pd.IndexSlice
print (df.loc[idx['E06000047',:], :])
2011/12* 2012/13* \
High Low Medium Very High High Low
7-8 0-4 5-6 9-10 7-8 0-4
Area Codes Area Names
E06000047 County Durham 43.58 6.41 19.23 30.78 44.67 8.42
Medium Very High
5-6 9-10
Area Codes Area Names
E06000047 County Durham 20.23 26.68
</code></pre>
<hr>
<pre><code>print (df.loc[idx[:,'ENGLAND'], idx['2012/13*',['Low','Very High']]])
2012/13*
Low Very High
0-4 9-10
Area Codes Area Names
E92000001 ENGLAND 5.74 25.62
</code></pre>
| 1 | 2016-09-28T11:09:08Z | [
"python",
"pandas",
"indexing",
"multiple-columns",
"multi-index"
]
|
Change dictionary values from int to string | 39,745,633 | <p>This is what my dictionary looks like.</p>
<pre><code>phoneBook = {"Skywalker": 55511243, "Solo": 55568711, "Vader": 55590858}
</code></pre>
<p>I need to change each phonenumber into a string and add <code>"+1-"</code> in front of it. But, I'm not sure how to do it.</p>
| -1 | 2016-09-28T11:02:42Z | 39,745,692 | <p>Use a dictionary comprehension</p>
<pre><code>{k:'+1-'+str(phoneBook[k]) for k in phoneBook}
</code></pre>
| 1 | 2016-09-28T11:06:08Z | [
"python",
"string",
"python-3.x",
"dictionary",
"int"
]
|
Change dictionary values from int to string | 39,745,633 | <p>This is what my dictionary looks like.</p>
<pre><code>phoneBook = {"Skywalker": 55511243, "Solo": 55568711, "Vader": 55590858}
</code></pre>
<p>I need to change each phonenumber into a string and add <code>"+1-"</code> in front of it. But, I'm not sure how to do it.</p>
| -1 | 2016-09-28T11:02:42Z | 39,745,735 | <p>With a simple dictionary comprehension:</p>
<pre><code>r = {k: "+1-{}".format(v) for k,v in phoneBook.items()}
</code></pre>
<p>Where <code>"+1-{}".format(v)</code> converts to a string and prepends <code>+1-</code> to it. Similarly you could use <code>"+1-" + str(v)</code> as noted in the other answer but I <em>personally</em> find it less readable.</p>
<pre><code>print(r)
{'Skywalker': '+1-55511243', 'Solo': '+1-55568711', 'Vader': '+1-55590858'}
</code></pre>
<p>Alternatively, if you want to do it <em>in-place</em>, i.e not create a new dictionary as comprehensions do, iterate <em>over the keys</em><sup>*</sup> and update the values:</p>
<pre><code>for k in phoneBook:
phoneBook[k] = "+1-{}".format(phoneBook[k])
</code></pre>
<p><sup>*Iterating over the keys only is important, if you iterate over both keys and values you'll get odd behavior because you'll be altering the view you iterate through.</sup></p>
| 2 | 2016-09-28T11:08:03Z | [
"python",
"string",
"python-3.x",
"dictionary",
"int"
]
|
C++ code not exiting when wrapped in python | 39,745,751 | <p>I am having an issue with my python code exiting while running my c++ code lib. I can't seem to figure out if its the python code doing it or my c++. Any help would be greatly appreciated. </p>
<p>Here is my cpp</p>
<pre><code>class Led {
public:
void snowled()
{
LinuxGPIO gpio23(23);
gpio23.SetDirection(true);
bool on = true;
for (;;)
{
printf("Switching %s the LED...\n", on ? "on" : "off");
gpio23.SetValue(on);
on = !on;
sleep(1);
}
}
};
extern "C" {
Led* Led_new(){ return new Led(); }
void Led_snowled(Led* led){ led->snowled(); }
}
</code></pre>
<p>here is my python
#I tried calling sys.exit() but it will not exit. </p>
<pre><code>import sys
import time
from ctypes import cdll
lib = cdll.LoadLibrary('./snowled.so')
class Led(object):
def __init__(self):
self.obj = lib.Led_new()
def snowled(self):
lib.Led_snowled(self.obj)
def sleeper(self):
num = float(1)
time.sleep(num)
def main(self):
light = Led()
light.snowled()
def stop_running(self):
try:
sys.exit()
except:
print(sys.exc_info()[0])
if __name__=='__main__':
Led().main()
Led().stop_running()
</code></pre>
| -1 | 2016-09-28T11:08:53Z | 39,746,285 | <p>The call <code>sys.exit()</code> actually raise a <a href="https://docs.python.org/2/library/exceptions.html#exceptions.SystemExit" rel="nofollow">SystemExit</a> exception. Without parameters, the exit status is zero. </p>
<p>Why do you catch it?</p>
| 0 | 2016-09-28T11:34:59Z | [
"python",
"c++",
"cpython"
]
|
Speed-up cython code | 39,745,881 | <p>I have code that is working in python and want to use cython to speed up the calculation. The function that I've copied is in a .pyx file and gets called from my python code. V, C, train, I_k are 2-d numpy arrays and lambda_u, user, hidden are ints.
I don't have any experience in using C or cython. What is an efficient
way to make this code faster.
Using <code>cython -a</code> for compiling shows me that the code is flawed but how can I improve it. Using <code>for i in prange (user_size, nogil=True):</code>
results in <code>Constructing Python slice object not allowed without gil</code>.</p>
<p>How has the code to be modified to harvest the power of cython?</p>
<pre><code> @cython.boundscheck(False)
@cython.wraparound(False)
def u_update(V, C, train, I_k, lambda_u, user, hidden):
cdef int user_size = user
cdef int hidden_dim = hidden
cdef np.ndarray U = np.empty((hidden_dim,user_size), float)
cdef int m = C.shape[1]
for i in range(user_size):
C_i = np.zeros((m, m), dtype=float)
for j in range(m):
C_i[j,j]=C[i,j]
U[:,i] = np.dot(np.linalg.inv(np.dot(V, np.dot(C_i,V.T)) + lambda_u*I_k), np.dot(V, np.dot(C_i,train[i,:].T)))
return U
</code></pre>
| 1 | 2016-09-28T11:15:25Z | 39,747,088 | <p>The first thing that comes to mind is you haven't typed the function arguments and specified the data type and number of dimensions like so :</p>
<pre><code>def u_update(np.ndarray[np.float64, ndim=2]V, np.ndarray[np.float64, ndim=2]\
C, np.ndarray[np.float64, ndim=2] train, np.ndarray[np.float64, ndim=2] \
I_k, int lambda_u, int user, int hidden) :
</code></pre>
<p>This will greatly speed up indexing with 2 indices like you do in the inner loop.</p>
<p>It's best to do this to the array <code>U</code> as well, although you are using slicing:</p>
<pre><code>cdef np.ndarray[np.float64, ndim=2] U = np.empty((hidden_dim,user_size), np.float64)
</code></pre>
<p>Next, you are redefining <code>C_i</code>, a large 2-D array every iteration of the outer loop. Also, you have not supplied any type information for it, which is a must if Cython is to offer any speedup. To fix this :</p>
<pre><code>cdef np.ndarray[np.float64, ndim=2] C_i = np.zeros((m, m), dtype=np.float64)
for i in range(user_size):
C_i.fill(0)
</code></pre>
<p>Here, we have defined it once (with type information), and reused the memory by filling with zeros instead of calling <code>np.zeros()</code> to make a new array every time.</p>
<p>Also, you might want to turn off bounds checking only <em>after</em> you have finished debugging.</p>
<p>If you need speedups in the <code>U[:,i]=...</code> step, you could consider writing another function with Cython to perform those operations using loops.</p>
<p>Do read this <a href="http://cython.readthedocs.io/en/latest/src/userguide/numpy_tutorial.html" rel="nofollow">tutorial</a> which should give you an idea of what to do when working with Numpy arrays in Cython and what not to do as well, and also to appreciate how much of a speedup you can get with these simple changes.</p>
| 1 | 2016-09-28T12:09:49Z | [
"python",
"numpy",
"cython"
]
|
Speed-up cython code | 39,745,881 | <p>I have code that is working in python and want to use cython to speed up the calculation. The function that I've copied is in a .pyx file and gets called from my python code. V, C, train, I_k are 2-d numpy arrays and lambda_u, user, hidden are ints.
I don't have any experience in using C or cython. What is an efficient
way to make this code faster.
Using <code>cython -a</code> for compiling shows me that the code is flawed but how can I improve it. Using <code>for i in prange (user_size, nogil=True):</code>
results in <code>Constructing Python slice object not allowed without gil</code>.</p>
<p>How has the code to be modified to harvest the power of cython?</p>
<pre><code> @cython.boundscheck(False)
@cython.wraparound(False)
def u_update(V, C, train, I_k, lambda_u, user, hidden):
cdef int user_size = user
cdef int hidden_dim = hidden
cdef np.ndarray U = np.empty((hidden_dim,user_size), float)
cdef int m = C.shape[1]
for i in range(user_size):
C_i = np.zeros((m, m), dtype=float)
for j in range(m):
C_i[j,j]=C[i,j]
U[:,i] = np.dot(np.linalg.inv(np.dot(V, np.dot(C_i,V.T)) + lambda_u*I_k), np.dot(V, np.dot(C_i,train[i,:].T)))
return U
</code></pre>
| 1 | 2016-09-28T11:15:25Z | 39,752,528 | <p>You are trying to use <code>cython</code> by diving into the deep end of pool. You should start with something small, such as some of the numpy examples. Or even try to improve on <code>np.diag</code>.</p>
<pre><code> i = 0
C_i = np.zeros((m, m), dtype=float)
for j in range(m):
C_i[j,j]=C[i,j]
</code></pre>
<p>v.</p>
<pre><code> C_i = diag(C[i,:])
</code></pre>
<p>Can you improve the speed of this simple expression? <code>diag</code> is not compiled, but it does perform an efficient indexed assignment. </p>
<pre><code> res[:n-k].flat[i::n+1] = v
</code></pre>
<p>But the real problem for <code>cython</code> is this expression:</p>
<pre><code>U[:,i] = np.dot(np.linalg.inv(np.dot(V, np.dot(C_i,V.T)) + lambda_u*I_k), np.dot(V, np.dot(C_i,train[i,:].T)))
</code></pre>
<p><code>np.dot</code> is compiled. <code>cython</code> won't turn that in to <code>c</code> code, nor will it consolidate all 5 <code>dots</code> into one expression. It also won't touch the <code>inv</code>. So at best <code>cython</code> will speed up the iteration wrapper, but it will still call this Python expression <code>m</code> times.</p>
<p>My guess is that this expression can be cleaned up. Replacing the inner <code>dots</code> with <code>einsum</code> can probably eliminate the need for <code>C_i</code>. The <code>inv</code> might make 'vectorizing' the whole thing difficult. But I'd have to study it more. </p>
<p>But if you want to stick with the <code>cython</code> route, you need to transform that <code>U</code> expression into simple iterative code, without calls to numpy functions like <code>dot</code> and <code>inv</code>.</p>
<p>===================</p>
<p>I believe the following are equivalent:</p>
<pre><code>np.dot(C_i,V.T)
C[i,:,None]*V.T
</code></pre>
<p>In:</p>
<pre><code>np.dot(C_i,train[i,:].T)
</code></pre>
<p>if <code>train</code> is 2d, then <code>train[i,:]</code> is 1d, and the <code>.T</code> does nothing.</p>
<pre><code>In [289]: np.dot(np.diag([1,2,3]),np.arange(3))
Out[289]: array([0, 2, 6])
In [290]: np.array([1,2,3])*np.arange(3)
Out[290]: array([0, 2, 6])
</code></pre>
<p>If I got that right, you don't need <code>C_i</code>.</p>
<p>======================</p>
<p>Furthermore, these calculations can be moved outside the loop, with expressions like (not tested)</p>
<pre><code>CV1 = C[:,:,None]*V.T # a 3d array
CV2 = C * train.T
for i in range(user_size):
U[:,i] = np.dot(np.linalg.inv(np.dot(V, CV1[i,...]) + lambda_u*I_k), np.dot(V, CV2[i,...]))
</code></pre>
<p>A further step is to move both <code>np.dot(V,CV...)</code> out of the loop. That may require <code>np.matmul</code> (@) or <code>np.einsum</code>. Then we will have</p>
<pre><code>for i...
I = np.linalg.inv(VCV1[i,...])
U[:,i] = np.dot(I+ lambda_u), VCV2[i,])
</code></pre>
<p>or even</p>
<pre><code>for i...
I[...i] = np.linalg.inv(...) # if inv can't be vectorized
U = np.einsum(..., I+lambda_u, VCV2)
</code></pre>
<p>This is a rough sketch, and details will need to be worked out.</p>
| 2 | 2016-09-28T16:04:59Z | [
"python",
"numpy",
"cython"
]
|
Incorrect line number returned on specifying Start parameter in enumerate Python | 39,745,985 | <p>I have slight confusion regarding the start parameter in enumerate function,as i recently started working on python i don't have much idea how it is supposed to work.
Suppose i have an example file below:</p>
<pre><code>Test 1
Test 2
Test 3
</code></pre>
<p>This is the first line <code>[SB WOM]|[INTERNAL REQUEST]|[START]</code> which is the start of message</p>
<pre><code>Name : Vaibhav
Designation : Technical Lead
ID : 123456
Company : Nokia
</code></pre>
<p>This is the sixth line <code>[SB WOM]|[INTERNAL REQUEST]|[END]</code> which is the end of message</p>
<p>Now when i run the below code :</p>
<pre><code>path =("C:/Users/vgupt021/Desktop")
in_file = os.path.join(path,"KSClogs_Test.txt")
fd = open(in_file,'r')
for linenum,line in enumerate(fd) :
if "[SB WOM]|[INTERNAL REQUEST]|[START]" in line:
x1 = linenum
print x1
break
for linenum,line in enumerate(fd,x1):
if "[SB WOM]|[INTERNAL REQUEST]|[END]" in line:
print linenum
break
</code></pre>
<p>I get the linenum returned as 3 and 7, I am not clear why it is not returned as 3,8.Since the index number of line <code>"[SB WOM]|[INTERNAL REQUEST]|[END]"</code> is 8 and not 7, how the start parameter makes the difference in second part of the loop.</p>
| 1 | 2016-09-28T11:20:46Z | 39,746,150 | <p>Since the file iterator object has read the first four lines, when running the second <code>for</code> loop, it starts from where it stopped. The previous iteration stopped at line 3 (assuming we start counting from 0), the next for loop starts at line 4. </p>
<p>Therefore, the <code>enumerate</code> of the second loop should start from <code>x1 + 1</code> not <code>x1</code> as the line with index <code>x1</code> was already covered in the previous loop; last line of first loop:</p>
<pre><code>for linenum, line in enumerate(fd, x1+1):
...
</code></pre>
| 0 | 2016-09-28T11:28:38Z | [
"python"
]
|
Incorrect line number returned on specifying Start parameter in enumerate Python | 39,745,985 | <p>I have slight confusion regarding the start parameter in enumerate function,as i recently started working on python i don't have much idea how it is supposed to work.
Suppose i have an example file below:</p>
<pre><code>Test 1
Test 2
Test 3
</code></pre>
<p>This is the first line <code>[SB WOM]|[INTERNAL REQUEST]|[START]</code> which is the start of message</p>
<pre><code>Name : Vaibhav
Designation : Technical Lead
ID : 123456
Company : Nokia
</code></pre>
<p>This is the sixth line <code>[SB WOM]|[INTERNAL REQUEST]|[END]</code> which is the end of message</p>
<p>Now when i run the below code :</p>
<pre><code>path =("C:/Users/vgupt021/Desktop")
in_file = os.path.join(path,"KSClogs_Test.txt")
fd = open(in_file,'r')
for linenum,line in enumerate(fd) :
if "[SB WOM]|[INTERNAL REQUEST]|[START]" in line:
x1 = linenum
print x1
break
for linenum,line in enumerate(fd,x1):
if "[SB WOM]|[INTERNAL REQUEST]|[END]" in line:
print linenum
break
</code></pre>
<p>I get the linenum returned as 3 and 7, I am not clear why it is not returned as 3,8.Since the index number of line <code>"[SB WOM]|[INTERNAL REQUEST]|[END]"</code> is 8 and not 7, how the start parameter makes the difference in second part of the loop.</p>
| 1 | 2016-09-28T11:20:46Z | 39,746,372 | <p>Try this code</p>
<pre><code>x = range(10)
for i, e in enumerate(x):
if i == 4:
print i
st = i
break
for i, e in enumerate(x, st):
print i
</code></pre>
<p>And you will see this output:</p>
<pre><code>4
4 5 6 7 8 9 10 11 12 13
</code></pre>
<p>So, what does the second parameter of <code>enumerate</code>? Well, it's the starting value of the index of <code>enumerate</code>. The iterable variable <code>x</code> is enumerated again from the beginning but the values of <code>i</code> at different iteration is shifted by the value of <code>st</code>.</p>
<p>Instead of having the values of <code>i</code> as 0, 1, 2, etc., we have 4, 5, 6, etc.</p>
<p>I think that explains why you have the incorrect line number in your code.</p>
| 0 | 2016-09-28T11:38:59Z | [
"python"
]
|
One-to-One relationship SQLAlchemy with multiple files | 39,746,035 | <p>i have a problem with my relationship(...) and i don't understand why.</p>
<p>The error : </p>
<p>"InvalidRequestError: When initializing mapper Mapper|User|users, expression 'BannedUser' failed to locate a name ("name 'BannedUser' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined."</p>
<p>This is the code :</p>
<p>User model</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from .base import Base as BaseModel
class User(BaseModel, declarative_base()):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(16))
password = Column(String(16))
nickname = Column(String(16))
secret_question = Column(String(50))
secret_answer = Column(String(50))
role = Column(Integer)
is_banned = relationship("BannedUser", uselist=False, back_populates='users')
</code></pre>
<p>Banned user model :</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from .base import Base as BaseModel
class BannedUser(BaseModel, declarative_base()):
__tablename__ = 'banned_users'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', back_populates='banned_users')
reason = Column(String)
time_end = Column(DateTime)
</code></pre>
<p>I tried class directly instead of class string but not work too...</p>
<p>I tried 'User.id' instead of 'users.id' same thing...</p>
<p>I don't know what to do :(</p>
<p>Thank u in advance for the help, and sorry for language i'm french ^^</p>
| 0 | 2016-09-28T11:23:01Z | 39,750,778 | <p>On the <code>back_populates</code> (<a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.back_populates" rel="nofollow">doc</a>) you need to specify the property which is related on the other end of the relationship, while you specified the table name ... of the same entity ...</p>
<p>I would recommend doing it with <code>back_ref</code> (<a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.backref" rel="nofollow">doc</a>), which takes care of the other end related property (so you don't need to specify the <code>user</code> property on <code>BannedUser</code>, or the other way around), something like:</p>
<pre><code>...
class User(BaseModel, declarative_base()):
__tablename__ = 'users'
...
is_banned = relationship("BannedUser", uselist=False, back_ref='user')
...
</code></pre>
<p>But if you still want to do it with <code>back_populates</code>, you should do something like this:</p>
<pre><code>...
class User(BaseModel, declarative_base()):
__tablename__ = 'users'
...
is_banned = relationship("BannedUser", uselist=False, back_populates='user')
...
class BannedUser(BaseModel, declarative_base()):
__tablename__ = 'banned_users'
...
user = relationship('User', back_populates='is_banned')
...
</code></pre>
| 0 | 2016-09-28T14:43:41Z | [
"python",
"sqlalchemy",
"foreign-keys",
"relationship"
]
|
merging the time stamps of file if label is the same | 39,746,043 | <p>I have file with three columns, the Ist and 2nd column are the start and end of time while the 3rd is label. I want to merge the time stamps of consecutive rows ( 2 or more) if the label in the 3rd column is the same.</p>
<h1>inputs1:</h1>
<p><code>
0.000000 0.551875 x
0.551875 0.586875 x
0.586875 0.676188 t
0.676188 0.721875 t
0.721875 0.821250 t
0.821250 0.872063 p
0.872063 0.968625 q
0.968625 1.112250 q
</code></p>
<h1>inputs2:</h1>
<p><code>
0.000000 0.551875 x
0.551875 0.586875 x
0.586875 0.676188 t
0.676188 0.721875 t
0.721875 0.821250 t
0.821250 0.872063 p
0.872063 0.968625 q
0.968625 1.112250 q
1.112250 1.212250 x
1.212250 1.500000 x
</code></p>
<h1>inputs3:</h1>
<p><code>
0.000000 0.551875 x
0.551875 0.586875 x
0.586875 0.676188 t
0.676188 0.721875 t
0.721875 0.821250 t
0.821250 0.872063 oo
0.872063 0.968625 q
0.968625 1.112250 q
1.112250 1.212250 x
1.212250 1.500000 x
</code></p>
<h1>output</h1>
<p><code>
0.000000 0.586875 x
0.586875 0.821250 t
0.821250 0.872063 p
0.872063 1.112250 q
1.112250 1.500000 x
</code></p>
| 1 | 2016-09-28T11:23:20Z | 39,751,258 | <p>In Groovy, given:</p>
<pre><code>def inputs = [
[0.000000, 0.551875, 'x'],
[0.551875, 0.586875, 'x'],
[0.586875, 0.676188, 't'],
[0.676188, 0.721875, 't'],
[0.721875, 0.821250, 't'],
[0.821250, 0.872063, 'p'],
[0.872063, 0.968625, 'q'],
[0.968625, 1.112250, 'q']
]
</code></pre>
<p>Just group them by the 3rd element in each list, and then for each group create a list containing;</p>
<ul>
<li>the first item of the first list</li>
<li>the second item of the last list</li>
<li>the key that they were grouped by</li>
</ul>
<p>Giving:</p>
<pre><code>def outputs = inputs.groupBy { it[2] }.collect { key, items ->
[items[0][0], items[-1][1], key]
}
</code></pre>
<p>Which results in:</p>
<pre><code>[[0.000000, 0.586875, 'x'],
[0.586875, 0.821250, 't'],
[0.821250, 0.872063, 'p'],
[0.872063, 1.112250, 'q']]
</code></pre>
<h2>Gaps</h2>
<p>If your inputs can have gaps which you want to maintain, then you could try</p>
<pre><code>def inputs = [[0.000000, 0.551875, 'x'],
[0.551875, 0.586875, 'x'],
[0.586875, 0.676188, 't'],
[0.676188, 0.721875, 't'],
[0.721875, 0.821250, 't'],
[0.821250, 0.872063, 'p'],
[0.872063, 0.968625, 'q'],
[0.968625, 1.112250, 'q'],
[1.112250, 1.551875, 'x'],
[1.551875, 2.000000, 'x']]
def outputs = inputs.inject([]) { accum, line ->
if(accum && accum[-1][2] == line[2]) {
accum[-1][1] = line[1]
}
else {
accum << line
}
accum
}
</code></pre>
<p>To give</p>
<pre><code>[[0.000000, 0.586875, 'x'],
[0.586875, 0.821250, 't'],
[0.821250, 0.872063, 'p'],
[0.872063, 1.112250, 'q'],
[1.112250, 2.000000, 'x']]
</code></pre>
<h2>Wildcards</h2>
<pre><code>def inputs = [[0.000000, 0.551875, 'x'],
[0.551875, 0.586875, 'x'],
[0.586875, 0.676188, 't'],
[0.676188, 0.721875, 't'],
[0.721875, 0.821250, 't'],
[0.821250, 0.872063, 'oo'],
[0.872063, 0.968625, 'q'],
[0.968625, 1.112250, 'q'],
[1.112250, 1.551875, 'x'],
[1.551875, 2.000000, 'x']]
def coalesce(List inputs, String... wildcards) {
inputs.inject([]) { accum, line ->
if(accum &&
(accum[-1][2] == line[2] || wildcards.contains(line[2]))) {
accum[-1][1] = line[1]
}
else {
accum << line
}
accum
}
}
</code></pre>
<p>then;</p>
<pre><code>def outputs = coalesce(inputs, 'oo')
</code></pre>
<p>gives:</p>
<pre><code>[[0.000000, 0.586875, 'x'],
[0.586875, 0.872063, 't'],
[0.872063, 1.112250, 'q'],
[1.112250, 2.000000, 'x']]
</code></pre>
<p>And</p>
<pre><code>def outputs = coalesce(inputs, 'oo', 'q')
</code></pre>
<p>Gives</p>
<pre><code>[[0.000000, 0.586875, 'x'],
[0.586875, 1.112250, 't'],
[1.112250, 2.000000, 'x']]
</code></pre>
| 0 | 2016-09-28T15:04:58Z | [
"java",
"python",
"algorithm",
"groovy"
]
|
How to start Python file (filename.py, which have appeal to oracle ) from sikuli? | 39,746,061 | <p>I tried to import os, then import my module..
[error] ImportError ( No module named filename )</p>
| 0 | 2016-09-28T11:24:17Z | 39,757,098 | <p>If I take your question quite literal, this would do it:</p>
<pre><code>run("C:\Path\To\Python\python.exe C:\Path\To\Script\script.py")
</code></pre>
<p>This would require Python to be installed in <code>C:\Path\To\Python\</code>.</p>
<p>If you want to import the python script this only works if the Python code is supported by Sikuli's Jython interpreter. Instructions on how to proceed are <a href="https://answers.launchpad.net/sikuli/+faq/1114" rel="nofollow">here</a>.</p>
<p>Reference:<br>
<a href="https://answers.launchpad.net/sikuli/+faq/1114" rel="nofollow">https://answers.launchpad.net/sikuli/+faq/1114</a></p>
| 0 | 2016-09-28T20:30:18Z | [
"python",
"oracle",
"jython",
"sikuli"
]
|
I want this function to loop through both lists and return the object that is the same in both | 39,746,115 | <p>These are the lists; note how the second list is made up of objects that need splitting first. </p>
<pre><code>gaps = ['__1__', '__2__', '__3__']
questions = ['Bruce Wayne is __1__', 'Clark Kent is __2__', 'Barry Allen is __3__']
</code></pre>
<p>Here's the code. It seems to work only for the first (zeroth) object, bud that's it - it doesn't even loop.</p>
<pre><code>def is_gap(question, gap):
place = 0
while (place < 3):
question[place] = question[place].split(' ')
for index in gaps:
if index in question[place]:
return index
else:
return None
place += 1
print is_gap(questions, gaps)
</code></pre>
| -5 | 2016-09-28T11:26:34Z | 39,746,208 | <p>Python stops executing as soon as it hits a return statement. If you return inside a loop, it'll stop running after one iteration, when it hits the first return statement.</p>
| 0 | 2016-09-28T11:31:30Z | [
"python",
"list"
]
|
Getting for line in plaintext.split('\n'): UnicodeDecodeError: 'ascii' codec can't decode byte 0x96 in position 2: ordinal not in range(128) | 39,746,190 | <p>I'm going to design sentimental analysis on twitter data using nltk tutorials but not able to run following code</p>
<pre><code>import pickle
import random
import nltk
from nltk import pos_tag
from nltk.classify import ClassifierI
from nltk.classify.scikitlearn import SklearnClassifier
from nltk.tokenize import word_tokenize
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.svm import LinearSVC
from statistics import mode
class VoteClassifier(ClassifierI):
def __init__(self, *classifiers):
self._classifiers = classifiers
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
def confidence(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes)
return conf
short_pos = open("positive.txt", "r").read()
short_neg = open("negative.txt", "r").read()
# move this up here
all_words = []
documents = []
# j is adject, r is adverb, and v is verb
# allowed_word_types = ["J","R","V"]
allowed_word_types = ["J"]
for p in short_pos.split('\n'):
documents.append((p, "pos"))
words = word_tokenize(p)
pos = pos_tag(words)
for w in pos:
if w[1][0] in allowed_word_types:
all_words.append(w[0].lower())
for p in short_neg.split('\n'):
documents.append((p, "neg"))
words = word_tokenize(p)
pos = pos_tag(words)
for w in pos:
if w[1][0] in allowed_word_types:
all_words.append(w[0].lower())
save_documents = open("pickled_algos/documents.pickle", "wb")
pickle.dump(documents, save_documents)
save_documents.close()
all_words = nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:5000]
save_word_features = open("pickled_algos/word_features5k.pickle", "wb")
pickle.dump(word_features, save_word_features)
save_word_features.close()
def find_features(document):
words = word_tokenize(document)
features = {}
for w in word_features:
features[w] = (w in words)
return features
featuresets = [(find_features(rev), category) for (rev, category) in documents]
random.shuffle(featuresets)
print(len(featuresets))
testing_set = featuresets[10000:]
training_set = featuresets[:10000]
classifier = nltk.NaiveBayesClassifier.train(training_set)
print("Original Naive Bayes Algo accuracy percent:", (nltk.classify.accuracy(classifier, testing_set)) * 100)
classifier.show_most_informative_features(15)
###############
save_classifier = open("pickled_algos/originalnaivebayes5k.pickle", "wb")
pickle.dump(classifier, save_classifier)
save_classifier.close()
MNB_classifier = SklearnClassifier(MultinomialNB())
MNB_classifier.train(training_set)
print("MNB_classifier accuracy percent:", (nltk.classify.accuracy(MNB_classifier, testing_set)) * 100)
save_classifier = open("pickled_algos/MNB_classifier5k.pickle", "wb")
pickle.dump(MNB_classifier, save_classifier)
save_classifier.close()
BernoulliNB_classifier = SklearnClassifier(BernoulliNB())
BernoulliNB_classifier.train(training_set)
print("BernoulliNB_classifier accuracy percent:", (nltk.classify.accuracy(BernoulliNB_classifier, testing_set)) * 100)
save_classifier = open("pickled_algos/BernoulliNB_classifier5k.pickle", "wb")
pickle.dump(BernoulliNB_classifier, save_classifier)
save_classifier.close()
LogisticRegression_classifier = SklearnClassifier(LogisticRegression())
LogisticRegression_classifier.train(training_set)
print("LogisticRegression_classifier accuracy percent:",
(nltk.classify.accuracy(LogisticRegression_classifier, testing_set)) * 100)
save_classifier = open("pickled_algos/LogisticRegression_classifier5k.pickle", "wb")
pickle.dump(LogisticRegression_classifier, save_classifier)
save_classifier.close()
LinearSVC_classifier = SklearnClassifier(LinearSVC())
LinearSVC_classifier.train(training_set)
print("LinearSVC_classifier accuracy percent:", (nltk.classify.accuracy(LinearSVC_classifier, testing_set)) * 100)
save_classifier = open("pickled_algos/LinearSVC_classifier5k.pickle", "wb")
pickle.dump(LinearSVC_classifier, save_classifier)
save_classifier.close()
# NuSVC_classifier = SklearnClassifier(NuSVC())
# NuSVC_classifier.train(training_set)
# print("NuSVC_classifier accuracy percent:", (nltk.classify.accuracy(NuSVC_classifier, testing_set))*100)
SGDC_classifier = SklearnClassifier(SGDClassifier())
SGDC_classifier.train(training_set)
print("SGDClassifier accuracy percent:", nltk.classify.accuracy(SGDC_classifier, testing_set) * 100)
save_classifier = open("pickled_algos/SGDC_classifier5k.pickle", "wb")
pickle.dump(SGDC_classifier, save_classifier)
save_classifier.close()
</code></pre>
| -1 | 2016-09-28T11:30:41Z | 39,746,467 | <p>Open the files in text mode with the right encoding, e.g.:</p>
<pre><code>with io.open("positive.txt", "r", encoding="UTF8") as fd:
short_pos = fd.read()
</code></pre>
| 0 | 2016-09-28T11:42:32Z | [
"python",
"python-2.7",
"python-3.x",
"nltk",
"nltk-trainer"
]
|
How to check through the whole user input and not just the first word | 39,746,191 | <p>I try to check through user input but it only checks the first word. Any suggestions of how I can get the program to check through the whole string against a 2D list instead of just checking the first word and outputting missing.
Code below:</p>
<pre><code>my_list = [['noisey','pc','broken']['smashed','window','glass']]
search = input('Enter what is going wrong: ')
notfound = 'True'
for i in mylist[0:1]:
while notfound == 'True':
if search in my_list[0]:
print('Found in Pc')
notfound = 'False'
elif search in my_list[1]:
print('Found in Home.')
notfound = 'False'
else:
print('missing')
notfound = 'False'
</code></pre>
| -2 | 2016-09-28T11:30:43Z | 39,750,756 | <p>This should do the trick</p>
<pre><code>#!/usr/bin/python3
my_list = [['noisey','pc','broken'],['smashed','window','glass']]
search = input('Enter what is going wrong: ')
for word in search.split():
if word in my_list[0]:
print(word,'Found in PC');
elif word in my_list[1]:
print(word,'Found in Home');
else:
print(word,"Not Found");
</code></pre>
<p>Output: </p>
<pre><code>Enter what is going wrong: noisey pc smashed accidentally
noisey Found in PC
pc Found in PC
smashed Found in Home
accidentally Not Found
</code></pre>
| 0 | 2016-09-28T14:42:49Z | [
"python",
"python-3.x"
]
|
python + sqlite: How to use Order by for column with special letters? | 39,746,215 | <p>I want to use <code>order by</code> to sort one of the column. This column, lets say its name is ColA, contains many <strong>special letters</strong>. Here is an example what ColA looks like:</p>
<pre><code>ColA
Abc
D6
(8)
-s
'st
9-57
6s
A&C
5
Ãber
ÑÑÌÑÑкий
W/WO
</code></pre>
<p>I tried with the following codes. </p>
<pre><code>import sqlite3
# Connect
WorkingFile = "C:\\test.db"
con = sqlite3.connect(WorkingFile)
cur = con.cursor()
# Sort data by ColA
cur.execute("SELECT * FROM MyTable ORDER BY ColA ASC;")
print "sorted"
con.commit()
#rename the table:
cur.execute("ALTER TABLE MyTable RENAME TO TempOldTable;")
#Then create the new table with the missing column:
cur.execute('''CREATE TABLE MyTable
(WorkingID INTEGER PRIMARY KEY AUTOINCREMENT,
ColA TEXT,
ColB TEXT,
ColC TEXT);
''')
#And populate it with the old data:
cur.execute('''INSERT INTO MyTable (ColA, ColB, ColC)
SELECT ColA, ColB, ColC
FROM TempOldTable;''')
#Then delete the old table:
cur.execute("DROP TABLE TempOldTable;")
# Finish
con.commit()
cur.close()
</code></pre>
<p>Here I was tring to make a new table, to define ColA to <code>TEXT</code> datatype, and copy the sorted data into it.</p>
<p>But it gives me no change to the database file.</p>
<p>Well, I adimit ColB and ColC contain also such kind of special letters. </p>
<p>But I think the programming idea is not wrong. So what am I doing wrong? Please help me out. Thanks.</p>
| 0 | 2016-09-28T11:31:57Z | 39,747,898 | <p>A SELECT statement does not modify the database.</p>
<p>To reorder the table, you must sort the rows when you actually write the new table:</p>
<pre><code>INSERT INTO MyTable (ColA, ColB, ColC)
SELECT ColA, ColB, ColC
FROM TempOldTable
ORDER BY ColA;
</code></pre>
| 0 | 2016-09-28T12:42:34Z | [
"python",
"sqlite"
]
|
sys.stdin.readline() with if else (Python) | 39,746,223 | <p>I am new at Python and need a little help.
I am trying to use the next command in order to get user input from screen:
sys.stdin.readline()</p>
<p>All is fine when I want to print something but when I am trying to combine an if else statement it seems that the user input is ignoring the case sensitive string that I wrote in the if == and it always return the else even when I writing the input 'Sam'</p>
<p>I want to make a simple task like this one:</p>
<pre><code>print("What is your name ?")
name = sys.stdin.readline()
print("Hello", name)
if name == 'Sam' :
print ('You are in our group')
else :
print('You are not in our group')
</code></pre>
<p>What should I do in the sys.stdin.readline() will acknowledge the if == argument ?</p>
<p>Thank you for you Help</p>
| 0 | 2016-09-28T11:32:16Z | 39,746,273 | <p>The line will include the end of line character <code>'\n'</code> (<a href="https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">docs</a>). So it's never equal to <code>'Sam'</code> (except possibly at the end of the file).</p>
<p>Maybe use <code>name = name.strip()</code> to remove it and any extra whitespace characters.</p>
| 1 | 2016-09-28T11:34:20Z | [
"python"
]
|
python dataframe std deviation of a column/row containing all Nan values except one element | 39,746,316 | <p>I have a python dataframe like this </p>
<pre><code>In [212]: d3
Out[212]:
a b c d e
a 0.0 0.0 0.0 0.0 0.0
b 1.0 1.0 1.0 1.0 1.0
c 2.0 2.0 2.0 2.0 2.0
d 3.0 3.0 3.0 3.0 3.0
e 3.0 4.0 4.0 4.0 4.0
f 5.0 5.0 5.0 5.0 0.0
p NaN 3.0 NaN 3.0 NaN
q NaN 4.0 4.0 4.0 NaN
r NaN 5.0 NaN NaN NaN
</code></pre>
<p>And when I find standard deviation using <code>d3.std(axis=1)</code>, I get SD of row 'r' is <strong>NaN</strong> and I was expecting <strong>0</strong> for the same.</p>
<pre><code>In [213]: d3.std(axis=1)
Out[213]:
a 0.000000
b 0.000000
c 0.000000
d 0.000000
e 0.447214
f 2.236068
p 0.000000
q 0.000000
r NaN
dtype: float64
</code></pre>
<p>When I try the same using numpy's <code>nanstd()</code> function this gives me desired result.</p>
<pre><code>In [225]: np.nanstd(d3.loc['r',:])
Out[225]: 0.0
</code></pre>
<p>But I have a dataframe and I want to use dataframe's std function like this <code>d3['new_col']=np.where(d3.std(axis=1)==0, d3.min(axis=1), np.nan)</code><br>
this results into </p>
<pre><code>In [226]: d3['new_col'] = np.where(d3.std(axis=1)==0, d3.min(axis=1), np.nan)
In [227]: d3
Out[227]:
a b c d e new_col
a 0.0 0.0 0.0 0.0 0.0 0.0
b 1.0 1.0 1.0 1.0 1.0 1.0
c 2.0 2.0 2.0 2.0 2.0 2.0
d 3.0 3.0 3.0 3.0 3.0 3.0
e 3.0 4.0 4.0 4.0 4.0 NaN
f 5.0 5.0 5.0 5.0 0.0 NaN
p NaN 3.0 NaN 3.0 NaN 3.0
q NaN 4.0 4.0 4.0 NaN 4.0
r NaN 5.0 NaN NaN NaN NaN
</code></pre>
<p>I am expecting rightmost bottom most value to be <strong>5.0</strong> not <strong>NaN</strong>.</p>
| 1 | 2016-09-28T11:36:23Z | 39,746,529 | <p>Use arg <code>ddof=0</code> to make <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.std.html" rel="nofollow"><code>df.std</code></a> behave like <code>np.std</code> as it always leaves the last value while calculating standard deviation by default (<em>ddof=1</em>):</p>
<pre><code>df['new_col'] = np.where(df.std(axis=1, ddof=0)==0, df.min(axis=1), np.nan)
</code></pre>
<p><a href="http://i.stack.imgur.com/tY8jr.png" rel="nofollow"><img src="http://i.stack.imgur.com/tY8jr.png" alt="enter image description here"></a></p>
| 0 | 2016-09-28T11:45:08Z | [
"python",
"pandas",
"dataframe",
"standard-deviation"
]
|
Is there a keyboard shortcut in Pycharm for rename a specific variable? | 39,746,405 | <p>I'm using <strong>Pycharm</strong> for Python coding, and I want to change the name of a <strong>specific variable</strong> all over the code. is there any keyboard shortcut for this operation?</p>
<p>In Matlab I can use <em>ctrl</em> + <em>shift</em>.</p>
<p>For example:</p>
<pre><code>old_name=5
x=old_name*123
</code></pre>
<p>will become:</p>
<pre><code>new_name=5
x=new_name*123
</code></pre>
<p>without the need to change both of the <code>old_name</code> references.</p>
<p>Thanks!</p>
| 0 | 2016-09-28T11:40:08Z | 39,746,546 | <p>Highlight your <code>old_name</code> and hit <kbd>Shift</kbd>+<kbd>F6</kbd></p>
| 2 | 2016-09-28T11:45:53Z | [
"python",
"python-2.7",
"keyboard",
"pycharm",
"keyboard-shortcuts"
]
|
Is there a keyboard shortcut in Pycharm for rename a specific variable? | 39,746,405 | <p>I'm using <strong>Pycharm</strong> for Python coding, and I want to change the name of a <strong>specific variable</strong> all over the code. is there any keyboard shortcut for this operation?</p>
<p>In Matlab I can use <em>ctrl</em> + <em>shift</em>.</p>
<p>For example:</p>
<pre><code>old_name=5
x=old_name*123
</code></pre>
<p>will become:</p>
<pre><code>new_name=5
x=new_name*123
</code></pre>
<p>without the need to change both of the <code>old_name</code> references.</p>
<p>Thanks!</p>
| 0 | 2016-09-28T11:40:08Z | 39,746,600 | <p>I don't know about a shortcut for this special purpose, but I simply use <kbd>Ctrl</kbd>+<kbd>R</kbd> to replace the old variable names with new ones. You can also set settings such as <em>Match case</em>, <em>Regex</em> or <em>In selection</em>.</p>
<p>Note that this won't work, if you have a variable name including another variable name:</p>
<pre><code>var1 = 0
var1_s = "0"
</code></pre>
<p>Replacing <code>var1</code> to <code>xy</code> would result in :</p>
<pre><code>xy = 0
xy_s = "0"
</code></pre>
<p>But that also forces you to do consistent and clear variable naming.</p>
| 0 | 2016-09-28T11:48:38Z | [
"python",
"python-2.7",
"keyboard",
"pycharm",
"keyboard-shortcuts"
]
|
connect to ms-sql from python, tried in several ways but no luck | 39,746,411 | <p>I am trying with <code>pyodbc</code> and <code>freetds</code>, but <code>freetds</code> can't be installed. I got an error like:</p>
<pre><code>==> Installing homebrew/versions/freetds091
==> Downloading ftp://ftp.freetds.org/pub/freetds/stable/freetds-0.91.112.tar.gz
curl: (28) Operation timed out after 0 milliseconds with 0 out of 0 bytes received
Error: Failed to download resource "freetds091"
</code></pre>
| 1 | 2016-09-28T11:40:31Z | 39,832,576 | <p>You'll want to edit the formula to replace the ftp address with an http address..</p>
<pre><code>brew edit freetds
</code></pre>
<p>This will open the FreeTDS formula. Replace the line starting with <code>url</code> with:</p>
<pre><code>url "https://fossies.org/linux/privat/freetds-1.00.15.tar.bz2"
</code></pre>
<p>This will also install the latest / greatest 1.00 version; 0.91 is very out of date. Good luck!</p>
| 0 | 2016-10-03T13:15:25Z | [
"python",
"freetds"
]
|
Sense up arrow in Python? | 39,746,463 | <p>I have this script</p>
<pre><code>import sys, os, termios, tty
home = os.path.expanduser("~")
history = []
if os.path.exists(home+"/.incro_repl_history"):
readhist = open(home+"/.incro_repl_history", "r+").readlines()
findex = 0
for j in readhist:
if j[-1] == "\n":
readhist[findex] = j[:-1]
else:
readhist[findex] = j
findex += 1
history = readhist
del readhist, findex
class _Getch:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(3)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
while True:
try:
cur = raw_input("> ")
key = _Getch()
print key
if key == "\x1b[A":
print "\b" * 1000
print history[0]
history.append(cur)
except EOFError:
sys.stdout.write("^D\n")
history.append("^D")
except KeyboardInterrupt:
if not os.path.exists(home+"/.incro_repl_history"):
histfile = open(home+"/.incro_repl_history", "w+")
for i in history:
histfile.write(i+"\n")
else:
os.remove(home+"/.incro_repl_history")
histfile = open(home+"/.incro_repl_history", "w+")
for i in history:
histfile.write(i+"\n")
sys.exit("")
</code></pre>
<p>When run, it get's the contents of <code>/home/bjskistad/.incro_repl_history</code>, reads the lines, and removes the newspace character, and then defines the <code>_Getch</code> class/function. Then, it runs the main loop of the script. It <code>try</code>s to set <code>cur</code> to <code>raw_input()</code>. I then try to sense the up arrow using the <code>_Getch</code> class defined. This is where I am having trouble. I can't sense the up arrow using my <code>_Getch</code> class. How can I sense the up arrow with my current code?</p>
| 0 | 2016-09-28T11:42:28Z | 39,746,654 | <p>The <code>raw_input</code> function always read a string until ENTER, not a single character (arrow, etc.)</p>
<p>You need to define your own <code>getch</code> function, see: <a href="http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user">Python read a single character from the user</a>. </p>
<p>Then you can re-implement your "input" function with a loop using getch` function.</p>
<p>Here is a simple usage:</p>
<pre><code>while True:
char = getch()
if char == '\x03':
raise SystemExit("Bye.")
elif char in '\x00\xe0':
next_char = getch()
print("special: {!r}+{!r}".format(char, next_char))
else:
print("normal: {!r}".format(char))
</code></pre>
<p>Under Windows, with the following keys: <code>Hello<up><down><left><right><ctrl+c></code>, you'll get:</p>
<pre><code>normal: 'H'
normal: 'e'
normal: 'l'
normal: 'l'
normal: 'o'
special: '\xe0'+'H'
special: '\xe0'+'P'
special: '\xe0'+'K'
special: '\xe0'+'M'
</code></pre>
<p>So arrow corresponds to the combining characters: "\xe0H".</p>
| 0 | 2016-09-28T11:51:07Z | [
"python",
"arrow-keys",
"getch"
]
|
How to perform action when QCalendarWidget popup closes? | 39,746,664 | <p>I am using a <code>QDateEdit</code> widget with <code>QDateEdit.setCalendarPopup(True)</code>. I am trying to connect a slot to the event when the calendar popup closes. See my example below for my attempts so far, found in <code>MyCalendarWidget</code>. None of my attempts so far have worked. What can I do to perform an action every time the calendar widget popup closes, <em>not</em> only when the date is changed?</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args):
super(MainWindow,self).__init__(*args)
self._date = QtGui.QDateEdit()
self._date.setCalendarPopup(True)
self._date.setCalendarWidget(MyCalendarWidget())
self.setCentralWidget(self._date)
class App(QtGui.QApplication):
def __init__(self, *args):
super(App,self).__init__(*args)
self.main = MainWindow()
self.connect(self, QtCore.SIGNAL("lastWindowClosed()"), self.byebye )
self.main.show()
def byebye( self ):
self.exit(0)
class MyCalendarWidget(QtGui.QCalendarWidget):
def __init__(self, parent=None):
print("mycal initialized")
super(MyCalendarWidget, self).__init__(parent)
self.installEventFilter(self)
self._many = 2
self._many2 = 2
def focusInEvent(self, event):
print('-'*self._many + 'focus in')
if self._many == 2:
self._many = 4
else:
self._many = 2
super(MyCalendarWidget, self).focusInEvent(event)
def focusOutEvent(self, event):
print('-'*self._many2+'focus out')
if self._many2 == 2:
self._many2 = 4
else:
self._many2 = 2
super(MyCalendarWidget, self).focusOutEvent(event)
def closeEvent(self, event):
print('close')
super(MyCalendarWidget, self).closeEvent(event)
def mouseReleaseEvent(self, event):
print('mouse')
super(MyCalendarWidget, self).mouseReleaseEvent(event)
def main(args):
global app
app = App(args)
app.exec_()
if __name__ == "__main__":
main(sys.argv)
</code></pre>
| 0 | 2016-09-28T11:51:27Z | 39,747,045 | <p>Figured it out - turns out I need to use the <code>clicked</code> signal in <code>QCalendarWidget</code>. This removes the need to sub-class <code>QCalendarWidget</code> as well.</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args):
super(MainWindow,self).__init__(*args)
self._date = QtGui.QDateEdit()
self._date.setCalendarPopup(True)
calendar = self._date.calendarWidget()
calendar.clicked.connect(self._clicked)
self.setCentralWidget(self._date)
def _clicked(self, date):
print('clicked')
class App(QtGui.QApplication):
def __init__(self, *args):
super(App,self).__init__(*args)
self.main = MainWindow()
self.connect(self, QtCore.SIGNAL("lastWindowClosed()"), self.byebye )
self.main.show()
def byebye( self ):
self.exit(0)
def main(args):
global app
app = App(args)
app.exec_()
if __name__ == "__main__":
main(sys.argv)
</code></pre>
| 0 | 2016-09-28T12:08:28Z | [
"python",
"qt",
"qt4",
"pyqt4"
]
|
Python GUI not updating info after program has launched | 39,746,721 | <p>This is what I've written (alot of inspiration from online, since im a student and just started learning python). When I open the program, theres a GUI with one button. When I press the button it displays the time as it should. But if i close the popup window, and press it again, the time is the same as it was last time. In short: I have to re-open the program to display current time (since it does not update with current time after it opens).</p>
<pre><code>import Tkinter as tk
import tkMessageBox
import datetime
ctime = datetime.datetime.now() .strftime("%Y-%m-%d %H:%M:%S")
top = tk.Tk()
def showInfo():
tkMessageBox.showinfo( "Today:", str(ctime))
B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()
</code></pre>
| 1 | 2016-09-28T11:54:04Z | 39,746,909 | <p>Try this:</p>
<pre><code>import Tkinter as tk
import tkMessageBox
import datetime
top = tk.Tk()
def showInfo():
ctime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
tkMessageBox.showinfo( "Today:", str(ctime))
B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()
</code></pre>
<p>put <code>ctime</code> inside the function <code>showInfo</code> to update each time when clicked on the button</p>
| 3 | 2016-09-28T12:02:40Z | [
"python",
"python-3.x",
"user-interface",
"tkinter"
]
|
Python GUI not updating info after program has launched | 39,746,721 | <p>This is what I've written (alot of inspiration from online, since im a student and just started learning python). When I open the program, theres a GUI with one button. When I press the button it displays the time as it should. But if i close the popup window, and press it again, the time is the same as it was last time. In short: I have to re-open the program to display current time (since it does not update with current time after it opens).</p>
<pre><code>import Tkinter as tk
import tkMessageBox
import datetime
ctime = datetime.datetime.now() .strftime("%Y-%m-%d %H:%M:%S")
top = tk.Tk()
def showInfo():
tkMessageBox.showinfo( "Today:", str(ctime))
B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()
</code></pre>
| 1 | 2016-09-28T11:54:04Z | 39,747,057 | <p>You can use a method to get the current time every time you click the button: </p>
<pre><code>import Tkinter as tk
import tkMessageBox
import datetime
def getTime():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
top = tk.Tk()
def showInfo():
tkMessageBox.showinfo( "Today:", getTime())
B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()
</code></pre>
| 2 | 2016-09-28T12:08:50Z | [
"python",
"python-3.x",
"user-interface",
"tkinter"
]
|
How to pass keywords list to pathos.multiprocessing? | 39,746,758 | <p>I am using pathos.multiprocessing to parallelize a program that requires using instance methods. Here is a minimum working example:</p>
<pre><code>import time
import numpy as np
from pathos.multiprocessing import Pool, ProcessingPool, ThreadingPool
class dummy(object):
def __init__(self, arg, key1=None, key2=-11):
np.random.seed(arg)
randnum = np.random.randint(0, 5)
print 'Sleeping {} seconds'.format(randnum)
time.sleep(randnum)
self.value = arg
self.more1 = key1
self.more2 = key2
args = [0, 10, 20, 33, 82]
keys = ['key1', 'key2']
k1val = ['car', 'borg', 'syria', 'aurora', 'libera']
k2val = ['a', 'b', 'c', 'd', 'e']
allks = [dict(zip(keys, [k1val[i], k2val[i]])) for i in range(5)]
pool = ThreadingPool(4)
result = pool.map(dummy, args, k1val, k2val)
print [[r.value, r.more1, r.more2] for r in result]
</code></pre>
<p>The result printed is (as expected):</p>
<pre><code>Sleeping 4 seconds
Sleeping 1 seconds
Sleeping 3 seconds
Sleeping 4 seconds
Sleeping 3 seconds
[[0, 'car', 'a'], [10, 'borg', 'b'], [20, 'syria', 'c'], [33, 'aurora', 'd'], [82, 'libera', 'e']]
</code></pre>
<p>However, in this call to <code>map</code> the order of the last two arguments matters, and if I do:</p>
<pre><code>result2 = pool.map(dummy, args, k2val, k1val)
</code></pre>
<p>I obtain:</p>
<pre><code>[[0, 'a', 'car'], [10, 'b', 'borg'], [20, 'c', 'syria'], [33, 'd', 'aurora'], [82, 'e', 'libera']]
</code></pre>
<p>whereas I would like to obtain the same as the first result. The behaviour would be the same as what <code>apply_async</code> <code>kwds</code> can do in the standard module <code>multiprocessing</code>, i.e. pass a list of dictionaries, where in each dictionary the keys are the keyword names and the items are the keyword arguments (see <code>allks</code>). Notice that the standard module <code>multiprocessing</code> cannot use instance methods, and therefore does not meet even the minimum requirements.</p>
<p>Tentatively this would be:
result = pool.map(dummy, args, kwds=allks) # This does not work</p>
| 1 | 2016-09-28T11:55:59Z | 39,757,488 | <p>I'm the <code>pathos</code> author. Yeah, you hit on something that I have known needs a little work. Currently, the <code>map</code> and <code>pipe</code> (i.e. <code>apply</code>) methods from <code>ProcessPool</code>, <code>ThreadPool</code>, and <code>ParallelPool</code> cannot take <code>kwds</code> -- you have to pass them as <code>args</code>. However, if you use <code>_ProcessPool</code> or <code>_ThreadPool</code>, then you can pass <code>kwds</code> to their <code>map</code> and <code>apply</code> methods.
The pools in <code>pathos.pools</code> that start with an underscore actually come directly from <code>multiprocess</code>, so they have identical APIs to those in <code>multiprocessing</code> (but with better serialization, so can pass class methods etc).</p>
<pre><code>>>> from pathos.pools import _ProcessPool
>>> from multiprocess.pool import Pool
>>> Pool is _ProcessPool
True
</code></pre>
<p>So, for the edits to the original code would look something like this (<strong>from the OP's suggested edit</strong>):</p>
<pre><code>>>> from pathos.pools import _ThreadPool
>>> pool = _ThreadPool(4)
>>>
[â¦]
>>> result = []
>>> def callback(x):
>>> result.append(x)
>>>
>>> for a, k in zip(args, allks):
>>> pool.apply_async(dummy, args=(a,), kwds=k, callback=callback)
>>>
>>> pool.close()
>>> pool.join()
</code></pre>
| 2 | 2016-09-28T20:55:36Z | [
"python",
"dictionary",
"multiprocessing",
"keyword-argument",
"pathos"
]
|
Using Logging with Multiprocessing Module | 39,746,768 | <p>I need to create a single logger that can be used throughout my python package, but some of the functions implement multiprocessing. I want all those functions to write to the same log file just like everything else.</p>
<p>I know at Python 3.2+ there is a built in way to do this, but I need to back port to Python 2.7.x as well.</p>
<p>Is there any code out there that works well with both multiprocessing and non-multiprocessing functions for logging?</p>
<p>Normally, I would create a log as such:</p>
<pre><code>module = sys.modules['__main__'].__file__
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG,
format='%(name)s (%(levelname)s): %(message)s')
log = logging.getLogger(module)
fh = RotatingFileHandler(arguments.o, mode='a', maxBytes=2*1024*1024,
backupCount=2, encoding=None, delay=0)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - % (message)s')
fh.setFormatter(formatter)
fh.setLevel(logging.DEBUG)
log.addHandler(fh)
</code></pre>
<p>Then the output would write to a single file. It works great, but when I implement this, this code will create multiple files, which I do not want.</p>
<p>Any ideas?</p>
<p>Thank you</p>
| 1 | 2016-09-28T11:56:33Z | 39,759,109 | <p>The functionality to do this in Python >= 3.2 (via the <code>QueueHandler</code> and <code>QueueListener</code> classes, as described <a href="http://plumberjack.blogspot.co.uk/2010/09/using-logging-with-multiprocessing.html" rel="nofollow">here</a>) is available for Python 2.7 through the <a href="https://pypi.python.org/pypi/logutils" rel="nofollow"><code>logutils</code></a> project.</p>
| 0 | 2016-09-28T23:24:36Z | [
"python",
"python-2.7",
"logging"
]
|
Response streamed [200 OK]> is not JSON serializable stream image python | 39,746,893 | <p>I am looking for a way to serve some images from the bing map without sharing the URL (because it contains the secret key) and return it to the client (without saving to disk first). I'm using this method from <a href="http://flask.pocoo.org/snippets/118/" rel="nofollow">here</a></p>
<pre><code>def get_stream_from_url(url):
req = requests.get(url, stream = True)
return Response(stream_with_context(req.iter_content()), content_type = req.headers['content-type'])
</code></pre>
<p>I use it in another method, where I generate a list with those info for those image, so basically I wan to put the sream response inside the json as a value of key <code>url</code>: </p>
<pre><code> def images_data_and_url(self, data):
results = []
for i in range(1, 13):
image = {}
description = data['description']
url = self.get_stream_from_url(data['url'])
tile = {"description": description
"url": url}
results.append(image)
print results
return json.dumps(results)
</code></pre>
<p>EDIT:
If I print the results I have this:</p>
<pre><code><type 'list'>: [{'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>} , {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>},{'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}]
</code></pre>
<p>If I do like this I get this error </p>
<pre><code><Response streamed [200 OK]> is not JSON serializable
</code></pre>
<p>This because of the function <code>get_stream_from_url</code> returns a response :/ My problem is that I don't know how to send it in another way? </p>
<p>In HTML I get the data and assign per the data for each image like this:</p>
<pre><code><img class="image1 " data-description="The description" src="">
</code></pre>
<p>Can somebody help me, how to encode the stream so I can send it as with the JSON data?</p>
| 0 | 2016-09-28T12:01:44Z | 39,748,980 | <p><code>Flask</code> is overkill for this. I've created a library called <code>wsinfo</code>, which is available here: <a href="https://github.com/linusg/wsinfo" rel="nofollow">https://github.com/linusg/wsinfo</a>.</p>
<p>With it, the code is as simple as:</p>
<pre><code>import base64
import wsinfo
import sys
def html_image(data, content_type):
if sys.version.startswith("3"):
from io import BytesIO
f = BytesIO(data.encode())
else:
from StringIO import StringIO
f = StringIO(data)
encoded = base64.b64encode(f.read())
return "data:{};base64,{}".format(content_type, encoded)
url = "http://t0.tiles.virtualearth.net/tiles/a1210223003.jpeg?g=854&mkt=en-US"
w = wsinfo.Info(url)
img = html_image(w.content, w.content_type)
with open("out.html", "w") as html:
html.write('<img class="image1" data-description="The description" src="{}" />'.format(img))
</code></pre>
<p>The code runs with both Python 2 and 3, and results in an HTML file called <code>out.html</code>, where the image is embedded.</p>
| 1 | 2016-09-28T13:29:11Z | [
"python",
"json",
"python-2.7",
"bing-maps",
"bing"
]
|
Response streamed [200 OK]> is not JSON serializable stream image python | 39,746,893 | <p>I am looking for a way to serve some images from the bing map without sharing the URL (because it contains the secret key) and return it to the client (without saving to disk first). I'm using this method from <a href="http://flask.pocoo.org/snippets/118/" rel="nofollow">here</a></p>
<pre><code>def get_stream_from_url(url):
req = requests.get(url, stream = True)
return Response(stream_with_context(req.iter_content()), content_type = req.headers['content-type'])
</code></pre>
<p>I use it in another method, where I generate a list with those info for those image, so basically I wan to put the sream response inside the json as a value of key <code>url</code>: </p>
<pre><code> def images_data_and_url(self, data):
results = []
for i in range(1, 13):
image = {}
description = data['description']
url = self.get_stream_from_url(data['url'])
tile = {"description": description
"url": url}
results.append(image)
print results
return json.dumps(results)
</code></pre>
<p>EDIT:
If I print the results I have this:</p>
<pre><code><type 'list'>: [{'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>} , {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>},{'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}, {'description': ' this is an example', 'url': <Response streamed [200 OK]>}]
</code></pre>
<p>If I do like this I get this error </p>
<pre><code><Response streamed [200 OK]> is not JSON serializable
</code></pre>
<p>This because of the function <code>get_stream_from_url</code> returns a response :/ My problem is that I don't know how to send it in another way? </p>
<p>In HTML I get the data and assign per the data for each image like this:</p>
<pre><code><img class="image1 " data-description="The description" src="">
</code></pre>
<p>Can somebody help me, how to encode the stream so I can send it as with the JSON data?</p>
| 0 | 2016-09-28T12:01:44Z | 39,775,897 | <p>There is no need to hide a Bing Maps key. Anyone can create on and use it under the free terms of use. As such there is little incentive for them to steal your key. In majority of cases where a key appeared to be stolen, the root cause was code being handed off that contained the key or the key being posted in code samples in forum posts. The user of the key usually were unaware of the key in the code. The Bing Maps team is able to track these situations and resolve them as needed. That said it rarely occurs. Generally, when someone wants to steal a Bing Maps key, they just use the key from the Bing Maps website.</p>
| 0 | 2016-09-29T16:49:37Z | [
"python",
"json",
"python-2.7",
"bing-maps",
"bing"
]
|
Control-C not stopping thread/spinning cursor | 39,746,897 | <p>I have code that copies files. When it is doing so a cursor spins. This all works fine. However if I use <kbd>Ctrl</kbd>+<kbd>C</kbd> to stop the copy I expect the <code>KeyboardInterrupt</code> to set the event and the cursor to stop spinning. The copy stops however the cursor spins forever, why is this?</p>
<p>I tried putting a print into the Interrupt and that did not get displayed, so it seems it is not being called?</p>
<pre><code>def spinning_cursor(event):
for j in itertools.cycle('/-\|'):
if not event.is_set():
sys.stdout.write(j)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\b')
else:
return
def copy_file(sfile, dfile, sync):
processing_flag = Event()
Thread(target = spinning_cursor, kwargs = {'event': processing_flag}).start()
if os.path.exists(sfile):
try:
shutil.copyfile(sfile, dfile)
processing_flag.set()
except KeyboardInterrupt:
processing_flag.set()
pass
...
</code></pre>
| 0 | 2016-09-28T12:01:51Z | 39,750,980 | <p>It is not really an answer, because I cannot explain what really happens, but I could partially reproduce. It looks like <code>copy_file</code> <em>swallows</em> the KeyboardInterrupt and raises another exception. If that happens, as the <code>processing_flag.set()</code> is only in the normal and <code>except KeyboardInterrupt</code> branches, control never passes there. As a consequence, the Event is never set and the child thread keeps on spinning (that's what I did to reproduce the behaviour...)</p>
<h3>Workarounds.</h3>
<p>I could find 2 possible workarounds</p>
<ul>
<li><p>use <code>except</code> without any filtering:</p>
<pre><code>try:
shutil.copyfile(sfile, dfile)
processing_flag.set()
except:
processing_flag.set()
pass
</code></pre>
<p>that should be enough to catch any possible exception raised by <code>copyfile</code></p></li>
<li><p>use a <code>finally</code> block. I personally prefere that way, because it is really what <code>finally</code> is aimed to: execute that branch whatever could happen. In that case, you could even remove the <code>except</code> block and have just a <code>try:... finally:...</code>:</p>
<pre><code>try:
shutil.copyfile(sfile, dfile)
finally:
processing_flag.set()
</code></pre></li>
</ul>
| 1 | 2016-09-28T14:52:09Z | [
"python",
"multithreading"
]
|
Egg_info error when installing rpy2 windows 10 | 39,746,961 | <p>I want to install <code>rpy2</code> and next install <code>anaconda</code> with <code>spyder</code> to use python. </p>
<p>I tried this command</p>
<pre><code>py -m pip install rpy2
</code></pre>
<p>but it gave me this error</p>
<pre><code>Command "python setup.py egg_info" failed with error code 1 in C:\Users\Robert\AppData\Local\Temp\pip-build-o27u4aog\rpy2\
</code></pre>
<p>I tried to install <code>unroll</code> as well with similar pip command and it gave me similar error </p>
<pre><code>Command "python setup.py egg_info" failed with error code 1 in C:\Users\Robert\AppData\Local\Temp\pip-build-nyfqo09i\uroll\
</code></pre>
<p>Like suggested for example <a href="http://stackoverflow.com/questions/17886647/cant-install-via-pip-because-of-egg-info-error">here</a> I succesfully did</p>
<pre><code>py -m pip install --upgrade setuptools
</code></pre>
<p>and</p>
<pre><code>py -m pip install ez_setup
</code></pre>
<p>but nothing helped. I had to unistall <code>anaconda</code> to <code>--upgrade setuptools</code> looking foward to install <code>rpy2</code> but now I dont know what to do more.</p>
<p>I am using windows 10, <code>R 3.2.5</code> and <code>python 3.5.</code></p>
<p>Any suggestions?</p>
| 0 | 2016-09-28T12:04:28Z | 39,796,785 | <p>Use precompiled binaries.</p>
<p>See: <a href="http://rpy2.readthedocs.io/en/default/overview.html#microsoft-s-windows-precompiled-binaries" rel="nofollow">http://rpy2.readthedocs.io/en/default/overview.html#microsoft-s-windows-precompiled-binaries</a></p>
<p>The main page for rpy2 will be updated to indicate that <code>pip install</code> is not the easiest way to install rpy2 on Windows. </p>
| 0 | 2016-09-30T17:18:28Z | [
"python",
"rpy2"
]
|
CSV split rows into lists | 39,747,047 | <p>So i would like to split string from list into multiple lists
like rows[1] should be splited into another list contained in list m
i saw this here and it hsould be accesable m[0][0] to get first item form first list .
import csv</p>
<pre><code>reader = csv.reader(open("alerts.csv"), delimiter=',')
)
rows=[]
for row in reader:
rows.append(row)
num_lists=int(len(rows))
lists=[]
m=[]
for x in rows:
m.append(x.split(';')[0])
</code></pre>
<p>printing rows: </p>
<pre><code>[['priority;status;time;object_class;host;app;inc;tool;msg'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;call'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;msg'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;msg']]
</code></pre>
<p>and output should look like
m[0][0] should return pririty </p>
| 0 | 2016-09-28T12:08:32Z | 39,747,197 | <p>you can do this pretty easily with pandas</p>
<pre><code>import pandas as pd
A = pd.read_csv('yourfile.csv')
for x in A.values:
for y in x:
print y
</code></pre>
<p>so the 'print y' statement access each element in the row. but I mean, after the "for x in A.values" you can do just about anything</p>
| 1 | 2016-09-28T12:13:23Z | [
"python",
"list",
"csv"
]
|
CSV split rows into lists | 39,747,047 | <p>So i would like to split string from list into multiple lists
like rows[1] should be splited into another list contained in list m
i saw this here and it hsould be accesable m[0][0] to get first item form first list .
import csv</p>
<pre><code>reader = csv.reader(open("alerts.csv"), delimiter=',')
)
rows=[]
for row in reader:
rows.append(row)
num_lists=int(len(rows))
lists=[]
m=[]
for x in rows:
m.append(x.split(';')[0])
</code></pre>
<p>printing rows: </p>
<pre><code>[['priority;status;time;object_class;host;app;inc;tool;msg'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;call'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;msg'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;msg']]
</code></pre>
<p>and output should look like
m[0][0] should return pririty </p>
| 0 | 2016-09-28T12:08:32Z | 39,747,430 | <p>Exact solution to your question; you almost got it right (note the <code>delimiter</code> value):</p>
<pre><code>reader = csv.reader(open("alerts.csv"), delimiter=';')
table = [row for row in reader]
print(table[0][0])
>>> priority
</code></pre>
<p>For easy data handling, it is often nice to explicitly extract the header like so:</p>
<pre><code>reader = csv.reader(open("alerts.csv"), delimiter=';')
header = reader.next()
table = [row for row in reader]
print(header[0])
print(table[0][0])
>>> priority
>>> P2
</code></pre>
| 0 | 2016-09-28T12:24:07Z | [
"python",
"list",
"csv"
]
|
CSV split rows into lists | 39,747,047 | <p>So i would like to split string from list into multiple lists
like rows[1] should be splited into another list contained in list m
i saw this here and it hsould be accesable m[0][0] to get first item form first list .
import csv</p>
<pre><code>reader = csv.reader(open("alerts.csv"), delimiter=',')
)
rows=[]
for row in reader:
rows.append(row)
num_lists=int(len(rows))
lists=[]
m=[]
for x in rows:
m.append(x.split(';')[0])
</code></pre>
<p>printing rows: </p>
<pre><code>[['priority;status;time;object_class;host;app;inc;tool;msg'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;call'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;msg'], ['P2;CLOSED;24-09-2016 20:06:41;nm;prod;;390949;HPNNM;msg']]
</code></pre>
<p>and output should look like
m[0][0] should return pririty </p>
| 0 | 2016-09-28T12:08:32Z | 39,747,476 | <p>Here's how to do it:</p>
<pre><code>import csv
with open('alerts.csv') as f:
reader = csv.reader(f, delimiter=';')
next(reader) # skip over the first header row
rows = [row for row in reader]
>>> print(rows[0][0])
P2
</code></pre>
<p>This uses a list comprehension to read all rows from the CSV file into a list. The delimiter should be a semi-colon, not a comma; so use <code>delimiter=';'</code>. Also the first row is a header and is therefore skipped.</p>
| 0 | 2016-09-28T12:25:52Z | [
"python",
"list",
"csv"
]
|
Looping through an 8-byte hex code in python | 39,747,141 | <p>I have an 8-byte hex code and i'm trying to loop through 00-FF for each byte starting from the last to the first but i'm new to python and i'm stuck. </p>
<p>here's the code for looping through 00-FF:</p>
<pre><code>for h in range(0, 256):
return "{:02x}".format(h)
</code></pre>
<p>Essentially what i have is a </p>
<pre><code>hexcode = 'f20bdba6ff29eed7'
</code></pre>
<p>EDIT: I'm going to add a little background information on this and remove my previous explanation. I'm writing a Padding Attack aglorithm with DES. Here's what needs to happen:</p>
<pre><code>hexcode = 'f20bdba6ff29eed7'
for i in range(0,8):
(FOR i = 0 ) Loop through 00-FF for the last byte (i.e. 'd7') until you find the value that works
(FOR i = 1 ) Loop through 00-FF for the 7th byte (i.e. 'ee') until you find the value that works
and so on until the 1st byte
</code></pre>
<p>MY PROBLEM: my problem is that i dont know how to loop through all 8 bytes of the hex. This is easy when it's the 8th byte, because i just remove the last two elements and loop through 00-FF and add it back to hex to see if its the correct code. Essentially what the code does is :</p>
<pre><code>remove last two elements of hex
try 00 as the last two elements
if the test returns true then stop
if it doesn't move to 01 (cont. through FF, but stop when you find the correct value)
</code></pre>
<p>My issue is, when its the bytes in the middle (2-7) how do i loop for a middle value and then add it all back together. Essentially</p>
<pre><code>For byte 7:
Remove elements 13,14 from hex
try 00 as element 13,14
add hex[0:12] + 00 + hex [15:16]
if 00 returns true then stop, if not then loop through 01-ff until it does
</code></pre>
<p>and so on for bytes 6,5,4,3,2,1</p>
| 1 | 2016-09-28T12:11:15Z | 39,752,707 | <p>Here's a quick way to break a string into chunks. We assume it has even length.</p>
<pre><code>hexcode = 'f20bdba6ff29eed7'
l = len(hexcode)
for n in range(0, len(hexcode)/2):
index = n * 2
print hexcode[index:index+2]
</code></pre>
<p>If you need to operate on the string representations, you could easily generate a list of two character bytecodes using something similar to this. Personally, I prefer to operate on the bytes, and use the hexcodes only for IO.</p>
<pre><code>[hexcode[n*2:n*2+2] for n in range(len(hexcode)/2)]
</code></pre>
| 0 | 2016-09-28T16:13:48Z | [
"python",
"loops",
"hex"
]
|
Why does tensorlow LSTM takes only the hidden size as input? | 39,747,170 | <p>In the tensorflow <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/rnn_cell.html#LSTMCell" rel="nofollow">LSTM</a> cell we only initialize it by number of units (<code>num_units</code>) which is the hidden size of the cell. However, the cell should also take an input <code>x</code>. And since the underlying operation is a matrix multiplication operation the size of <code>x</code> should also play a role in setting up the LSTM weight. So, shouldn't the cell take the size of the input <code>x</code> also as an initialization parameter? </p>
| 0 | 2016-09-28T12:12:12Z | 39,747,366 | <p>LSTM cell (or other types of RNN cells) is just an object you pass to the function such as <code>tf.nn.rnn</code>. <code>tf.nn.rnn</code> takes cell and data for input. Cell is called inside of rnn function with the data you've passed to <code>tf.nn.rnn</code>. </p>
| 1 | 2016-09-28T12:21:21Z | [
"python",
"tensorflow",
"lstm"
]
|
Add column to dataframe based on date column range | 39,747,222 | <p>I have a <code>df</code> containing <code>n</code> <code>columns</code>. One of these is a <code>column</code> named <code>date</code> which contains values formatted as <code>mm-dd-yy</code>. Now I want to add a <code>column</code> <code>interval</code> to my <code>df</code>. This <code>column</code> should return the <code>year</code> contained in <code>date</code> but also if it's <code>H1</code> or <code>H2</code>. <code>H1</code> is half year one and should be all <code>date</code> values between <code>01-dd-yy</code> <code>06-dd-yy</code> and thus <code>H2</code> should be all <code>date</code> values between <code>07-dd-yy</code> and <code>12-dd-yy</code>.</p>
<p>This is an example of the data in <code>df['date']</code>:</p>
<pre><code>0 01-27-16
1 02-27-16
2 03-27-16
3 04-27-16
4 05-27-16
5 06-27-16
6 07-27-16
7 08-24-16
8 09-24-16
9 10-16-15
...etc...
</code></pre>
<p>In <code>df</code> I want to add another column named <code>interval</code> containing:</p>
<pre><code> 0 16H1
1 16H1
2 16H1
3 16H1
4 16H1
5 16H1
6 16H2
7 16H2
8 16H2
9 15H2
...etc...
</code></pre>
<p>So I thought I'd create a <code>function</code> and then use <code>map</code>.</p>
<pre><code>def is_in_range(x):
if x['date'] >= '01-01-16' x['date'] <= '06-31-16':
print '16H1'
elif x['date'] >= '07-01-16' and x['date'] <= '12-31-16':
print '16H2'
elif x['date'] >= '01-01-15' and x['date'] <= '06-31-15':
print '15H1'
elif x['date'] >= '07-01-15' and x['date'] <= '12-31-15':
print '15H2'
...etc...
</code></pre>
<p>I call the function like this:</p>
<pre><code>df.groupby(df['date'].map(is_in_range))
</code></pre>
<p>Now this gives me:</p>
<blockquote>
<p>`TypeError: 'Timestamp' object has no attribute '<strong>getitem</strong>'</p>
</blockquote>
<p>to begin with. I'm not sure why, but either way there surely must be a better way?</p>
| 1 | 2016-09-28T12:14:22Z | 39,747,412 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.quarter.html" rel="nofollow"><code>dt.quarter</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.month.html" rel="nofollow"><code>dt.month</code></a>.</p>
<p>First convert <code>int</code> year value to <code>str</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>, then select last <code>2</code> chars. Last use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with condition:</p>
<pre><code>#first convert to datetime if not datetime
df.date = pd.to_datetime(df.date)
df['interval'] = df.date.astype(str).str[2:4] + np.where(df.date.dt.month < 7, 'H1','H2')
print (df)
date interval
0 2016-01-27 16H1
1 2016-02-27 16H1
2 2016-03-27 16H1
3 2016-04-27 16H1
4 2016-05-27 16H1
5 2016-06-27 16H1
6 2016-07-27 16H2
7 2016-08-24 16H2
8 2016-09-24 16H2
9 2015-10-16 15H2
</code></pre>
<p>Or:</p>
<pre><code>df['interval'] = df.date.astype(str).str[2:4] + np.where(df.date.dt.quarter < 3,'H1','H2')
print (df)
date interval
0 2016-01-27 16H1
1 2016-02-27 16H1
2 2016-03-27 16H1
3 2016-04-27 16H1
4 2016-05-27 16H1
5 2016-06-27 16H1
6 2016-07-27 16H2
7 2016-08-24 16H2
8 2016-09-24 16H2
9 2015-10-16 15H2
</code></pre>
<p><code>string</code> solution:</p>
<pre><code>df['interval'] = df.date.str[6:] + np.where(df.date.str[:2].astype(int) < 7, 'H1','H2')
print (df)
date interval
0 01-27-16 16H1
1 02-27-16 16H1
2 03-27-16 16H1
3 04-27-16 16H1
4 05-27-16 16H1
5 06-27-16 16H1
6 07-27-16 16H2
7 08-24-16 16H2
8 09-24-16 16H2
9 10-16-15 15H2
</code></pre>
<p>List comprehension solutions work if not <strong>NaN</strong>:</p>
<p><code>string</code> column:</p>
<pre><code>df['interval'] = [x[6:] + 'H1' if int(x[:2])< 7 else x[6:] + 'H2' for x in df['date']]
</code></pre>
<p><code>datetime</code> column:</p>
<pre><code>#first convert to datetime if not datetime
df.date = pd.to_datetime(df.date)
df['interval'] = [x[2:4] + 'H1' if int(x[5:7])< 7 else x[2:4] + 'H2' for x in df['date'].astype(str)]
print (df)
date interval
0 01-27-16 16H1
1 02-27-16 16H1
2 03-27-16 16H1
3 04-27-16 16H1
4 05-27-16 16H1
5 06-27-16 16H1
6 07-27-16 16H2
7 08-24-16 16H2
8 09-24-16 16H2
9 10-16-15 15H2
</code></pre>
| 1 | 2016-09-28T12:23:21Z | [
"python",
"date",
"datetime",
"pandas",
"time-series"
]
|
Add column to dataframe based on date column range | 39,747,222 | <p>I have a <code>df</code> containing <code>n</code> <code>columns</code>. One of these is a <code>column</code> named <code>date</code> which contains values formatted as <code>mm-dd-yy</code>. Now I want to add a <code>column</code> <code>interval</code> to my <code>df</code>. This <code>column</code> should return the <code>year</code> contained in <code>date</code> but also if it's <code>H1</code> or <code>H2</code>. <code>H1</code> is half year one and should be all <code>date</code> values between <code>01-dd-yy</code> <code>06-dd-yy</code> and thus <code>H2</code> should be all <code>date</code> values between <code>07-dd-yy</code> and <code>12-dd-yy</code>.</p>
<p>This is an example of the data in <code>df['date']</code>:</p>
<pre><code>0 01-27-16
1 02-27-16
2 03-27-16
3 04-27-16
4 05-27-16
5 06-27-16
6 07-27-16
7 08-24-16
8 09-24-16
9 10-16-15
...etc...
</code></pre>
<p>In <code>df</code> I want to add another column named <code>interval</code> containing:</p>
<pre><code> 0 16H1
1 16H1
2 16H1
3 16H1
4 16H1
5 16H1
6 16H2
7 16H2
8 16H2
9 15H2
...etc...
</code></pre>
<p>So I thought I'd create a <code>function</code> and then use <code>map</code>.</p>
<pre><code>def is_in_range(x):
if x['date'] >= '01-01-16' x['date'] <= '06-31-16':
print '16H1'
elif x['date'] >= '07-01-16' and x['date'] <= '12-31-16':
print '16H2'
elif x['date'] >= '01-01-15' and x['date'] <= '06-31-15':
print '15H1'
elif x['date'] >= '07-01-15' and x['date'] <= '12-31-15':
print '15H2'
...etc...
</code></pre>
<p>I call the function like this:</p>
<pre><code>df.groupby(df['date'].map(is_in_range))
</code></pre>
<p>Now this gives me:</p>
<blockquote>
<p>`TypeError: 'Timestamp' object has no attribute '<strong>getitem</strong>'</p>
</blockquote>
<p>to begin with. I'm not sure why, but either way there surely must be a better way?</p>
| 1 | 2016-09-28T12:14:22Z | 39,747,419 | <p>is the 'date' column a string? you can't really compare strings like that</p>
<p>convert the last two elements in the string to an int</p>
<pre><code>A = [x[6:]+'H1' if int(x[6:]+)< 7 else 'H2' for x in df['date'].values]
</code></pre>
<p>and finally</p>
<pre><code>df['interval'] = A
</code></pre>
| 1 | 2016-09-28T12:23:29Z | [
"python",
"date",
"datetime",
"pandas",
"time-series"
]
|
for-loop over tuple in Python: ValueError | 39,747,305 | <p>I have a tuple of arrays like the following:</p>
<pre><code>z = (array( [ [1], [2], [3]] ),
array( [[10],[11],[12]] )
)
</code></pre>
<p>I want to iterate over them with a simple for loop using two variables:</p>
<pre><code>for x, y in z:
print("it worked")
self.doStuff(x, y)
</code></pre>
<p>... but it throws the error:</p>
<pre><code>ValueError: too many values to unpack (expected 2)
</code></pre>
<p>I have googled this error. Many seem to suggest the .split() method or .items(). I'm not really sure, where to add those, since the don't belong to tuples. How can I execute this for-loop properly? Thanks for your help.</p>
| 1 | 2016-09-28T12:18:17Z | 39,747,395 | <p>The line </p>
<pre><code>for x, y in z:
</code></pre>
<p>assumes (at least in Python2.7), that each element in <code>z</code> can be <a href="https://www.python.org/dev/peps/pep-3113/" rel="nofollow">tuple unpacked</a>. This would be the case if each element in <code>z</code> is, say, a pair tuple:</p>
<pre><code>In [23]: for x, y in [(1, 2), (3, 4)]:
...: pass
...:
</code></pre>
<p>For your case, could it be that you simply want</p>
<pre><code>x, y = z
</code></pre>
<p>?</p>
<p>This works by me:</p>
<pre><code>In [19]: z = (array( [ [1], [2], [3]] ),
...: array( [[10],[11],[12]] )
...: )
In [20]: x, y = z
In [21]: x
Out[21]:
array([[1],
[2],
[3]])
In [22]: y
Out[22]:
array([[10],
[11],
[12]])
</code></pre>
| 2 | 2016-09-28T12:22:28Z | [
"python",
"for-loop"
]
|
for-loop over tuple in Python: ValueError | 39,747,305 | <p>I have a tuple of arrays like the following:</p>
<pre><code>z = (array( [ [1], [2], [3]] ),
array( [[10],[11],[12]] )
)
</code></pre>
<p>I want to iterate over them with a simple for loop using two variables:</p>
<pre><code>for x, y in z:
print("it worked")
self.doStuff(x, y)
</code></pre>
<p>... but it throws the error:</p>
<pre><code>ValueError: too many values to unpack (expected 2)
</code></pre>
<p>I have googled this error. Many seem to suggest the .split() method or .items(). I'm not really sure, where to add those, since the don't belong to tuples. How can I execute this for-loop properly? Thanks for your help.</p>
| 1 | 2016-09-28T12:18:17Z | 39,747,424 | <p>Reading the other answer it might be that I misunderstood what you want. </p>
<p>You can also use</p>
<pre><code>for x,y in zip(*z):
</code></pre>
<p>to unzip the z tuple.</p>
<p>The output then is:</p>
<pre><code>it worked
[1] [10]
it worked
[2] [11]
it worked
[3] [12]
</code></pre>
| 2 | 2016-09-28T12:23:41Z | [
"python",
"for-loop"
]
|
Can I use PyCharm windows with VirtualBox ubuntu | 39,747,344 | <p>Can I use PyCharm (non-professional version) to develop code in windows and SSH or integrate virtualbox into PyCharm so it can send to my host in virtualbox Ubuntu server? </p>
| -2 | 2016-09-28T12:20:10Z | 39,747,441 | <p>Yes you can. Share you code folder from windows using Vagrant or your virtual box into ubuntu and edit the code from pycharm windows. You can even debug code from ubuntu using pycharm. I have done this for months with Vagrant VMs.</p>
| 0 | 2016-09-28T12:24:31Z | [
"python",
"ssh",
"pycharm",
"virtualbox"
]
|
How to change map into a loop? | 39,747,403 | <p>this question is probably really simple but it will help me to understand the difference between loop and map.
In the first example I managed to change it from:</p>
<pre><code> nrs = list(map(lambda x: int( open("img_" + str(x) + ".csv").readline().split(",")[1] ) , range(82))
</code></pre>
<p>to:</p>
<pre><code> nrs = []
for x in range(82):
nrs.append(int( open("img_" + str(x) + ".csv").readline().split(",")[1] ))
</code></pre>
<p>but how can I change:</p>
<pre><code> plt.plot(list(map(lambda x: ages[x], list(avg_si.keys() ))), list(avg_si.values()), 'ro', label='size')
</code></pre>
<p>into a loop?
I tried with:</p>
<pre><code>srednia = []
for x in list(avg_si.values()):
srednia.append(ages[x], list(avg_si.keys()))
plt.plot(srednia, "ro", label = "size")
</code></pre>
<p>But I get a KeyError </p>
| 1 | 2016-09-28T12:22:59Z | 39,747,639 | <p>You should iterate over keys, not values.</p>
<pre><code> srednia = []
for x in list(avg_si.keys()):
srednia.append(ages[x], list(avg_si.values()))
plt.plot(srednia, "ro", label = "size")
</code></pre>
| 0 | 2016-09-28T12:31:53Z | [
"python"
]
|
How to change map into a loop? | 39,747,403 | <p>this question is probably really simple but it will help me to understand the difference between loop and map.
In the first example I managed to change it from:</p>
<pre><code> nrs = list(map(lambda x: int( open("img_" + str(x) + ".csv").readline().split(",")[1] ) , range(82))
</code></pre>
<p>to:</p>
<pre><code> nrs = []
for x in range(82):
nrs.append(int( open("img_" + str(x) + ".csv").readline().split(",")[1] ))
</code></pre>
<p>but how can I change:</p>
<pre><code> plt.plot(list(map(lambda x: ages[x], list(avg_si.keys() ))), list(avg_si.values()), 'ro', label='size')
</code></pre>
<p>into a loop?
I tried with:</p>
<pre><code>srednia = []
for x in list(avg_si.values()):
srednia.append(ages[x], list(avg_si.keys()))
plt.plot(srednia, "ro", label = "size")
</code></pre>
<p>But I get a KeyError </p>
| 1 | 2016-09-28T12:22:59Z | 39,750,281 | <p>The expression</p>
<pre><code>plt.plot(list(map(lambda x: ages[x], list(avg_si.keys() ))), list(avg_si.values()), 'ro', label='size')
</code></pre>
<p>is somewhat hard to parse. In addition to the last two string arguments you are passing it two lists:</p>
<pre><code>1) list(map(lambda x: ages[x], list(avg_si.keys() )))
2) list(avg_si.values())
</code></pre>
<p>The second list requires no comment. The first one is the <code>map</code> expression. It is equivalent to the following list comprehension:</p>
<pre><code>[ages[x] for x in avg_si.keys()]
</code></pre>
<p>Which would make the entire line equivalent to</p>
<pre><code>plt.plot([ages[x] for x in avg_si.keys()], list(avg_si.values()), 'ro', label='size')
</code></pre>
<p>If you wanted to replace the comprehension by a loop you could do:</p>
<pre><code>ageList = []
for x in avg_si.keys():
ageList.append(ages[x])
</code></pre>
<p>and then:</p>
<pre><code>plt.plot(ageList, list(avg_si.values()), 'ro', label='size')
</code></pre>
| 0 | 2016-09-28T14:22:02Z | [
"python"
]
|
python replace will not replace "'" with "\'" | 39,747,440 | <pre><code> dctLineItems = InvFunctions.dctLineItems
for value in dctLineItems.values():
iORDER_ID = value[0]
iITEM_No = value[1]
iQUANTITY = value[2]
sTmp = value[3]
sTmp2 = sTmp.replace("'", "\'", 1)
#sTmp2 = connPy.escape(sTmp)
sITEM_Name = sTmp2
sPART_No = value[4]
fPRICE = value[5]
fPRICE = fPRICE.lstrip('$')
iDOGWOOD = value[6]
iADVANCED = value[7]
</code></pre>
<p>I have tested it extensively and replace works for just about anything except what I need it to do. When I try to replace " ' " with " \' " it doesn't do anything. Notice the commented line#8 connPy.escape(sTmp), it doesn't work either but that is going to be a separate question.</p>
| -2 | 2016-09-28T12:24:31Z | 39,747,680 | <p>My best guess is that the backslash is known in Python as an escape sequence. Python doesn't recognize this as a literal, so you would have to put <code>\\</code> instead. The same applies to the single quote (<code>\'</code>)</p>
<p>So where you're using your replace function (I'm guessing the 5th line from the top), try typing this:</p>
<p><code>sTmp.replace("'", "\\", 1)</code></p>
| 0 | 2016-09-28T12:33:42Z | [
"python"
]
|
python replace will not replace "'" with "\'" | 39,747,440 | <pre><code> dctLineItems = InvFunctions.dctLineItems
for value in dctLineItems.values():
iORDER_ID = value[0]
iITEM_No = value[1]
iQUANTITY = value[2]
sTmp = value[3]
sTmp2 = sTmp.replace("'", "\'", 1)
#sTmp2 = connPy.escape(sTmp)
sITEM_Name = sTmp2
sPART_No = value[4]
fPRICE = value[5]
fPRICE = fPRICE.lstrip('$')
iDOGWOOD = value[6]
iADVANCED = value[7]
</code></pre>
<p>I have tested it extensively and replace works for just about anything except what I need it to do. When I try to replace " ' " with " \' " it doesn't do anything. Notice the commented line#8 connPy.escape(sTmp), it doesn't work either but that is going to be a separate question.</p>
| -2 | 2016-09-28T12:24:31Z | 39,747,728 | <p>Another option: using Python's raw strings:</p>
<pre><code>>>> "'hello'".replace("'", "\'")
>>> "'hello'"
>>>
>>> "'hello'".replace("'", "\\'")
>>> "\\'hello\\'"
>>>
>>> "'hello'".replace("'", r"\'") # <- Note the starting r
>>> "\\'hello\\'"
</code></pre>
| 0 | 2016-09-28T12:36:02Z | [
"python"
]
|
Read the Docs: Distutils2 error during installation | 39,747,527 | <p>I try to install local instance of Read the Docs on my Win10</p>
<p>When I follow this documentation:<br>
<a href="http://docs.readthedocs.io/en/latest/install.html" rel="nofollow">http://docs.readthedocs.io/en/latest/install.html</a></p>
<p>and type:</p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>I get this error:</p>
<pre><code>Collecting Distutils2==1.0a3 (from -r requirements/pip.txt (line 65))
Using cached Distutils2-1.0a3.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\USER\AppData\Local\Temp\pip-build-xseiavup\Distutils2\setup.py", line 9, in <module>
from distutils2.util import find_packages
File "C:\Users\USER\AppData\Local\Temp\pip-build-xseiavup\Distutils2\distutils2\util.py", line 174
except KeyError, var:
^
SyntaxError: invalid syntax
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\USER\AppData\Local\Temp\pip-build-xseiavup\Distutils2\
</code></pre>
<p>Anyone know this error?</p>
<p>My pip version: 8.1.2;<br>
python: 3.5</p>
| 0 | 2016-09-28T12:28:09Z | 39,747,948 | <p>Is it possible you are running the Python 2 <code>pip</code>? The error message clearly indicates that the code is being executed under Python 3 but has Python 2 syntax. Do you get better results with</p>
<pre><code>python -m pip install -r requirements.txt
</code></pre>
<p>I wonder? If not then verify that</p>
<pre><code>python
</code></pre>
<p>runs version 3.5 ...</p>
<p>Oh. I just checked and the <a href="https://pypi.python.org/pypi/Distutils2/1.0a4" rel="nofollow">disutils2 page on PyPI</a> says</p>
<p><strong>Distutils2 development is stopped.</strong></p>
<p>tl;dr: keep using setuptools and pip for now, donât use distutils2.</p>
<p>It looks like there was never a Python 3 version. Looks like you might need to update your code.</p>
| 1 | 2016-09-28T12:44:33Z | [
"python",
"read-the-docs"
]
|
Converting CSV to XML with Hierarchies using Python to feed through API | 39,747,534 | <p>I've seen a couple of answers of how to convert a csv (or SQL table) to XML, but I haven't seen one that includes hierarchies and isn't overtly complicated. I need to map a csv file into a pre-existing XML format to feed it to an API using Python. I can already send a valid XML to the website, but I'm having issues converting the csv to the XML in the first place.</p>
<p>My CSV has this format:</p>
<pre><code>OrganizationName,OrdNum,OrdType,OrderTMSStatus,FreightTerms,IsPrePayment,ScheduledEarlyPickup,ScheduledEarlyDelivery,WeightValue,uom,WeightBase,uom2,WeightValue3,uom4,WeightBase5,uom6,VolumeValue,uom7,VolumeBase,uom8,VolumeValue9,uom10,VolumeBase11,uom12,TotalPieceCount,TotalHandlingUnitCount,IsInPlanning,AreTotalsOverridden,CurrencyValue,uom13,CurrencyBase,uom14,IsHot,IsHazmat,BillingStatus,IntegrationStatus,OriginLocNum,OrganizationName15,TradingPartnerNum,TradingPartnerType,LocNum,LocationType,IsActive,IsBillTo,IsRemitTo,IsCorporate,AddrName,Addr1,CityName,StateCode,CountryISO2,PostalCode,CalendarName,CalendarAppointmentName,AllowsHazmat,IsDeliveryAptRequired,IsPickupAptRequired,DestinationLocNum,OrganizationName16,TradingPartnerNum17,TradingPartnerType18,LocNum19,LocationType20,IsActive21,IsBillTo22,IsRemitTo23,IsCorporate24,AddrName25,Addr126,CityName27,StateCode28,CountryISO229,PostalCode30,CalendarName31,CalendarAppointmentName32,AllowsHazmat33,IsDeliveryAptRequired34,IsPickupAptRequired35,OrganizationName36,TradingPartnerNum37,TradingPartnerName,TradingPartnerType38,IsActive39,OrdLineNum,WeightValue40,uom41,WeightBase42,uom43,WeightValue44,uom45,WeightBase46,uom47,VolumeValue48,uom49,VolumeBase50,uom51,VolumeValue52,uom53,VolumeBase54,uom55,PieceCount,HandlingUnitCount,IsHazmat56
My-Organization,PythonTest1,Planning,New,PPD,FALSE,3/17/2016 13:30,3/21/2016 20:00,30000,Lb,30000,Lb,30000,Lb,30000,Lb,2100,CuFt,2100,CuFt,2100,CuFt,2100,CuFt,2100,26,FALSE,FALSE,0,USD,0,USD,FALSE,FALSE,New,New,DC_OH,My-Organization,Test,Client,DC_OH,ShipReceive,TRUE,FALSE,FALSE,FALSE,DC_OH,--,Hamilton,OH,US,45014,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,CZ_906,My-Organization,Test,Client,CZ_906,ShipReceive,TRUE,FALSE,FALSE,FALSE,7-ELEVEN CDC C/O GENESIS LOGISTICS,--,Santa Fe Springs,CA,US,90670,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,My-Organization,Test,Test,Client,TRUE,1,30000,Lb,30000,Lb,30000,Lb,30000,Lb,2100,CuFt,2100,CuFt,2100,CuFt,2100,CuFt,1170,26,FALSE
My-Organization,PythonTest2,Planning,New,PPD,FALSE,3/16/2016 14:00,3/21/2016 21:00,25000,Lb,25000,Lb,25000,Lb,25000,Lb,2300,CuFt,2300,CuFt,2300,CuFt,2300,CuFt,2300,26,FALSE,FALSE,0,USD,0,USD,FALSE,FALSE,New,New,DC_KY,My-Organization,Test,Client,DC_KY,ShipReceive,TRUE,FALSE,FALSE,FALSE,DC_KY,--,Florence,KY,US,41042,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,CZ_906,My-Organization,Test,Client,CZ_906,ShipReceive,TRUE,FALSE,FALSE,FALSE,7-ELEVEN CDC C/O GENESIS LOGISTICS,--,Santa Fe Springs,CA,US,90670,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,My-Organization,Test,Test,Client,TRUE,1,25000,Lb,25000,Lb,25000,Lb,25000,Lb,2300,CuFt,2300,CuFt,2300,CuFt,2300,CuFt,1170,26,FALSE
</code></pre>
<p>This is how it should look:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:OrderData xmlns:ns1="http://schemas.3gtms.com/tms/v1/tns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Orders>
<Order>
<OrganizationName>My-Organization</OrganizationName>
<OrdNum>PythonTest1</OrdNum>
<OrdType>Planning</OrdType>
<OrderTMSStatus>New</OrderTMSStatus>
<FreightTerms>PPD</FreightTerms>
<IsPrePayment>false</IsPrePayment>
<ScheduledEarlyPickup>2016-03-17T13:30:00.000</ScheduledEarlyPickup>
<ScheduledEarlyDelivery>2016-03-21T20:00:00.000</ScheduledEarlyDelivery>
<TotalGrossWeight>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</TotalGrossWeight>
<TotalNetWeight>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</TotalNetWeight>
<TotalGrossVolume>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</TotalGrossVolume>
<TotalNetVolume>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</TotalNetVolume>
<TotalPieceCount>2100</TotalPieceCount>
<TotalHandlingUnitCount>26</TotalHandlingUnitCount>
<IsInPlanning>false</IsInPlanning>
<AreTotalsOverridden>false</AreTotalsOverridden>
<FreightValue>
<CurrencyValue uom="USD">0</CurrencyValue>
<CurrencyBase uom="USD">0</CurrencyBase>
</FreightValue>
<IsHot>false</IsHot>
<IsHazmat>false</IsHazmat>
<BillingStatus>New</BillingStatus>
<IntegrationStatus>New</IntegrationStatus>
<OriginLocNum>DC_OH</OriginLocNum>
<OriginLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>DC_OH</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>DC_OH</AddrName>
<Addr1>--</Addr1>
<CityName>Hamilton</CityName>
<StateCode>OH</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>45014</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</OriginLoc>
<DestinationLocNum>CZ_906</DestinationLocNum>
<DestinationLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>CZ_906</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>7-ELEVEN CDC C/O GENESIS LOGISTICS</AddrName>
<Addr1>--</Addr1>
<CityName>Santa Fe Springs</CityName>
<StateCode>CA</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>90670</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</DestinationLoc>
<Client>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerName>Test</TradingPartnerName>
<TradingPartnerType>Client</TradingPartnerType>
<IsActive>true</IsActive>
</Client>
<OrderLines>
<OrderLine>
<OrdLineNum>1</OrdLineNum>
<WeightGross>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</WeightGross>
<WeightNet>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</WeightNet>
<VolumeGross>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</VolumeGross>
<VolumeNet>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</VolumeNet>
<PieceCount>1170</PieceCount>
<HandlingUnitCount>26</HandlingUnitCount>
<IsHazmat>false</IsHazmat>
</OrderLine>
</OrderLines>
</Order>
<Order>
<OrganizationName>My-Organization</OrganizationName>
<OrdNum>PythonTest2</OrdNum>
<OrdType>Planning</OrdType>
<OrderTMSStatus>New</OrderTMSStatus>
<FreightTerms>PPD</FreightTerms>
<IsPrePayment>false</IsPrePayment>
<ScheduledEarlyPickup>2016-03-16T14:00:00.000</ScheduledEarlyPickup>
<ScheduledEarlyDelivery>2016-03-21T21:00:00.000</ScheduledEarlyDelivery>
<TotalGrossWeight>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</TotalGrossWeight>
<TotalNetWeight>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</TotalNetWeight>
<TotalGrossVolume>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</TotalGrossVolume>
<TotalNetVolume>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</TotalNetVolume>
<TotalPieceCount>2300</TotalPieceCount>
<TotalHandlingUnitCount>26</TotalHandlingUnitCount>
<IsInPlanning>false</IsInPlanning>
<AreTotalsOverridden>false</AreTotalsOverridden>
<FreightValue>
<CurrencyValue uom="USD">0</CurrencyValue>
<CurrencyBase uom="USD">0</CurrencyBase>
</FreightValue>
<IsHot>false</IsHot>
<IsHazmat>false</IsHazmat>
<BillingStatus>New</BillingStatus>
<IntegrationStatus>New</IntegrationStatus>
<OriginLocNum>DC_KY</OriginLocNum>
<OriginLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>DC_KY</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>DC_KY</AddrName>
<Addr1>--</Addr1>
<CityName>Florence</CityName>
<StateCode>KY</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>41042</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</OriginLoc>
<DestinationLocNum>CZ_906</DestinationLocNum>
<DestinationLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>CZ_906</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>7-ELEVEN CDC C/O GENESIS LOGISTICS</AddrName>
<Addr1>--</Addr1>
<CityName>Santa Fe Springs</CityName>
<StateCode>CA</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>90670</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</DestinationLoc>
<Client>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerName>Test</TradingPartnerName>
<TradingPartnerType>Client</TradingPartnerType>
<IsActive>true</IsActive>
</Client>
<OrderLines>
<OrderLine>
<OrdLineNum>1</OrdLineNum>
<WeightGross>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</WeightGross>
<WeightNet>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</WeightNet>
<VolumeGross>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</VolumeGross>
<VolumeNet>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</VolumeNet>
<PieceCount>1170</PieceCount>
<HandlingUnitCount>26</HandlingUnitCount>
<IsHazmat>false</IsHazmat>
</OrderLine>
</OrderLines>
</Order>
</Orders>
</code></pre>
<p></p>
<p>Help is much appreciated.</p>
<hr>
<p>In case it is helpful for anyone trying to do something similar, this is how you upload the valid XML to the system:</p>
<pre><code>import requests
filename = 'somefile.xml'
api_url = 'someurl.com'
headers = {'Content-Type': 'application/xml'}
response = requests.post(api_url, data=open(filename).read(), headers=headers)
</code></pre>
| 0 | 2016-09-28T12:28:21Z | 39,747,761 | <p>There is no generic library to directly convert your CSV to a required XML. You will need to build the XML using xml functions provided by python or using something like <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">xml.etree API</a> </p>
<p><a href="http://stackoverflow.com/questions/20063987/python-create-xml-from-csv-within-a-loop">Here's one sample link</a></p>
<p>This is a flow in which you can achieve it -></p>
<ol>
<li>Read CSV</li>
<li><p>Create your namespace</p>
<p>
</p></li>
<li><p>Create your parent node <code><Orders></code></p></li>
<li><p>Read the CSV. For each line, create a new node <code><Order></code> and add elements to it. Add this node as a child to parent <code><Orders></code></p></li>
<li><p>Repeat Step 4 tile end of file</p></li>
</ol>
| 0 | 2016-09-28T12:37:23Z | [
"python",
"xml",
"csv"
]
|
Converting CSV to XML with Hierarchies using Python to feed through API | 39,747,534 | <p>I've seen a couple of answers of how to convert a csv (or SQL table) to XML, but I haven't seen one that includes hierarchies and isn't overtly complicated. I need to map a csv file into a pre-existing XML format to feed it to an API using Python. I can already send a valid XML to the website, but I'm having issues converting the csv to the XML in the first place.</p>
<p>My CSV has this format:</p>
<pre><code>OrganizationName,OrdNum,OrdType,OrderTMSStatus,FreightTerms,IsPrePayment,ScheduledEarlyPickup,ScheduledEarlyDelivery,WeightValue,uom,WeightBase,uom2,WeightValue3,uom4,WeightBase5,uom6,VolumeValue,uom7,VolumeBase,uom8,VolumeValue9,uom10,VolumeBase11,uom12,TotalPieceCount,TotalHandlingUnitCount,IsInPlanning,AreTotalsOverridden,CurrencyValue,uom13,CurrencyBase,uom14,IsHot,IsHazmat,BillingStatus,IntegrationStatus,OriginLocNum,OrganizationName15,TradingPartnerNum,TradingPartnerType,LocNum,LocationType,IsActive,IsBillTo,IsRemitTo,IsCorporate,AddrName,Addr1,CityName,StateCode,CountryISO2,PostalCode,CalendarName,CalendarAppointmentName,AllowsHazmat,IsDeliveryAptRequired,IsPickupAptRequired,DestinationLocNum,OrganizationName16,TradingPartnerNum17,TradingPartnerType18,LocNum19,LocationType20,IsActive21,IsBillTo22,IsRemitTo23,IsCorporate24,AddrName25,Addr126,CityName27,StateCode28,CountryISO229,PostalCode30,CalendarName31,CalendarAppointmentName32,AllowsHazmat33,IsDeliveryAptRequired34,IsPickupAptRequired35,OrganizationName36,TradingPartnerNum37,TradingPartnerName,TradingPartnerType38,IsActive39,OrdLineNum,WeightValue40,uom41,WeightBase42,uom43,WeightValue44,uom45,WeightBase46,uom47,VolumeValue48,uom49,VolumeBase50,uom51,VolumeValue52,uom53,VolumeBase54,uom55,PieceCount,HandlingUnitCount,IsHazmat56
My-Organization,PythonTest1,Planning,New,PPD,FALSE,3/17/2016 13:30,3/21/2016 20:00,30000,Lb,30000,Lb,30000,Lb,30000,Lb,2100,CuFt,2100,CuFt,2100,CuFt,2100,CuFt,2100,26,FALSE,FALSE,0,USD,0,USD,FALSE,FALSE,New,New,DC_OH,My-Organization,Test,Client,DC_OH,ShipReceive,TRUE,FALSE,FALSE,FALSE,DC_OH,--,Hamilton,OH,US,45014,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,CZ_906,My-Organization,Test,Client,CZ_906,ShipReceive,TRUE,FALSE,FALSE,FALSE,7-ELEVEN CDC C/O GENESIS LOGISTICS,--,Santa Fe Springs,CA,US,90670,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,My-Organization,Test,Test,Client,TRUE,1,30000,Lb,30000,Lb,30000,Lb,30000,Lb,2100,CuFt,2100,CuFt,2100,CuFt,2100,CuFt,1170,26,FALSE
My-Organization,PythonTest2,Planning,New,PPD,FALSE,3/16/2016 14:00,3/21/2016 21:00,25000,Lb,25000,Lb,25000,Lb,25000,Lb,2300,CuFt,2300,CuFt,2300,CuFt,2300,CuFt,2300,26,FALSE,FALSE,0,USD,0,USD,FALSE,FALSE,New,New,DC_KY,My-Organization,Test,Client,DC_KY,ShipReceive,TRUE,FALSE,FALSE,FALSE,DC_KY,--,Florence,KY,US,41042,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,CZ_906,My-Organization,Test,Client,CZ_906,ShipReceive,TRUE,FALSE,FALSE,FALSE,7-ELEVEN CDC C/O GENESIS LOGISTICS,--,Santa Fe Springs,CA,US,90670,Mon-Fri-8-5,24/7 Appointment,FALSE,FALSE,FALSE,My-Organization,Test,Test,Client,TRUE,1,25000,Lb,25000,Lb,25000,Lb,25000,Lb,2300,CuFt,2300,CuFt,2300,CuFt,2300,CuFt,1170,26,FALSE
</code></pre>
<p>This is how it should look:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:OrderData xmlns:ns1="http://schemas.3gtms.com/tms/v1/tns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Orders>
<Order>
<OrganizationName>My-Organization</OrganizationName>
<OrdNum>PythonTest1</OrdNum>
<OrdType>Planning</OrdType>
<OrderTMSStatus>New</OrderTMSStatus>
<FreightTerms>PPD</FreightTerms>
<IsPrePayment>false</IsPrePayment>
<ScheduledEarlyPickup>2016-03-17T13:30:00.000</ScheduledEarlyPickup>
<ScheduledEarlyDelivery>2016-03-21T20:00:00.000</ScheduledEarlyDelivery>
<TotalGrossWeight>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</TotalGrossWeight>
<TotalNetWeight>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</TotalNetWeight>
<TotalGrossVolume>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</TotalGrossVolume>
<TotalNetVolume>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</TotalNetVolume>
<TotalPieceCount>2100</TotalPieceCount>
<TotalHandlingUnitCount>26</TotalHandlingUnitCount>
<IsInPlanning>false</IsInPlanning>
<AreTotalsOverridden>false</AreTotalsOverridden>
<FreightValue>
<CurrencyValue uom="USD">0</CurrencyValue>
<CurrencyBase uom="USD">0</CurrencyBase>
</FreightValue>
<IsHot>false</IsHot>
<IsHazmat>false</IsHazmat>
<BillingStatus>New</BillingStatus>
<IntegrationStatus>New</IntegrationStatus>
<OriginLocNum>DC_OH</OriginLocNum>
<OriginLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>DC_OH</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>DC_OH</AddrName>
<Addr1>--</Addr1>
<CityName>Hamilton</CityName>
<StateCode>OH</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>45014</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</OriginLoc>
<DestinationLocNum>CZ_906</DestinationLocNum>
<DestinationLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>CZ_906</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>7-ELEVEN CDC C/O GENESIS LOGISTICS</AddrName>
<Addr1>--</Addr1>
<CityName>Santa Fe Springs</CityName>
<StateCode>CA</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>90670</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</DestinationLoc>
<Client>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerName>Test</TradingPartnerName>
<TradingPartnerType>Client</TradingPartnerType>
<IsActive>true</IsActive>
</Client>
<OrderLines>
<OrderLine>
<OrdLineNum>1</OrdLineNum>
<WeightGross>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</WeightGross>
<WeightNet>
<WeightValue uom="Lb">30000</WeightValue>
<WeightBase uom="Lb">30000</WeightBase>
</WeightNet>
<VolumeGross>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</VolumeGross>
<VolumeNet>
<VolumeValue uom="CuFt">2100</VolumeValue>
<VolumeBase uom="CuFt">2100</VolumeBase>
</VolumeNet>
<PieceCount>1170</PieceCount>
<HandlingUnitCount>26</HandlingUnitCount>
<IsHazmat>false</IsHazmat>
</OrderLine>
</OrderLines>
</Order>
<Order>
<OrganizationName>My-Organization</OrganizationName>
<OrdNum>PythonTest2</OrdNum>
<OrdType>Planning</OrdType>
<OrderTMSStatus>New</OrderTMSStatus>
<FreightTerms>PPD</FreightTerms>
<IsPrePayment>false</IsPrePayment>
<ScheduledEarlyPickup>2016-03-16T14:00:00.000</ScheduledEarlyPickup>
<ScheduledEarlyDelivery>2016-03-21T21:00:00.000</ScheduledEarlyDelivery>
<TotalGrossWeight>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</TotalGrossWeight>
<TotalNetWeight>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</TotalNetWeight>
<TotalGrossVolume>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</TotalGrossVolume>
<TotalNetVolume>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</TotalNetVolume>
<TotalPieceCount>2300</TotalPieceCount>
<TotalHandlingUnitCount>26</TotalHandlingUnitCount>
<IsInPlanning>false</IsInPlanning>
<AreTotalsOverridden>false</AreTotalsOverridden>
<FreightValue>
<CurrencyValue uom="USD">0</CurrencyValue>
<CurrencyBase uom="USD">0</CurrencyBase>
</FreightValue>
<IsHot>false</IsHot>
<IsHazmat>false</IsHazmat>
<BillingStatus>New</BillingStatus>
<IntegrationStatus>New</IntegrationStatus>
<OriginLocNum>DC_KY</OriginLocNum>
<OriginLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>DC_KY</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>DC_KY</AddrName>
<Addr1>--</Addr1>
<CityName>Florence</CityName>
<StateCode>KY</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>41042</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</OriginLoc>
<DestinationLocNum>CZ_906</DestinationLocNum>
<DestinationLoc>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerType>Client</TradingPartnerType>
<LocNum>CZ_906</LocNum>
<LocationType>ShipReceive</LocationType>
<IsActive>true</IsActive>
<IsBillTo>false</IsBillTo>
<IsRemitTo>false</IsRemitTo>
<IsCorporate>false</IsCorporate>
<AddrName>7-ELEVEN CDC C/O GENESIS LOGISTICS</AddrName>
<Addr1>--</Addr1>
<CityName>Santa Fe Springs</CityName>
<StateCode>CA</StateCode>
<CountryISO2>US</CountryISO2>
<PostalCode>90670</PostalCode>
<CalendarName>Mon-Fri-8-5</CalendarName>
<CalendarAppointmentName>24/7 Appointment</CalendarAppointmentName>
<AllowsHazmat>false</AllowsHazmat>
<IsDeliveryAptRequired>false</IsDeliveryAptRequired>
<IsPickupAptRequired>false</IsPickupAptRequired>
</DestinationLoc>
<Client>
<OrganizationName>My-Organization</OrganizationName>
<TradingPartnerNum>Test</TradingPartnerNum>
<TradingPartnerName>Test</TradingPartnerName>
<TradingPartnerType>Client</TradingPartnerType>
<IsActive>true</IsActive>
</Client>
<OrderLines>
<OrderLine>
<OrdLineNum>1</OrdLineNum>
<WeightGross>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</WeightGross>
<WeightNet>
<WeightValue uom="Lb">25000</WeightValue>
<WeightBase uom="Lb">25000</WeightBase>
</WeightNet>
<VolumeGross>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</VolumeGross>
<VolumeNet>
<VolumeValue uom="CuFt">2300</VolumeValue>
<VolumeBase uom="CuFt">2300</VolumeBase>
</VolumeNet>
<PieceCount>1170</PieceCount>
<HandlingUnitCount>26</HandlingUnitCount>
<IsHazmat>false</IsHazmat>
</OrderLine>
</OrderLines>
</Order>
</Orders>
</code></pre>
<p></p>
<p>Help is much appreciated.</p>
<hr>
<p>In case it is helpful for anyone trying to do something similar, this is how you upload the valid XML to the system:</p>
<pre><code>import requests
filename = 'somefile.xml'
api_url = 'someurl.com'
headers = {'Content-Type': 'application/xml'}
response = requests.post(api_url, data=open(filename).read(), headers=headers)
</code></pre>
| 0 | 2016-09-28T12:28:21Z | 39,783,287 | <p>I actually figured out a SQL solution for this...but it is ridiculously manual and specific for my case. I hope the format still helps someone solve a similar issue.</p>
<p>If you notice from the code below, the XML tags will assume the name of the column if you don't include an alias. You can use the format 'Parent/Child' for hierarchies... Look at the bottom of the query to see multiple embedded hierarchies.</p>
<pre><code>SELECT
[OrganizationName]
,[OrdNum]
,[OrdType]
,[OrderTMSStatus]
,[FreightTerms]
,[IsPrePayment]
,[ScheduledEarlyPickup]
,[ScheduledEarlyDelivery]
,[WeightValue] 'TotalGrossWeight/WeightValue'
,[WeightBase] 'TotalGrossWeight/WeightBase'
,[WeightValue3] 'TotalNetWeight/WeightValue'
,[WeightBase5] 'TotalNetWeight/WeightBase'
,[VolumeValue] 'TotalGrossVolume/VolumeValue'
,[VolumeBase] 'TotalGrossVolume/VolumeBase'
,[VolumeValue9] 'TotalNetVolume/VolumeValue'
,[VolumeBase11] 'TotalNetVolume/VolumeBase'
,[TotalPieceCount]
,[TotalHandlingUnitCount]
,[IsInPlanning]
,[AreTotalsOverridden]
,[CurrencyValue] 'FreightValue/CurrencyValue'
,[CurrencyBase] 'FreightValue/CurrencyBase'
,[IsHot]
,[IsHazmat]
,[BillingStatus]
,[IntegrationStatus]
,[OriginLocNum]
,[OrganizationName15] 'OriginLoc/OrganizationName'
,[TradingPartnerNum] 'OriginLoc/TradingPartnerNum'
,[TradingPartnerType] 'OriginLoc/TradingPartnerType'
,[LocNum] 'OriginLoc/LocNum'
,[LocationType] 'OriginLoc/LocationType'
,[IsActive] 'OriginLoc/IsActive'
,[IsBillTo] 'OriginLoc/IsBillTo'
,[IsRemitTo] 'OriginLoc/IsRemitTo'
,[IsCorporate] 'OriginLoc/IsCorporate'
,[AddrName] 'OriginLoc/AddrName'
,[Addr1] 'OriginLoc/Addr1'
,[CityName] 'OriginLoc/CityName'
,[StateCode] 'OriginLoc/StateCode'
,[CountryISO2] 'OriginLoc/CountryISO2'
,[PostalCode] 'OriginLoc/PostalCode'
,[CalendarName] 'OriginLoc/CalendarName'
,[CalendarAppointmentName] 'OriginLoc/CalendarAppointmentName'
,[AllowsHazmat] 'OriginLoc/AllowsHazmat'
,[IsDeliveryAptRequired] 'OriginLoc/IsDeliveryAptRequired'
,[IsPickupAptRequired] 'OriginLoc/IsPickupAptRequired'
,[DestinationLocNum]
,[OrganizationName16] 'DestinationLoc/OrganizationName'
,[TradingPartnerNum17] 'DestinationLoc/TradingPartnerNum'
,[TradingPartnerType18] 'DestinationLoc/TradingPartnerType'
,[LocNum19] 'DestinationLoc/LocNum'
,[LocationType20] 'DestinationLoc/LocationType'
,[IsActive21] 'DestinationLoc/IsActive'
,[IsBillTo22] 'DestinationLoc/IsBillTo'
,[IsRemitTo23] 'DestinationLoc/IsRemitTo'
,[IsCorporate24] 'DestinationLoc/IsCorporate'
,[AddrName25] 'DestinationLoc/AddrName'
,[Addr126] 'DestinationLoc/Addr1'
,[CityName27] 'DestinationLoc/CityName'
,[StateCode28] 'DestinationLoc/StateCode'
,[CountryISO229] 'DestinationLoc/CountryISO2'
,[PostalCode30] 'DestinationLoc/PostalCode'
,[CalendarName31] 'DestinationLoc/CalendarName'
,[CalendarAppointmentName32] 'DestinationLoc/CalendarAppointmentName'
,[AllowsHazmat33] 'DestinationLoc/AllowsHazmat'
,[IsDeliveryAptRequired34] 'DestinationLoc/IsDeliveryAptRequired'
,[IsPickupAptRequired35] 'DestinationLoc/IsPickupAptRequired'
,[OrganizationName36] 'Client/OrganizationName'
,[TradingPartnerNum37] 'Client/TradingPartnerNum'
,[TradingPartnerName] 'Client/TradingPartnerName'
,[TradingPartnerType38] 'Client/TradingPartnerType'
,[IsActive39] 'Client/IsActive'
,[OrdLineNum] 'OrderLines/OrderLine/OrdLineNum'
,[WeightValue40] 'OrderLines/OrderLine/WeightGross/WeightValue'
,[WeightBase42] 'OrderLines/OrderLine/WeightGross/WeightBase'
,[WeightValue44] 'OrderLines/OrderLine/WeightNet/WeightValue'
,[WeightBase46] 'OrderLines/OrderLine/WeightNet/WeightBase'
,[VolumeValue48] 'OrderLines/OrderLine/VolumeGross/VolumeValue'
,[VolumeBase50] 'OrderLines/OrderLine/VolumeGross/VolumeBase'
,[VolumeValue52] 'OrderLines/OrderLine/VolumeNet/VolumeValue'
,[VolumeBase54] 'OrderLines/OrderLine/VolumeNet/VolumeBase'
,[PieceCount] 'OrderLines/OrderLine/PieceCount'
,[HandlingUnitCount] 'OrderLines/OrderLine/HandlingUnitCount'
,[IsHazmat56] 'OrderLines/OrderLine/IsHazmat'
FROM [MyDatabase].[dbo].[OrderSample]
For XML PATH ('Order')
</code></pre>
<p>I run that script inside of Python using the pymssql library</p>
<pre><code>#Create a function that reads SQL Query file and returns the result as a string
def queryReturn(query=sql, connection = conn):
'''
This function runs a SQL File and returns the result as a strings
It takes in a T-SQL file as the first argument
For example:
sql=open('sqlFinal.sql', 'r').read().decode('utf-8')
xml = queryReturn(sql)
You can also define which database connection to use
For example: xml = queryReturn(sql,conn)
'''
cursor = connection.cursor()
cursor.execute(query)
result= "".join([item[0] for item in cursor.fetchall()])
return result
#Create the header and tail for the XML
header ='''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:OrderData xmlns:ns1="http://schemas.3gtms.com/tms/v1/tns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Orders>\n '''
tail = '''\n </Orders>
</ns1:OrderData> '''
#Add uom to the opening tags that need it
xml2=xml2.replace('<WeightValue','<WeightValue uom="Lb"')
xml2=xml2.replace('<WeightBase','<WeightBase uom="Lb"')
xml2=xml2.replace('<VolumeValue','<VolumeValue uom="CuFt"')
xml2=xml2.replace('<VolumeBase','<VolumeBase uom="CuFt"')
xml2=xml2.replace('<CurrencyValue','<CurrencyValue uom="USD"')
xml2=xml2.replace('<CurrencyBase','<CurrencyBase uom="USD"')
</code></pre>
<p>Then I add the top and bottom parts of the query to the main body:</p>
<pre><code>#create final XML string
final = header+xml2+tail
</code></pre>
| 0 | 2016-09-30T03:38:38Z | [
"python",
"xml",
"csv"
]
|
My beginner python project (calculator) is having trouble with inputs | 39,747,635 | <p>Whenever I test my calculator to see how it deals with inputs that are not numbers, it flags up a ValueError. More precisely, this one "ValueError: could not convert string to float: 'a'". I have tried to amend this so there is a solution to dealing with non-integers but to no avail... Help is much appreciated.</p>
<p>Here is my code so far:</p>
<pre><code>print("1. ADDITION ")
print("2. MULTIPLICATION ")
print("3. TAKEAWAY ")
print("4. DIVISION ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
while Operator > 4:
print("Please select a number from the options above. ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
if Operator != (1 or 2 or 3 or 4):
print("please enter one of the options above. ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
continue
while True:
Num1 = float(input("Please enter first number. "))
if Num1 == float(Num1):
print("thanks! ")
elif Num1 != float(Num1):
Num1 = float(input("Please enter first number. "))
break
while True:
Num2 = float(input("Please enter second number. "))
if Num2 == float(Num2):
print("thanks ")
elif Num1 != float(Num1):
Num1 = float(input("Please enter first number. "))
break
</code></pre>
| -2 | 2016-09-28T12:31:44Z | 39,747,784 | <p>Please read the docs for handling exceptions:</p>
<p><a href="https://docs.python.org/2/tutorial/errors.html#handling-exceptions" rel="nofollow">https://docs.python.org/2/tutorial/errors.html#handling-exceptions</a></p>
<p>for a float:</p>
<pre><code>try:
x = float(input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
</code></pre>
| 0 | 2016-09-28T12:38:01Z | [
"python"
]
|
My beginner python project (calculator) is having trouble with inputs | 39,747,635 | <p>Whenever I test my calculator to see how it deals with inputs that are not numbers, it flags up a ValueError. More precisely, this one "ValueError: could not convert string to float: 'a'". I have tried to amend this so there is a solution to dealing with non-integers but to no avail... Help is much appreciated.</p>
<p>Here is my code so far:</p>
<pre><code>print("1. ADDITION ")
print("2. MULTIPLICATION ")
print("3. TAKEAWAY ")
print("4. DIVISION ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
while Operator > 4:
print("Please select a number from the options above. ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
if Operator != (1 or 2 or 3 or 4):
print("please enter one of the options above. ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
continue
while True:
Num1 = float(input("Please enter first number. "))
if Num1 == float(Num1):
print("thanks! ")
elif Num1 != float(Num1):
Num1 = float(input("Please enter first number. "))
break
while True:
Num2 = float(input("Please enter second number. "))
if Num2 == float(Num2):
print("thanks ")
elif Num1 != float(Num1):
Num1 = float(input("Please enter first number. "))
break
</code></pre>
| -2 | 2016-09-28T12:31:44Z | 39,747,788 | <p>Exception handling is what are you looking for.
Smthng like this:</p>
<pre><code>input = 'a'
try:
int(a)
except ValueError:
print 'Input is not integer'
</code></pre>
| 1 | 2016-09-28T12:38:08Z | [
"python"
]
|
My beginner python project (calculator) is having trouble with inputs | 39,747,635 | <p>Whenever I test my calculator to see how it deals with inputs that are not numbers, it flags up a ValueError. More precisely, this one "ValueError: could not convert string to float: 'a'". I have tried to amend this so there is a solution to dealing with non-integers but to no avail... Help is much appreciated.</p>
<p>Here is my code so far:</p>
<pre><code>print("1. ADDITION ")
print("2. MULTIPLICATION ")
print("3. TAKEAWAY ")
print("4. DIVISION ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
while Operator > 4:
print("Please select a number from the options above. ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
if Operator != (1 or 2 or 3 or 4):
print("please enter one of the options above. ")
Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
continue
while True:
Num1 = float(input("Please enter first number. "))
if Num1 == float(Num1):
print("thanks! ")
elif Num1 != float(Num1):
Num1 = float(input("Please enter first number. "))
break
while True:
Num2 = float(input("Please enter second number. "))
if Num2 == float(Num2):
print("thanks ")
elif Num1 != float(Num1):
Num1 = float(input("Please enter first number. "))
break
</code></pre>
| -2 | 2016-09-28T12:31:44Z | 39,747,928 | <p>Note: You should name your variables in lower case according to PEP8, see: <a href="http://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names">What is the naming convention in Python for variable and function names?</a>.</p>
<p>If you want to retry an input until you don't get <code>ValueError</code>, put it in a loop:</p>
<pre><code>print("Please select a number from the options above.")
while True:
try:
operator = int(input("please enter one of the numbers above to decide the operator you want: "))
except ValueError:
print("Sorry, not a number. Please retry.")
else:
if 1 <= operator <= 4:
break
else:
print("Sorry, choose a value between 1 and 4.")
</code></pre>
<p>Note: use <code>input</code> with Python 3.x or <code>raw_input</code> with Python 2.7</p>
<pre><code>1. ADDITION
2. MULTIPLICATION
3. TAKEAWAY
4. DIVISION
Please select a number from the options above.
please enter one of the numbers above to decide the operator you want: spam
Sorry, not a number. Please retry.
please enter one of the numbers above to decide the operator you want: 12
Sorry, choose a value between 1 and 4.
please enter one of the numbers above to decide the operator you want: 2
</code></pre>
| 0 | 2016-09-28T12:43:34Z | [
"python"
]
|
Airflow unable to execute all the dependent tasks in one go from UI | 39,747,645 | <p>My DAG has 3 tasks and we are using Celery executor as we have to trigger individual tasks from UI.We are able to execute the individual task from UI.</p>
<p>The problem which we are facing currently, is that we are unable to execute all the steps of DAG from UI in one go, although we have set the task dependencies.</p>
<p>We are able to execute the complete DAG from command line but is there any way to execute the same via UI ?</p>
| 0 | 2016-09-28T12:32:05Z | 39,801,249 | <p>could it be that you just need to restart the <em>webserver</em> and the <em>scheduler</em>? It happens when you change your code, like adding new tasks.
Please post more details and some code.</p>
| 0 | 2016-09-30T23:02:03Z | [
"python",
"airflow"
]
|
Download specific file in url using PHP/Python | 39,747,730 | <p>I previously used to use <code>wget -r</code> on the linux terminal for downloading files with certain extensions:</p>
<pre><code>wget -r -A Ext URL
</code></pre>
<p>But now I was assigned by my lecturer to do the same thing using PHP or Python. Who can help?</p>
| 1 | 2016-09-28T12:36:02Z | 39,747,825 | <p>I guess urllib pretty well for you</p>
<pre><code>import urllib
urllib.urlretrieve (URL, file)
</code></pre>
| 2 | 2016-09-28T12:39:36Z | [
"php",
"python",
"web-crawler",
"wget"
]
|
Download specific file in url using PHP/Python | 39,747,730 | <p>I previously used to use <code>wget -r</code> on the linux terminal for downloading files with certain extensions:</p>
<pre><code>wget -r -A Ext URL
</code></pre>
<p>But now I was assigned by my lecturer to do the same thing using PHP or Python. Who can help?</p>
| 1 | 2016-09-28T12:36:02Z | 39,747,874 | <p>You can use PHP function <code>file_get_contents()</code> to retrieve the contents of a documents. The first argument of the function is filename which can either be a local path to a file or a URL.<br>
See example from PHP <a href="http://php.net/manual/en/function.file-get-contents.php" rel="nofollow">docs</a> </p>
<pre><code><?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
</code></pre>
| 1 | 2016-09-28T12:41:13Z | [
"php",
"python",
"web-crawler",
"wget"
]
|
Download specific file in url using PHP/Python | 39,747,730 | <p>I previously used to use <code>wget -r</code> on the linux terminal for downloading files with certain extensions:</p>
<pre><code>wget -r -A Ext URL
</code></pre>
<p>But now I was assigned by my lecturer to do the same thing using PHP or Python. Who can help?</p>
| 1 | 2016-09-28T12:36:02Z | 39,748,094 | <p>Alternatively, you can use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a>: Requests is the only Non-GMO HTTP library for Python, safe for human consumption.</p>
<p>Example (from the doc):</p>
<pre><code>>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
</code></pre>
| 0 | 2016-09-28T12:50:44Z | [
"php",
"python",
"web-crawler",
"wget"
]
|
Download specific file in url using PHP/Python | 39,747,730 | <p>I previously used to use <code>wget -r</code> on the linux terminal for downloading files with certain extensions:</p>
<pre><code>wget -r -A Ext URL
</code></pre>
<p>But now I was assigned by my lecturer to do the same thing using PHP or Python. Who can help?</p>
| 1 | 2016-09-28T12:36:02Z | 39,782,286 | <p>For Python, use a web-crawler library such as scrapy.</p>
<p>It has <a href="https://doc.scrapy.org/en/latest/topics/spiders.html" rel="nofollow">classes</a> that do all the work when passed arguments similar to those you put on the <code>wget</code> command line.</p>
<p>You can use scrapy <a href="https://doc.scrapy.org/en/latest/topics/media-pipeline.html" rel="nofollow">pipelines</a> to filter out unwanted downloads, and value-add the downloads such as adding thumbnails.</p>
| 0 | 2016-09-30T01:20:16Z | [
"php",
"python",
"web-crawler",
"wget"
]
|
The efficient way of Array transformation by using numpy | 39,747,900 | <p>How to change the ARRAY U(Nz,Ny, Nx) to U(Nx,Ny, Nz) by using numpy? thanks</p>
| 0 | 2016-09-28T12:42:40Z | 39,747,938 | <p>Just <code>numpy.transpose(U)</code> or <code>U.T</code>.</p>
| 5 | 2016-09-28T12:44:07Z | [
"python",
"numpy"
]
|
The efficient way of Array transformation by using numpy | 39,747,900 | <p>How to change the ARRAY U(Nz,Ny, Nx) to U(Nx,Ny, Nz) by using numpy? thanks</p>
| 0 | 2016-09-28T12:42:40Z | 39,748,990 | <p>In general, if you want to change the order of data in numpy array, see <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/routines.array-manipulation.html#rearranging-elements" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.1/reference/routines.array-manipulation.html#rearranging-elements</a>.</p>
<p>The <code>np.fliplr()</code> and <code>np.flipud()</code> functions can be particularly useful when the transpose is not actually what you want. </p>
<p>Additionally, more general element reordering can be done by creating an index mask, partially explained <a href="http://stackoverflow.com/questions/19984102/select-elements-of-numpy-array-via-boolean-mask-array">here</a></p>
| 2 | 2016-09-28T13:29:35Z | [
"python",
"numpy"
]
|
Passing arg to subprocess.call | 39,748,061 | <p>I have a series of scripts that get called in an explicit order by another <code>run.py</code>. </p>
<p>Inside <code>run.py</code> I have the following:</p>
<pre><code>script1 = str(sys.path[0]) + "\\script1.py"
subprocess.call(["Python", script1])
</code></pre>
<p>And so on for 3 scripts. If I would like to pass two arguments to script 1 in this format, arguments such as explicit run settings to be used in the script when it is executing, how would I do this? I have a feeling it would rely on sys.argv within script1, but have gotten errors about the argument being out of range regardless of what index position I pass.</p>
<p>Thanks!</p>
| 0 | 2016-09-28T12:49:27Z | 39,748,170 | <p>Subprocesses takes a list of arguments, which it then turns into a command it executes.</p>
<p>So:</p>
<pre><code>subprocess.call(["Python", script1, 'arg1', 'arg2'])
</code></pre>
<p>To <code>subprocess.call</code>, <em>all</em> the parts of its list are arguments. You just happen to be specifying "Python" and script1, but to subprocess, both are just other arguments.</p>
<p>There is a lot more reading on the <a href="https://docs.python.org/2/library/subprocess.html#using-the-subprocess-module" rel="nofollow">documentation for subprocess</a> which I would recommend looking over.</p>
| 2 | 2016-09-28T12:54:06Z | [
"python",
"subprocess",
"exec",
"call",
"sys"
]
|
How to extract certain strings when they occur adjacently with BeautifulSoup | 39,748,092 | <p>I'm parsing an HTML page's result from BeautifulSoup and the part(s) I'm interested in looks like this:</p>
<pre><code><i class="fa fa-circle align-middle font-80" style="color: #45C414; margin-right: 15px"></i>Departure for <a href="/en/ais/details/ports/17787/port_name:TEKIRDAG/_:3525d580eade08cfdb72083b248185a9" title="View details for: TEKIRDAG">TEKIRDAG</a> </td>
</code></pre>
<p>I'm interested in extracting the <code>port_name</code>, TEKIRDAG, however there are many port name's that are labeled identically. My question is is there a way to only extract <code>port_name</code> if it occers after the string <code>'Departure for'</code>?</p>
| 2 | 2016-09-28T12:50:37Z | 39,748,141 | <p>You can locate the text node and get the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow">next sibling</a>:</p>
<pre><code>In [1]: from bs4 import BeautifulSoup
In [2]: data = """<i class="fa fa-circle align-middle font-80" style="color: #45C414; margin-right: 15px"></i>Departu
...: re for <a href="/en/ais/details/ports/17787/port_name:TEKIRDAG/_:3525d580eade08cfdb72083b248185a9" title="Vie
...: w details for: TEKIRDAG">TEKIRDAG</a> </td>"""
...:
In [3]: soup = BeautifulSoup(data, "html.parser")
In [4]: soup.find(text="Departure for ").next_sibling.get_text()
Out[4]: u'TEKIRDAG'
</code></pre>
| 1 | 2016-09-28T12:52:39Z | [
"python",
"html",
"beautifulsoup"
]
|
Converting a str to an int | 39,748,223 | <p>My Problem is that the type <code>'ip'</code> is str, but i need integer.</p>
<p>So i did the convert <code>int(ip)</code>. Then i got error </p>
<blockquote>
<p>invalid literal for int() with base 10:</p>
</blockquote>
<p>So i did a little bit of research and found that i had to put int <code>int(float(ip))</code>. </p>
<p>Now i get "could not convert string to float". </p>
<pre><code>import socket
def retrieveBanner(ip, port):
s = socket.socket()
s.connect((int(float(ip)),port))
banner = s.recv(1024).decode()
print("Bitte geben Sie eine IP und ein Port ein")
ip = input("IP? ")
port = input("Port? ")
retrieveBanner(ip, port)
if ("NASFTPD" in banner):
print("Vulnerable")
</code></pre>
| -4 | 2016-09-28T12:56:14Z | 39,748,401 | <p>According to the <a href="https://docs.python.org/3/library/socket.html#socket.socket.connect" rel="nofollow">documentation</a>, <code>connect</code> expects a tuple <code>(string, int)</code>, with the string being the ip address and the int being the port. You can modify your code this way to fix it :</p>
<pre><code>s.connect((ip, int(port)))
</code></pre>
<p>Hope it'll be helpful.</p>
| 0 | 2016-09-28T13:03:56Z | [
"python"
]
|
Converting a str to an int | 39,748,223 | <p>My Problem is that the type <code>'ip'</code> is str, but i need integer.</p>
<p>So i did the convert <code>int(ip)</code>. Then i got error </p>
<blockquote>
<p>invalid literal for int() with base 10:</p>
</blockquote>
<p>So i did a little bit of research and found that i had to put int <code>int(float(ip))</code>. </p>
<p>Now i get "could not convert string to float". </p>
<pre><code>import socket
def retrieveBanner(ip, port):
s = socket.socket()
s.connect((int(float(ip)),port))
banner = s.recv(1024).decode()
print("Bitte geben Sie eine IP und ein Port ein")
ip = input("IP? ")
port = input("Port? ")
retrieveBanner(ip, port)
if ("NASFTPD" in banner):
print("Vulnerable")
</code></pre>
| -4 | 2016-09-28T12:56:14Z | 39,748,750 | <p>To convert a dotted notation IP address in a string to an integer you need:</p>
<pre><code>i_ip = socket.inet_aton(ip)
</code></pre>
<p>"aton" is short for "ASCII to number". This is for IPv4 addresses.</p>
| 0 | 2016-09-28T13:19:14Z | [
"python"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.