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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to get dictionary values from list of lists (any language)? | 38,689,547 | <p>I most interested in simplicity, so would appreciate solution in any language (also interesting how it would look using LINQ). I tried to do it in Python, but failed.</p>
<p>From these two lists:</p>
<pre><code>init_li1 = [[234,45,1,86,2,0],[324,6,1],[123,1111,3]]
init_li2 = ["Alpha", "Beta", "Gamma"]
</code></pre>
<p>I would like to get this dictionary:</p>
<pre><code>{"Alpha":[234,45,1,86,2,0], "Beta":[324,6,1], "Gamma":[123,1111,3]}
</code></pre>
| -1 | 2016-08-01T00:27:28Z | 38,689,705 | <p>Since you mentioned LINQ, you could do set something like this in C#:</p>
<pre><code> var list_1 = new List<List<int>>
{
new List<int> { 234, 45, 1, 86, 2, 0 },
new List<int> { 324, 6, 1 },
new List<int> { 123, 1111, 3 }
};
var list_2 = new List<string>
{
"Alpha",
"Beta",
"Gamma"
};
</code></pre>
<p>Then you could pull them into a dictionary like:</p>
<pre><code> var dictionary = new Dictionary<string, List<int>>();
list_2.ForEach(x =>
{
int index = list_2.IndexOf(x);
dictionary.Add(list_2[index], list_1[index]);
});
</code></pre>
<p>Or, in 'query style', maybe something like:</p>
<pre><code> var results = from key in list_2
let index = list_2.IndexOf(key)
let values = string.Join(" ", list_1[index])
select new { Key = key, Values = values };
</code></pre>
<p>Printing out these results with the following should give you what you're after:</p>
<pre><code> foreach (var item in results)
{
Console.WriteLine($"{item.Key} : {item.Values}");
}
</code></pre>
| 0 | 2016-08-01T00:59:34Z | [
"c#",
"python",
"list",
"dictionary"
] |
How to get dictionary values from list of lists (any language)? | 38,689,547 | <p>I most interested in simplicity, so would appreciate solution in any language (also interesting how it would look using LINQ). I tried to do it in Python, but failed.</p>
<p>From these two lists:</p>
<pre><code>init_li1 = [[234,45,1,86,2,0],[324,6,1],[123,1111,3]]
init_li2 = ["Alpha", "Beta", "Gamma"]
</code></pre>
<p>I would like to get this dictionary:</p>
<pre><code>{"Alpha":[234,45,1,86,2,0], "Beta":[324,6,1], "Gamma":[123,1111,3]}
</code></pre>
| -1 | 2016-08-01T00:27:28Z | 38,697,194 | <pre><code>init_li1 = [[234,45,1,86,2,0],[324,6,1],[123,1111,3]]
init_li2 = ["Alpha", "Beta", "Gamma"]
new_dict = {}
for i in range(0, len(init_li1)):
new_dict[init_li2[i]] = init_li1[i]
print new_dict
</code></pre>
| 0 | 2016-08-01T11:03:38Z | [
"c#",
"python",
"list",
"dictionary"
] |
Use xpath and scrapy to go through STIX files? | 38,689,596 | <p>I'm hoping to use scrapy to go through STIX documents, basically setting the documents up like a RSS feed and then 'scraping' through it.
Currently, I'm just using ipython and scrapy shell to get the xpaths. </p>
<pre><code><FileObj:Hashes>
<cyboxCommon:Hash>
<cyboxCommon:Type condition="Equals" xsi:type="cyboxVocabs:HashNameVocab-1.0">MD5</cyboxCommon:Type>
<cyboxCommon:Simple_Hash_Value condition="Equals">C71F2F84500E6AE4485C967F72BB9E52</cyboxCommon:Simple_Hash_Value>
</cyboxCommon:Hash>
</FileObj:Hashes>
</code></pre>
<p>I've 'scrapy' shelled to the page and I'm trying to pull out the md5 hash C71F2F84500E6AE4485C967F72BB9E52, all MD5's on the page are listed just like this. </p>
<p>This is what I've got but I can't get it to work -</p>
<pre><code>response.xpath("//cyboxCommon:Simple_Hash_Value[@condition=&quotEquals&quot]/text()").extract()
</code></pre>
<p>edited below --</p>
<pre><code>response.xpath("//*[@condition='Equals']/text()").extract()
</code></pre>
<p>this gives me all text after this, not just md5 but other STIX info which is close but still doens't work. I'm not sure if this has something to do with the colon's in the names. </p>
<p>I'd appreciate any suggestions, thanks!!!</p>
| 0 | 2016-08-01T00:36:41Z | 38,695,464 | <p>Scrapy Selector (or now Parsel Selector) escapes and cleans up the tags etc when creating a tree for parsing.</p>
<p>In your case the xpath you are looking for is:</p>
<pre><code>response.xpath("//simple_hash_value[@condition='Equals']/text()").extract()
</code></pre>
<p>You can view the cleaned up tree simply with <code>response.extract()</code> to see how your tree looks now.</p>
| 1 | 2016-08-01T09:34:41Z | [
"python",
"xpath",
"scrapy"
] |
Use xpath and scrapy to go through STIX files? | 38,689,596 | <p>I'm hoping to use scrapy to go through STIX documents, basically setting the documents up like a RSS feed and then 'scraping' through it.
Currently, I'm just using ipython and scrapy shell to get the xpaths. </p>
<pre><code><FileObj:Hashes>
<cyboxCommon:Hash>
<cyboxCommon:Type condition="Equals" xsi:type="cyboxVocabs:HashNameVocab-1.0">MD5</cyboxCommon:Type>
<cyboxCommon:Simple_Hash_Value condition="Equals">C71F2F84500E6AE4485C967F72BB9E52</cyboxCommon:Simple_Hash_Value>
</cyboxCommon:Hash>
</FileObj:Hashes>
</code></pre>
<p>I've 'scrapy' shelled to the page and I'm trying to pull out the md5 hash C71F2F84500E6AE4485C967F72BB9E52, all MD5's on the page are listed just like this. </p>
<p>This is what I've got but I can't get it to work -</p>
<pre><code>response.xpath("//cyboxCommon:Simple_Hash_Value[@condition=&quotEquals&quot]/text()").extract()
</code></pre>
<p>edited below --</p>
<pre><code>response.xpath("//*[@condition='Equals']/text()").extract()
</code></pre>
<p>this gives me all text after this, not just md5 but other STIX info which is close but still doens't work. I'm not sure if this has something to do with the colon's in the names. </p>
<p>I'd appreciate any suggestions, thanks!!!</p>
| 0 | 2016-08-01T00:36:41Z | 38,707,488 | <p>OK so apparently STIX has it's own namespace, this particular problem uses this one - </p>
<p>xmlns:cybox="http://cybox.mitre.org/cybox-2" </p>
<p>In order to grab the text from the STIX file I had to use name() or you can use local-name()</p>
<pre><code>response.xpath("//*[name()='cyboxCommon:Simple_Hash_Value']/text()").extract()
</code></pre>
<p>or </p>
<pre><code>response.xpath("//*/*[local-name()='Simple_Hash_Value']/text()").extract()
</code></pre>
<p>But @granitosaurus what if I wanted a compound statement? MD5 and then then has? I can't get this to work... let me know if you need me to open a new question. </p>
<pre><code>response.xpath("//*[name()='cyboxCommon:Type']/[text()='MD5']/following-sibling::[name()='cyboxCommon:Simple_Hash_Value']/text()").extract()
</code></pre>
| 0 | 2016-08-01T20:24:27Z | [
"python",
"xpath",
"scrapy"
] |
2 occurrences of a letter not spotted by indexing | 38,689,653 | <p>I am creating a game of hangman in python 3 and all seems to be working well apart from one part of the game. Take for example, the word 'hello'. Hello contains two 'l's. My game does not recognise that you can have more than one occurrence of a letter in a word and therefore does not update the game as it should. Here is how the program runs -
When entering 'L'</p>
<pre><code>The number of times L occured was 2
('WORD:', 'HEL*O', '; you have ', 10, 'lives left')
Please input a letter:
</code></pre>
<p>(btw I am aware the print is messy and I havent got round to sorting that yet lol)</p>
<p>as you can see, 'L' only allows me to get the one L in Hello and not all of them as you would expect in a game of hangman.</p>
| 0 | 2016-08-01T00:48:13Z | 38,689,691 | <p>I think you're also misunderstanding the second parameter of <a href="https://docs.python.org/2/library/string.html#string.find" rel="nofollow">index</a>, which is the start index to search from, not the nth occurrence to look for. What's happening right now is you're replacing the first "L" twice.</p>
<pre><code>string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.
</code></pre>
<p>Where find says that:</p>
<pre><code>Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end].
</code></pre>
<p>So, you don't need the indcount variable, which is the nth L to find, you need the position of the last found L, plus 1. Replace "indcount" with "pos + 1" so that it searches past the last found occurrence of the letter, and it should work as intended.</p>
| 1 | 2016-08-01T00:57:53Z | [
"python",
"python-3.x",
"indexing"
] |
what is the difference between x[1,2] and x[1][2] in hierarchy indexing for series in python? | 38,689,743 | <p>I have a series </p>
<pre><code>x=pd.Series(np.random.random(16),index=[[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4],['a','b','c','d','a','b','c','d','a','b','c','d','a','b','c','d']])
</code></pre>
<p>that looks like this:</p>
<pre><code>1 a -0.068167
b -1.036551
c -0.246619
d 1.318381
2 a -0.119061
b 0.249653
c 0.819153
d 1.334510
3 a 0.029305
b -0.879798
c 1.081574
d -1.590322
4 a 0.620149
b -2.197523
c 0.927573
d -0.274370
dtype: float64
</code></pre>
<p>What is the difference between x[1,'a'] and x[1]['a']. It gives me the same answer. I am confused as to what the difference internally means? When should I use the above two indexes?</p>
| 4 | 2016-08-01T01:06:15Z | 38,689,978 | <p>This explanation is from the <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html" rel="nofollow">numpy docs</a>, however I believe a similar thing is happening in pandas (which uses numpy inside, using "indexers" to provide a mapping between a (possibly) named index and the underlying integer-based index).</p>
<blockquote>
<p>So note that x[0,2] = x[0][2] though the second case is less efficient as a new temporary array is created after the first index that is subsequently indexed by 2.</p>
</blockquote>
<p>Here are the timings for your series; the first method is around 30 times faster:</p>
<pre><code>In [79]: %timeit x[1, 'a']
100000 loops, best of 3: 8.46 µs per loop
In [80]: %timeit x[1]['a']
1000 loops, best of 3: 274 µs per loop
</code></pre>
| 2 | 2016-08-01T01:49:59Z | [
"python",
"pandas",
"indexing",
"hierarchy"
] |
what is the difference between x[1,2] and x[1][2] in hierarchy indexing for series in python? | 38,689,743 | <p>I have a series </p>
<pre><code>x=pd.Series(np.random.random(16),index=[[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4],['a','b','c','d','a','b','c','d','a','b','c','d','a','b','c','d']])
</code></pre>
<p>that looks like this:</p>
<pre><code>1 a -0.068167
b -1.036551
c -0.246619
d 1.318381
2 a -0.119061
b 0.249653
c 0.819153
d 1.334510
3 a 0.029305
b -0.879798
c 1.081574
d -1.590322
4 a 0.620149
b -2.197523
c 0.927573
d -0.274370
dtype: float64
</code></pre>
<p>What is the difference between x[1,'a'] and x[1]['a']. It gives me the same answer. I am confused as to what the difference internally means? When should I use the above two indexes?</p>
| 4 | 2016-08-01T01:06:15Z | 38,694,236 | <p>In the case of <code>x[1, 'a']</code>, pandas is taking the <code>1, 'a'</code> as a tuple <code>(1, 'a')</code> and returning the series value that corresponds to the <code>(1, 'a')</code> index label.</p>
<p>In the case of <code>x[1]['a']</code>, pandas is figuring out that what you passed within <code>[]</code> is not a tuple in which it can reference it's index with and so finally figures that it may be a reference to an element of the first level. <code>x[1]</code> then returns a cross section of <code>x</code> on which we attempt to slice again with <code>['a']</code>.</p>
| 2 | 2016-08-01T08:31:08Z | [
"python",
"pandas",
"indexing",
"hierarchy"
] |
dataframe slicing and pivoting then into multiple dataframs | 38,689,770 | <p>Ultimately I want to run a parametric var on stock data below</p>
<p>I have data in the form:</p>
<pre><code> Date Symbol ClosingPrice Weight
0 7/22/2016 A 46.58 0.000002
1 7/25/2016 A 46.14 0.000002
2 7/26/2016 A 46.95 0.000002
3 7/27/2016 A 47.26 0.000002
4 7/28/2016 A 47.51 0.000002
5 7/22/2016 AA 10.57 0.000287
6 7/25/2016 AA 10.49 0.000287
7 7/26/2016 AA 10.67 0.000287
8 7/27/2016 AA 10.74 0.000287
9 7/28/2016 AA 10.68 0.000287
10 7/22/2016 AAAP 30.51 0.000003
11 7/25/2016 AAAP 31.02 0.000003
12 7/26/2016 AAAP 30.85 0.000003
13 7/27/2016 AAAP 30.97 0.000003
14 7/28/2016 AAAP 31.00 0.000003
</code></pre>
<p>I would like to create 2 separate dataframes as such:</p>
<pre><code>date A AA AAAP
7/22/2016 46.58 10.57 30.51
7/25/2016 46.14 10.49 31.02
7/26/2016 46.95 10.67 30.85
7/27/2016 47.26 10.74 30.97
7/28/2016 47.51 10.68 31
</code></pre>
<p>with symbols as the column headers </p>
<p>and</p>
<pre><code>Symbol Weight
A 0.00000166
AA 0.00028664
AAAP 0.00000326
</code></pre>
<p>The first dataframe will be used to calculate a variance/co-variance matrix and the second dataframe represents the weights of each security in the stock portfolio (a parameter in the parametric VAR calculation)</p>
| 1 | 2016-08-01T01:10:57Z | 38,689,797 | <p>To get the first table, you can pivot your original data frame to transform it from long to wide format on the first three columns:</p>
<pre><code>import pandas as pd
df.iloc[:,0:3].pivot('Date', 'Symbol', 'ClosingPrice')
# Symbol A AA AAAP
# Date
#7/22/2016 46.58 10.57 30.51
#7/25/2016 46.14 10.49 31.02
#7/26/2016 46.95 10.67 30.85
#7/27/2016 47.26 10.74 30.97
#7/28/2016 47.51 10.68 31.00
</code></pre>
<p>The second table is the unique values of the second and fourth columns, so select them and <code>drop_duplicates</code> should be OK:</p>
<pre><code>df.iloc[:,[1,3]].drop_duplicates()
# Symbol Weight
#0 A 0.000002
#5 AA 0.000287
#10 AAAP 0.000003
</code></pre>
| 3 | 2016-08-01T01:16:32Z | [
"python",
"pandas",
"dataframe",
"pivot",
"slice"
] |
How to write lambda function for counting occurrence in a string in Python sort() | 38,689,777 | <p>I'm trying to write a lambda function (still new to functional programming style of Python). I have a list like this:</p>
<pre><code>cur_list = [b'1z1zzz\r\n', b'1z1z1zzz\r\n', b'1z1z1zzz\r\n', b'zzzz\r\n', b'1zzzz\r\n']
</code></pre>
<p>I want to sort the list by the number of occurrence of '1' in each of them. So in the above list, the correct (sorted) solution would be like this:</p>
<pre><code>cur_list = [b'zzzz\r\n', b'1zzzz\r\n', b'1z1zzz\r\n', b'1z1z1zzz\r\n', b'1z1z1zzz\r\n']
</code></pre>
<p>What lambda function can be inserted into the following snippet of code to efficiently sort by the occurrence of '1' in a given list of string?</p>
<pre><code>cur_list.sort(key=#####what lambda function to insert here)
</code></pre>
<p>Thank you for your answers!</p>
| 0 | 2016-08-01T01:12:26Z | 38,689,780 | <p>That would be:</p>
<pre><code>lambda x: x.count('1')
</code></pre>
<p>Of course, as what you have seems like an array of byte strings, you might want this:</p>
<pre><code>lambda x: x.count(b"1")
</code></pre>
| 3 | 2016-08-01T01:12:56Z | [
"python",
"sorting",
"lambda"
] |
Adding headers to processed dataframe in Panda's | 38,689,999 | <p><a href="http://github.com/ecenm/data/blob/master/sorted.csv.zip" rel="nofollow">Here</a> is my dataset.</p>
<p>I am creating a new pandas dataframe (ptocol) from a previous dataframe (data) using the .groupby and .size methods as shown below. This behaves as expected, however the result is a dataframe with no column headers. </p>
<p>I tried and checked the solution discussed <a href="http://stackoverflow.com/questions/37038733/adding-column-headers-to-new-pandas-dataframe?noredirect=1&lq=1">here</a> for a very long time. But it doesn't work for me. Below is my code.</p>
<pre><code>import pandas as pd
import numpy
data = pd.read_csv('first.csv')
ptocol = data.groupby(["Protocol"], as_index=False).size().rename(columns={0:'NumOfPackets'}) # dosn't work
#ptocol = data.groupby(["Protocol"], as_index=False).count() #doesn't work
print ptocol
ptocol.to_csv('protocol.csv')
</code></pre>
<p><strong>Actual result (protocol.csv):</strong></p>
<pre><code>0x200e,26
ARP,100746
ATMTCP,48
BOOTP,123
BZR,4
...
...
</code></pre>
<p><strong>expected result (protocol.csv):</strong></p>
<pre><code>Protocol,NumOfPackets
0x200e,26
ARP,100746
ATMTCP,48
BOOTP,123
BZR,4
...
...
</code></pre>
<p>Any ideas/suggestion are welcome </p>
| 0 | 2016-08-01T01:53:39Z | 38,690,091 | <p><code>.size()</code> returns a Series object, you can use <code>reset_index()</code> to transform it to a data frame, try this instead:</p>
<pre><code>ptocol = data.groupby("Protocol").size().rename('NumOfPackets').reset_index()
ptocol.to_csv('protocol.cv', index = False)
</code></pre>
<p>This gives something like this, not the same data as yours but the format is what you are looking for:</p>
<pre><code>Symbol,NUM
A,5
AA,5
AAAP,5
</code></pre>
| 0 | 2016-08-01T02:08:46Z | [
"python",
"csv",
"pandas"
] |
python : print the multiple lines on console in place | 38,690,083 | <p>I want to print multiple lines on console in place.
Like this,</p>
<pre><code>AAAAAA
BBBBBB
</code></pre>
<p>But, If I print above the strings using <code>'\r'</code> as below,</p>
<pre><code>for i in range(10):
time.sleep(1)
print("AAAA\r", end='')
time.sleep(1)
print("BBBB\r", end='')
</code></pre>
<p>The final result is just like this </p>
<pre><code> BBBB
</code></pre>
<p>What's happening is <code>AAAA</code>-><code>BBBB</code>-><code>AAAA</code>-><code>BBBB</code>..... and it's not printing like this(IN PLACE!):</p>
<pre><code>AAAA
BBBB
</code></pre>
<p>Not Like this</p>
<pre><code>AAAA
BBBB
AAAA
BBBB
AAAA
BBBB
...
</code></pre>
<p>Is there any solution about this? Please help me</p>
| -1 | 2016-08-01T02:07:40Z | 38,691,134 | <p>is this what you want ..</p>
<pre><code>for i in range(10):
time.sleep(1)
print("AAAAA\n\n")
time.sleep(2)
print("BBBBB\n\n")
</code></pre>
| 0 | 2016-08-01T04:40:07Z | [
"python",
"printing"
] |
Making python text game invalid syntax error | 38,690,094 | <p>Right so I'm creating a text game in python as my first big project, but I'm confused about my syntax. It says invalid syntax, but I can see anything else. all help is appreciated in advance. </p>
<pre><code>def fight(playerhp, a1, a2, a3, a4, run, d1, d2, d3, d4, enemy, edamage, armor, attack, enemytype, reward):
print("OH NO YOUVE ENCOUNTERED " + enemy + "WHAT DO YOU DO?")
time.sleep(1)
while enemy > 0 and playerhp > 0:
attack = input("would you like to " + a1 + a2 + a3 + a4 + "or " + run)
if attack == a1:
enemy = enemy-d1
print("You dealt" + d1 + " damage! the enemy now has " + enemy + "HP!")
elif attack == a2:
enemy = enemy-d2
print("You dealt" + d2 + " damage! the enemy now has " + enemy + "HP!")
elif attack == a3:
enemy = enemy - d3
print("You dealt" + d3 + " damage! the enemy now has " + enemy + "HP!")
elif attack == a4:
enemy = enemy-d4
print("You dealt" + d4 + " damage! the enemy now has " + enemy + "HP!")
print("the " + enemytype + "attacks! It deals " + edamage + " damage! you now have" + playerhp + "health!")
if enemy <=0:
print("the monster was slayn and the guts went everywhere :D. In its carcass you found " + reward + "gold!")
if playerhp <=0:
print("the monster de_stroyed you, and your blood will be painted in its lair.")
Traceback (most recent call last):
File "python", line 38
enemy = enemy - d1
^
SyntaxError: invalid syntax
</code></pre>
| -3 | 2016-08-01T02:09:17Z | 38,690,182 | <p>You have a lot of syntax errors...</p>
<p>First, you forgot to indent all the code after the method definition. Second, you forgot a closing parentheses for this line of code,</p>
<pre><code>attack = input("would you like to " + a1 + a2 + a3 + a4 + "or " + run
</code></pre>
<p>Next, you forgot a colon after this if statement,</p>
<pre><code>if attack == a1
</code></pre>
<p>Then, you forgot a lot of closing double quotes in these lines of code after <code>HP!</code>,</p>
<pre><code>print("You dealt" + d1 + " damage! the enemy now has " + enemy + "HP!)
print("You dealt" + d2 + " damage! the enemy now has " + enemy + "HP!)
print("You dealt" + d3 + " damage! the enemy now has " + enemy + "HP!)
print("You dealt" + d4 + " damage! the enemy now has " + enemy + "HP!)
</code></pre>
<p>Lastly, this line of code is indented one tab too much,</p>
<pre><code>print("the monster de_stroyed you, and your blood will be painted in its lair.")
</code></pre>
<p>So the lesson to be learned here is to be careful and check your code more often. After all the proper indentation is added, it should look like this,</p>
<pre><code>def fight(playerhp, a1, a2, a3, a4, run, d1, d2, d3, d4, enemy, edamage, armor, attack, enemytype, reward):
print("OH NO YOUVE ENCOUNTERED " + enemy + "WHAT DO YOU DO?")
time.sleep(1)
while enemy > 0 and playerhp > 0:
attack = input("would you like to " + a1 + a2 + a3 + a4 + "or " + run)
if attack == a1:
enemy = enemy-d1
print("You dealt" + d1 + " damage! the enemy now has " + enemy + "HP!")
elif attack == a2:
enemy = enemy-d2
print("You dealt" + d2 + " damage! the enemy now has " + enemy + "HP!")
elif attack == a3:
enemy = enemy - d3
print("You dealt" + d3 + " damage! the enemy now has " + enemy + "HP!")
elif attack == a4:
enemy = enemy-d4
print("You dealt" + d4 + " damage! the enemy now has " + enemy + "HP!")
print("the " + enemytype + "attacks! It deals " + edamage + " damage! you now have" + playerhp + "health!")
if enemy <=0:
print("the monster was slayn and the guts went everywhere :D. In its carcass you found " + reward + "gold!")
if playerhp <=0:
print("the monster de_stroyed you, and your blood will be painted in its lair.")
</code></pre>
| 0 | 2016-08-01T02:21:57Z | [
"python"
] |
in selenium can't switch handle new popup layer | 38,690,119 | <p>this is html part. it appear new layer popup in widows.</p>
<pre><code><div style="top: 20px;" id="appInstallSuggestLayer" class="ly_prm_app">
<div class="prm_app_wrap">
<div class="prm_app_header">
<strong class="blind">today news</strong>
</code></pre>
<p>but, it is no iframe name in source and, no windows alert and, </p>
<p>no new windows pop up.</p>
<p>it appear new layer popup over 'mainframe' in browser, but iframe name is no.</p>
<p>so I can't hadle</p>
<p>what can I handle this layer popup??</p>
| 0 | 2016-08-01T02:12:33Z | 38,690,489 | <p>If there is no <code>frame</code> or <code>iframe</code> no need to switch anywhere just need to implement <code>WebDriverWait</code> to wait until popup visible as below :</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
wait = WebDriverWait(driver, 20)
pop_up = wait.until(EC.visibility_of_element_located((By.CLASS_NAME,'prm_app_wrap')))
</code></pre>
<p>Hope it helps...:)</p>
| 1 | 2016-08-01T03:11:45Z | [
"python",
"selenium"
] |
How to handle stdout from command like "with open() as f:" in python | 38,690,201 | <p>I am trying to stream large files over ssh, and can currently stream raw files just fine; as in:</p>
<pre><code>with open('somefile','r') as f:
tx.send(filepath='somefile',stream=f.read())
</code></pre>
<p>tx is a higher level class instance that I have that can stream just fine this way, but I want to be able to use commands like <code>pv</code>, <code>dd</code>, and <code>tar</code> to stream as well. What I need is:</p>
<pre><code>with run_some_command('tar cfv - somefile') as f:
tx.send(filepath='somefile',stream=f.read())
</code></pre>
<p>This would take stdout as a stream and write to a remote file.
I've tried doing something like:</p>
<pre><code>p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE)
tx.send(filepath='somefile',stream=p.stdout.readall())
</code></pre>
<p>but to no avail...
I've been googling for a while trying to find an example, but no luck so far.
Any help would be much appreciated!</p>
| 1 | 2016-08-01T02:25:10Z | 38,690,787 | <p>I think that the only issue is the <code>.readall()</code> method, that does not exist.</p>
<p>You can use <code>p.stdout.read()</code> to read the entire contents of stdout:</p>
<pre><code>p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE)
tx.send(filepath='somefile',stream=p.stdout.read())
</code></pre>
| 0 | 2016-08-01T03:55:59Z | [
"python",
"streaming",
"paramiko"
] |
How to handle stdout from command like "with open() as f:" in python | 38,690,201 | <p>I am trying to stream large files over ssh, and can currently stream raw files just fine; as in:</p>
<pre><code>with open('somefile','r') as f:
tx.send(filepath='somefile',stream=f.read())
</code></pre>
<p>tx is a higher level class instance that I have that can stream just fine this way, but I want to be able to use commands like <code>pv</code>, <code>dd</code>, and <code>tar</code> to stream as well. What I need is:</p>
<pre><code>with run_some_command('tar cfv - somefile') as f:
tx.send(filepath='somefile',stream=f.read())
</code></pre>
<p>This would take stdout as a stream and write to a remote file.
I've tried doing something like:</p>
<pre><code>p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE)
tx.send(filepath='somefile',stream=p.stdout.readall())
</code></pre>
<p>but to no avail...
I've been googling for a while trying to find an example, but no luck so far.
Any help would be much appreciated!</p>
| 1 | 2016-08-01T02:25:10Z | 38,691,396 | <p>I walked back and started with a basic example:</p>
<pre><code>calc_table_file = '/mnt/condor/proteinlab/1468300008.table'
import subprocess
class TarStream:
def open(self,filepath):
p = subprocess.Popen(['tar','cfv','-',filepath], stdout=subprocess.PIPE)
return(p.stdout)
import paramiko
def writer(stream):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('asu-bulk-uspacific', username='labtech', password=password)
client = ssh.open_sftp()
with client.open('/mnt/cold_storage/folding.table','w') as f:
while True:
data = stream.read(32)
if not data:
break
f.write(data)
## works with normal 'open'
with open(calc_table_file,'r') as f:
writer(f)
## and popen :)
tar = TarStream()
writer(tar.open(calc_table_file))
</code></pre>
<p>and it worked! Thanks for the help.</p>
| 0 | 2016-08-01T05:11:03Z | [
"python",
"streaming",
"paramiko"
] |
Python multi-threading/processing module for tasks with dependencies requiring sequencing | 38,690,202 | <p>I'm in the process of implementing a Python module that provides a thread (or process) pool that can handle processing tasks concurrently that are potentially dependent on each other. For example, in the case of an order management system, you could place an order, place another order, cancel the second order, place a third order, and then cancel the first order - all order placements can be processed at the same time, but the cancellations can't happen at the same time as their respective orders and must happen after their order placements are completed. I have come up with a good general purpose solution to problems like this and wanted to use it as my first open source contribution.</p>
<p>Before spending too much time on this I just wanted to know if something like this already exists. Does anyone know of an existing Python package that does this? Would this be useful to anyone?</p>
| 1 | 2016-08-01T02:25:11Z | 38,690,379 | <p>Yes, take a look at <a href="/questions/tagged/dask" class="post-tag" title="show questions tagged 'dask'" rel="tag">dask</a>. It has different schedulers for multithreaded, multiprocessing, and distributed computing which reuse threads and processes through <code>TaskPool</code> and <code>Pool</code> respectively. You can build any task dependencies (direct acyclic graphs - DAGs) with it. Though, I'm not sure about cancellation support but you can implement it manually in your tasks.</p>
| 1 | 2016-08-01T02:54:25Z | [
"python",
"multithreading",
"concurrency",
"dependencies",
"multiprocessing"
] |
Multiple if statement in list comprehension | 38,690,264 | <p>I have a python list that needs to be converted to a tuple, I also need to add a additional check to check the list element type and convert them to tuple</p>
<p>for example:</p>
<pre><code>row_data = ['map',[10,20]]
row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else d if type(d) is list else d for d in row_data)
print row_data
</code></pre>
<p><strong>result
row_data == ('map', [10, 20])</strong></p>
<pre><code>Expected result
row_data == ('map', (10, 20))
</code></pre>
<p>Need to add multiple ifs within the list comprehension and each having its own output.</p>
| 0 | 2016-08-01T02:34:53Z | 38,690,294 | <p>this should work - </p>
<pre><code>row_data = ['map',[10,20]]
row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else tuple(d) if type(d) is list else d for d in row_data)
print(row_data)
Output: ('map', (10, 20))
</code></pre>
| 0 | 2016-08-01T02:39:34Z | [
"python"
] |
React table with django namedtuple returns .map is not a function | 38,690,350 | <p>I want to make a table of with django <code>namedtuple</code> but getting an error. Headers(which is list) works fine though.</p>
<p><code>views.py</code>:</p>
<pre><code>info = [Info(id=5, location_id=861, f=None),Info(id=3, location_id=650, f=None)]
return render('index.html', {'info': info})
</code></pre>
<p><code>index.html</code></p>
<pre><code>var headers = ['id', 'location', 'f']
var Table = React.createClass({
render: function() {
return (
<table className="table-hover">
{this.props.headers.map(function(name, index) {
return <th key={ index }>{name}</th>;
})};
{this.props.tableContent.map(function(row, index) {
<tr key={index}>
return(
{row.map(function(col, i) {
<td key={i}>{col}</td>
})}
);
</tr>
})};
</table>
)
}
});
ReactDOM.render(
<Table headers={headers} tableContent={info}/>,
document.getElementById('content')
);
</code></pre>
<p>I can't see any output and the console says: <code>Uncaught TypeError: this.props.tableContent.map is not a function</code>.</p>
| 0 | 2016-08-01T02:49:28Z | 39,220,837 | <p>I forgot to put <code>safe</code> when receiving the data. To someone who might encounter this problem too. Please refer to <a href="http://stackoverflow.com/questions/4056883/when-should-i-use-escape-and-safe-in-djangos-template-system">this</a> question too</p>
| 0 | 2016-08-30T07:01:10Z | [
"javascript",
"python",
"django",
"reactjs"
] |
Andrews Plot random numbers in corner | 38,690,358 | <p>I am trying trying to plot some country data in an Andrews Plot but the number '1e12' keeps showing up in the top right corner and I have no idea why its there or how to get rid of it. Here is the plot itself: </p>
<p><a href="http://i.stack.imgur.com/6PoTc.png" rel="nofollow"><img src="http://i.stack.imgur.com/6PoTc.png" alt="enter image description here"></a></p>
<p>Here is the code I used to make it, pretty standard Andrews Plot: </p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
from pandas.tools.plotting import radviz
from pandas.tools.plotting import table
from pandas import read_csv
from pandas.tools.plotting import andrews_curves
import os
filepath ="/Users/.../DefenseAndrews.csv"
os.chdir(os.getcwd())
os.getcwd()
dc = read_csv(filepath,
header=0, usecols=['Country','GDP','ME','GE','Trade','PopDensity'])
plt.figure()
andrews_curves(dc, 'Country')
plt.legend(loc='best', bbox_to_anchor=(1.0, 4.3))
plt.savefig('figure4_AndrewsPlot.eps', format='eps', dpi=1200)
plt.show()
</code></pre>
<p>My previous solution was to just open save it and manually erase it in an art program. However, I now have to create the images as a eps file which I can't edit after the fact. Any help or advice would be greatly appreciated. </p>
| 2 | 2016-08-01T02:50:52Z | 38,691,604 | <p>That value is the scale on the axis. You'll have to divide your data by a factor of about 1e11. See the following example with iris data.</p>
<p><a href="https://raw.github.com/pydata/pandas/master/pandas/tests/data/iris.csv" rel="nofollow">iris data linked here</a></p>
<pre><code>from pandas.tools.plotting import andrews_curves
data1 = pd.read_csv('iris.csv')
data2 = data1.copy()
data2.iloc[:, :4] *= 1e11
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
andrews_curves(data1, 'Name', ax=axes[0])
andrews_curves(data2, 'Name', ax=axes[1])
</code></pre>
<p><a href="http://i.stack.imgur.com/uNXSV.png" rel="nofollow"><img src="http://i.stack.imgur.com/uNXSV.png" alt="enter image description here"></a></p>
<p>You'll notice the left chart does not have this scale number while the right chart does. I deliberately multiplied the data charted on the right by a factor of 1e11.</p>
| 2 | 2016-08-01T05:31:29Z | [
"python",
"pandas",
"matplotlib"
] |
Jupyter note matplotlib inline error in Anaconda | 38,690,433 | <p>I launched notebook in Anaconda, and had the code in screenshot. I don't know what's wrong with my code.</p>
<p><a href="http://i.stack.imgur.com/c9qhC.png" rel="nofollow">Link to code</a></p>
| 0 | 2016-08-01T03:03:14Z | 38,690,452 | <p>You need to actually run the first cell. Notebook is essentially a thin wrapper over a Python shell, and by default, it just executes one cell at a time. The <code>[1]</code> indicates that you only ran the second cell.</p>
| 0 | 2016-08-01T03:05:45Z | [
"python",
"python-3.x",
"jupyter-notebook"
] |
Python Openpyxl doesn't write to spreadsheet | 38,690,496 | <p>I'm trying to automate a task where it's get's the users location and turns them to latitude and longitude and write them to spreadsheet which I did. But it doesn't write anything to the spreadsheet. I tried adding the save too, another for loop and even to set it to write only but that didn't workout. Here is my code:</p>
<pre><code># Problem: Get for all locations the latitude and longitude
# Solution: loop through all of them turn them into geolocation values and write them back to spreadsheet. This is the code:
# 1. Import modules
import openpyxl
import os
import geocoder
from openpyxl.workbook import Workbook
# 2. Set up spread sheet
print('Opening workbook...')
wb = openpyxl.load_workbook('/Users/user/Downloads/plswork.xlsx', )
sheet = wb.get_sheet_by_name('results')
sheet = wb.active
# 3. Loop through all data
print('Reading rows...')
for row in range(3, sheet.max_row + 1):
country = sheet['E' + str(row)].value
city = sheet['F' + str(row)].value
both = country + ' ' + city
print both
# 4. Convert into location
g = geocoder.google(both)
location = g.latlng
print location
# 5. Write to spreadsheet
sheet['K' + str(row)] = str(location)
print('Saving...')
wb.save('plswork.xlsx')
print('Saved..')
</code></pre>
<p><a href="http://i.stack.imgur.com/QALo4.png" rel="nofollow"><img src="http://i.stack.imgur.com/QALo4.png" alt="This is the excel spreadsheet. Due to personal data the content is censored!"></a></p>
<p>This is the excel spreadsheet. Due to personal data the content is censored!</p>
| 0 | 2016-08-01T03:13:30Z | 38,690,522 | <p>Can't test this easily, but in the code you posted is the indent on the line below commen '5 Write to spreadsheet' correct? If it is correct then this line isn't in the loop, it is executed only once. I expect you should indent this line so it is in the for loop. </p>
| 2 | 2016-08-01T03:18:29Z | [
"python",
"xlsx",
"openpyxl"
] |
Kivy updating a widget image from outside the function that calls the layout | 38,690,541 | <p>I have a function scope issue. I need to update 'cardTableLayout' when the 'discard' button is pressed, after the evaluate function is called. How do I do this? I know this is a kv layout language issue. I'm not sure how to refrence 'cardTableLayout' from inside 'buttonClick_callback.'
python code
<code></p>
<pre><code>import sys
from os import path, listdir
from random import choice
sys.path.append('libs')
from good_deal import *
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.core.audio import SoundLoader
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.clock import mainthread
randomSong = choice(listdir('music'))
backgroundMusic = SoundLoader.load(path.join('music', randomSong))
backgroundMusic.play()
backgroundMusic.loop = True
cardImagesGlobal = []
hand, deck = deal()
class ScreenManagement(ScreenManager): pass
class Card(ToggleButtonBehavior, Image): pass
class GameButton(Button): pass
def buttonClick_callback(self):
buttonClickSound = SoundLoader.load(path.join('sounds', 'buttonClick.ogg'))
buttonClickSound.play()
index = 0
for items in cardImagesGlobal:
if items.state == 'down':
hand.marked.append(index)
index += 1
discard(hand, deck)
evaluate(hand)
class CardTableScreen(Screen):
@mainthread
def on_enter(self):
global cardImagesGlobal
cardImages = []
self.ids['handType'].text = hand.type
index = 0
for items in hand.ordered:
cardImages.append(Card(source = hand.filenames[index]))
self.ids['handLayout'].add_widget(cardImages[index])
index += 1
cardImagesGlobal = cardImages
discardButton = GameButton(text = 'DISCARD')
discardButton.bind(on_press = buttonClick_callback)
self.ids['cardTableLayout'].add_widget(discardButton)
layoutFile = Builder.load_file('main.kv')
class Main(App):
def build(self):
self.title = 'Good Deal Poker'
return layoutFile
if __name__ == "__main__":
Main().run()
</code></pre>
<p></code>
kv File
<code></p>
<pre><code>ScreenManagement:
CardTableScreen:
<Card>:
size_hint: (.95, .95)
<GameButton>:
size_hint: (.20, .10)
<CardTableScreen>:
name: 'cardTableScreen'
FloatLayout:
name: 'cardTableLayout'
id: cardTableLayout
canvas.before:
Color:
rgba: 0,.25,0,1
Rectangle:
pos: self.pos
size: self.size
Label:
name: 'handType'
id: handType
font_size: '20sp'
pos_hint: {'center_x':.5, 'center_y':.95}
BoxLayout:
size_hint: (1, .30)
pos_hint: {'center_x':.5, 'center_y':.75}
name: 'handLayout'
id: handLayout
orientation: 'horizontal'
canvas.before:
Color:
rgba: 0,.25,0,1
Rectangle:
pos: self.pos
size: self.size
</code></pre>
<p></code></p>
| 0 | 2016-08-01T03:20:59Z | 38,693,781 | <p>The button has been added to the <code>cardTableLayout</code>. On press, it executes a function called <code>buttonClick_callback</code>, passing itself as the first parameter.</p>
<p>This allows to reference the <code>cardTableLayout</code> inside the <code>buttonClick_callback</code> by calling <code>self.parent</code>.</p>
| 0 | 2016-08-01T08:04:06Z | [
"python",
"image",
"layout",
"scope",
"kivy"
] |
Kivy updating a widget image from outside the function that calls the layout | 38,690,541 | <p>I have a function scope issue. I need to update 'cardTableLayout' when the 'discard' button is pressed, after the evaluate function is called. How do I do this? I know this is a kv layout language issue. I'm not sure how to refrence 'cardTableLayout' from inside 'buttonClick_callback.'
python code
<code></p>
<pre><code>import sys
from os import path, listdir
from random import choice
sys.path.append('libs')
from good_deal import *
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.core.audio import SoundLoader
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.clock import mainthread
randomSong = choice(listdir('music'))
backgroundMusic = SoundLoader.load(path.join('music', randomSong))
backgroundMusic.play()
backgroundMusic.loop = True
cardImagesGlobal = []
hand, deck = deal()
class ScreenManagement(ScreenManager): pass
class Card(ToggleButtonBehavior, Image): pass
class GameButton(Button): pass
def buttonClick_callback(self):
buttonClickSound = SoundLoader.load(path.join('sounds', 'buttonClick.ogg'))
buttonClickSound.play()
index = 0
for items in cardImagesGlobal:
if items.state == 'down':
hand.marked.append(index)
index += 1
discard(hand, deck)
evaluate(hand)
class CardTableScreen(Screen):
@mainthread
def on_enter(self):
global cardImagesGlobal
cardImages = []
self.ids['handType'].text = hand.type
index = 0
for items in hand.ordered:
cardImages.append(Card(source = hand.filenames[index]))
self.ids['handLayout'].add_widget(cardImages[index])
index += 1
cardImagesGlobal = cardImages
discardButton = GameButton(text = 'DISCARD')
discardButton.bind(on_press = buttonClick_callback)
self.ids['cardTableLayout'].add_widget(discardButton)
layoutFile = Builder.load_file('main.kv')
class Main(App):
def build(self):
self.title = 'Good Deal Poker'
return layoutFile
if __name__ == "__main__":
Main().run()
</code></pre>
<p></code>
kv File
<code></p>
<pre><code>ScreenManagement:
CardTableScreen:
<Card>:
size_hint: (.95, .95)
<GameButton>:
size_hint: (.20, .10)
<CardTableScreen>:
name: 'cardTableScreen'
FloatLayout:
name: 'cardTableLayout'
id: cardTableLayout
canvas.before:
Color:
rgba: 0,.25,0,1
Rectangle:
pos: self.pos
size: self.size
Label:
name: 'handType'
id: handType
font_size: '20sp'
pos_hint: {'center_x':.5, 'center_y':.95}
BoxLayout:
size_hint: (1, .30)
pos_hint: {'center_x':.5, 'center_y':.75}
name: 'handLayout'
id: handLayout
orientation: 'horizontal'
canvas.before:
Color:
rgba: 0,.25,0,1
Rectangle:
pos: self.pos
size: self.size
</code></pre>
<p></code></p>
| 0 | 2016-08-01T03:20:59Z | 38,708,661 | <p>The problem was in the good_deal lib that was imported. The values being passed in were not updating correctly. Once rectified, the canvas is updating correctly. </p>
| 0 | 2016-08-01T21:47:55Z | [
"python",
"image",
"layout",
"scope",
"kivy"
] |
"which version" output differently with setting version in PyCharm | 38,690,596 | <p>I am using currently the latest version of PyCharm and python 2.7 (Home brew). I set python version in PyCharm like this: </p>
<p><a href="http://i.stack.imgur.com/z5uVT.png" rel="nofollow"><img src="http://i.stack.imgur.com/z5uVT.png" alt="enter image description here"></a></p>
<p>However, when I run codes in the same project: </p>
<p><a href="http://i.stack.imgur.com/zTNJ8.png" rel="nofollow"><img src="http://i.stack.imgur.com/zTNJ8.png" alt="enter image description here"></a></p>
<p>I get output like this:</p>
<p><a href="http://i.stack.imgur.com/TdwCq.png" rel="nofollow"><img src="http://i.stack.imgur.com/TdwCq.png" alt="enter image description here"></a></p>
<p>Why is that? And how can I config the right Python? </p>
<p>Thanks!</p>
| 0 | 2016-08-01T03:30:36Z | 38,690,713 | <p>You shouldn't be using <code>which python</code> to find out which <code>python</code> you're using.
Try this instead:</p>
<pre><code>import sys
print(sys.executable)
</code></pre>
| 1 | 2016-08-01T03:46:24Z | [
"python",
"pycharm"
] |
Script to replace characters in file | 38,690,620 | <p>i'm facing trouble trying to replace characters in a file.</p>
<pre><code> #!/usr/bin/env python
with open("crypto.txt","r") as arquivo:
data = arquivo.read()
for caracter in data:
if "a" in data:
data = data.replace("a","c")
elif "b" in data:
data = data.replace("b","d")
elif "c" in data:
data = data.replace("c","e")
elif "d" in data:
data = data.replace("d","f")
elif "e" in data:
data = data.replace("e","g")
elif "f" in data:
data = data.replace("f","h")
elif "g" in data:
data = data.replace("g","i")
elif "h" in data:
data = data.replace("h","j")
elif "i" in data:
data = data.replace("i","k")
elif "j" in data:
data = data.replace("j","l")
elif "k" in data:
data = data.replace("k","m")
elif "l" in data:
data = data.replace("l","n")
elif "m" in data:
data = data.replace("m","o")
elif "n" in data:
data = data.replace("n","p")
elif "o" in data:
data = data.replace("o","q")
elif "p" in data:
data = data.replace("p","r")
elif "q" in data:
data = data.replace("q","s")
elif "r" in data:
data = data.replace("r","t")
elif "s" in data:
data = data.replace("s","u")
elif "t" in data:
data = data.replace("t","v")
elif "u" in data:
data = data.replace("u","w")
elif "v" in data:
data = data.replace("v","x")
elif "w" in data:
data = data.replace("w","y")
elif "x" in data:
data = data.replace("x","z")
print data
</code></pre>
<p>the script reads a txt file called crypto and start to replace the characters based on the statements above. Inside the file is writed the word aloha.</p>
<p>this is the result i get everytime i run the script</p>
<pre><code>clohc
elohe
glohg
ilohi
iloji
klojk
</code></pre>
<p>how can i fix it?</p>
| 0 | 2016-08-01T03:33:36Z | 38,690,811 | <p>What about python's <a href="https://docs.python.org/3/library/stdtypes.html#str.translate" rel="nofollow"> string translate</a></p>
<pre><code>import string
with open("crypto.txt","r") as arquivo:
data = arquivo.read()
out = data.translate(string.maketrans("abcdefghijklmnopqrstuvw","defghijklmnopqrstuvwxyz"))
print out
</code></pre>
<p>It is directly equlal to perl <code>tr</code> function. It is works as below</p>
<p>Image describes <code>A</code> convert to <code>T</code>, <code>C</code> convert to <code>G</code>, <code>G</code> convert to <code>C</code> and <code>T</code> convert to <code>A</code></p>
<p><a href="http://i.stack.imgur.com/Btr3b.png" rel="nofollow"><img src="http://i.stack.imgur.com/Btr3b.png" alt=""></a> </p>
<blockquote>
<p><strong>Then don't get confuse with string translate and string replace</strong></p>
</blockquote>
<p>string replace, replace the whole word. string translate, replace by the each character. </p>
| 1 | 2016-08-01T03:58:02Z | [
"python"
] |
Updating heroku django deployed site with new commits to github repo | 38,690,635 | <p>Say I have deployed a django website on heroku through a github repository. (For deployment I simply clicked on the deploy button here - <a href="https://github.com/AmmsA/theresumator#theresumator---using-django-resumator" rel="nofollow">https://github.com/AmmsA/theresumator#theresumator---using-django-resumator</a>.) I now update the repository with new commits. </p>
<p>Q: How can I make changes in the deployed website from the repository without losing the data already present on the repository.</p>
| 0 | 2016-08-01T03:35:54Z | 38,690,869 | <p>When you are pushing the fresh commits <code>git push heroku master</code> or via git hook <code>git push origin master</code> -- these nothing to do with heroku database.</p>
<p>But this will run this command when build <code>python manage.py migrate</code> so if you are changed something in the migrations definetly db schema get alter not the values stored in there.</p>
| 1 | 2016-08-01T04:06:00Z | [
"python",
"django",
"heroku",
"github"
] |
Python - Zero-Order Hold Interpolation (Nearest Neighbor) | 38,690,747 | <p>I will be shocked if there isn't some standard library function for this especially in numpy or scipy but no amount of Googling is providing a decent answer.</p>
<p>I am getting data from the Poloniex exchange - cryptocurrency. Think of it like getting stock prices - buy and sell orders - pushed to your computer. So what I have is timeseries of prices for any given market. One market might get an update 10 times a day while another gets updated 10 times a minute - it all depends on how many people are buying and selling on the market.</p>
<p>So my timeseries data will end up being something like:</p>
<pre><code>[1 0.0003234,
1.01 0.0003233,
10.0004 0.00033,
124.23 0.0003334,
...]
</code></pre>
<p>Where the 1st column is the time value (I use Unix timestamps to the microsecond but didn't think that was necessary in the example. The 2nd column would be one of the prices - either the buy or sell prices.</p>
<p>What I want is to convert it into a matrix where the data is "sampled" at a regular time frame. So the interpolated (zero-order hold) matrix would be:</p>
<pre><code>[1 0.0003234,
2 0.0003233,
3 0.0003233,
...
10 0.0003233,
11 0.00033,
12 0.00033,
13 0.00033,
...
120 0.00033,
125 0.0003334,
...]
</code></pre>
<p>I want to do this with any reasonable time step. Right now I use <code>np.linspace(start_time, end_time, time_step)</code> to create the new time vector.</p>
<p>Writing my own, admittedly crude, zero-order hold interpolator won't be that hard. I'll loop through the original time vector and use np.nonzero to find all the indices in the new time vector which fit between one timestamp (t0) and the next (t1) then fill in those indices with the value from time t0.</p>
<p>For now, the crude method will work. The matrix of prices isn't that big. But I have to think there a faster method using one of the built-in libraries. I just can't find it.</p>
<p>Also, for the example above I only use a matrix of Nx2 (column 1: times, column 2: price) but ultimately the market has 6 or 8 different parameters that might get updated. A method/library function that could handled multiple prices and such in different columns would be great.</p>
<p>Python 3.5 via Anaconda on Windows 7 (hopefully won't matter).</p>
<p>TIA</p>
| 3 | 2016-08-01T03:51:46Z | 38,691,043 | <p>For your problem you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow"><code>scipy.interpolate.interp1d</code></a>. It seems to be able to do everything that you want. It is able to do a zero order hold interpolation if you specify <code>kind="zero"</code>. It can also simultaniously interpolate multiple columns of a matrix. You will just have to specify the appropriate <code>axis</code>. <code>f = interp1d(xData, yDataColumns, kind='zero', axis=0)</code> will then return a function that you can evaluate at any point in the interpolation range. You can then get your normalized data by calling <code>f(np.linspace(start_time, end_time, time_step)</code>.</p>
| 4 | 2016-08-01T04:28:31Z | [
"python",
"numpy",
"interpolation"
] |
alternative for python Enum with duplicate values | 38,690,784 | <p>I like Enum a lot and I would like to do the following:</p>
<pre><code>class Color(Enum):
green = 0
red = 1
blue = 1
for color in Color:
print(color.name)
print(color.value)
</code></pre>
<p>As you can see, there are duplicate values in Color class. What class alternative can I use in this case that supports iterable, name, value?</p>
| 2 | 2016-08-01T03:55:42Z | 38,691,346 | <p>Are you asking how you can have <code>Color.red</code> <em>and</em> <code>Color.blue</code> without <code>blue</code> being an alias for <code>red</code>?</p>
<p>If yes, you'll want to use the <a href="https://pypi.python.org/pypi/aenum" rel="nofollow"><code>aenum</code></a> library (built by the author of <a href="https://docs.python.org/3/library/enum.html#module-enum" rel="nofollow"><code>Enum</code></a> and <a href="https://pypi.python.org/pypi/enum34" rel="nofollow">`enum34'</a>) and it would look something like:</p>
<pre><code>from aenum import Enum, NoAlias
# python 3
class Color(Enum, settings=NoAlias):
green = 0
red = 1
blue = 1
# python 2
class Color(Enum):
_settings_ = NoAlias
green = 0
red = 1
blue = 1
</code></pre>
<p>And in use:</p>
<pre><code>for color in Color:
print(color.name)
print(color.value)
# green
# 0
# red
# 1
# blue
# 1
</code></pre>
<p>The downside of using <code>NoAlias</code> is by-value lookups are disabled (you can't do <code>Color(1)</code>).</p>
| 1 | 2016-08-01T05:05:08Z | [
"python",
"enums"
] |
Python Dictionary Returning Only 1 Entry? | 38,690,840 | <p>I've written the following code to print an upper/lower case alphabet dictionary whose values can be shifted by an integer. It keeps returning only one entry (e.g., {Z:z}), even though when I use a print statement in the for loop, I see the entire dictionary printed as expected, no matter what the shift. Any thoughts on why it would only return one entry would be greatly appreciated?</p>
<pre><code>def dictionary(self, shift):
'''
For Caesar cipher.
shift (integer): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
#create empty dictionary
alphaDict = {}
#retrieve alphabet in upper and lower case
letters = string.ascii_lowercase + string.ascii_uppercase
#build dictionary with shift
for i in range(len(letters)):
if letters[i].islower() == True:
alphaDict = {letters[i]: letters[(i + shift) % 26]}
else:
alphaDict = {letters[i]: letters[((i + shift) % 26) + 26]}
return alphaDict
</code></pre>
| 2 | 2016-08-01T04:00:55Z | 38,690,888 | <p>Instead of setting alpha dict to be a new one entry dict with each use, start with an empty dict and add values at the keys you want.</p>
<pre><code>#build dictionary with shift
for i in range(len(letters)):
if letters[i].islower() == True:
alphaDict[letters[i]] = letters[(i + shift) % 26]
else:
alphaDict[letters[i]] = letters[((i + shift) % 26) + 26]
return alphaDict
</code></pre>
| 3 | 2016-08-01T04:08:27Z | [
"python",
"dictionary",
"return",
"caesar-cipher"
] |
Python Dictionary Returning Only 1 Entry? | 38,690,840 | <p>I've written the following code to print an upper/lower case alphabet dictionary whose values can be shifted by an integer. It keeps returning only one entry (e.g., {Z:z}), even though when I use a print statement in the for loop, I see the entire dictionary printed as expected, no matter what the shift. Any thoughts on why it would only return one entry would be greatly appreciated?</p>
<pre><code>def dictionary(self, shift):
'''
For Caesar cipher.
shift (integer): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
#create empty dictionary
alphaDict = {}
#retrieve alphabet in upper and lower case
letters = string.ascii_lowercase + string.ascii_uppercase
#build dictionary with shift
for i in range(len(letters)):
if letters[i].islower() == True:
alphaDict = {letters[i]: letters[(i + shift) % 26]}
else:
alphaDict = {letters[i]: letters[((i + shift) % 26) + 26]}
return alphaDict
</code></pre>
| 2 | 2016-08-01T04:00:55Z | 38,690,907 | <p>You are creating a new dictionary each loop rather than appending it. YOu want to create a new <code>key - value</code> pair for the dictionary each loop. </p>
<pre><code> for i in letters:
if i.islower() == True:
alphaDict[i] = letters[(letters.index(i) + shift) % 26]}
else:
alphaDict[i] = letters[((letters.index(i) + shift) % 26) + 26]}
return alphaDict
</code></pre>
| 3 | 2016-08-01T04:10:50Z | [
"python",
"dictionary",
"return",
"caesar-cipher"
] |
Reconstruct the list of dict in python but the result is not in order | 38,690,905 | <pre><code>list_1 = [{'1': 'name_1', '2': 'name_2', '3': 'name_3',},
{'1': 'age_1', '2': 'age_2' ,'3': 'age_3',}]
</code></pre>
<p>I want to manipulate this list so that the dicts contain all the attributes for a particular ID. The ID itself must form part of the resulting dict. An example output is shown below:</p>
<pre><code>list_2 = [{'id' : '1', 'name' : 'name_1', 'age': 'age_1'},
{'id' : '2', 'name' : 'name_2', 'age': 'age_2'},
{'id' : '3', 'name' : 'name_3', 'age': 'age_3'}]
</code></pre>
<p>Then I did following:</p>
<pre><code>>>> list_2=[{'id':x,'name':list_1[0][x],'age':list_1[1][x]} for x in list_1[0].keys()]
</code></pre>
<p>Then it gives:</p>
<pre><code>>>> list_2
[{'age': 'age_1', 'id': '1', 'name': 'name_1'},
{'age': 'age_3', 'id': '3', 'name': 'name_3'},
{'age': 'age_2', 'id': '2', 'name': 'name_2'}]
</code></pre>
<p>But I don't understand why 'id' is showing in the second position while 'age' showing first?</p>
<p>I tried other ways but the result is the same. Any one can help to figure it out?</p>
| 0 | 2016-08-01T04:10:40Z | 38,691,051 | <p>Try using an OrderedDict:</p>
<pre><code>list_1 = [collections.OrderedDict([('1','name_1'), ('2', 'name_2'), ('3', 'name_3')]),
collections.OrderedDict([('1','age_1'),('2','age_2'),('3', 'age_3')])]
list_2=[collections.OrderedDict([('id',x), ('name',list_1[0][x]), ('age', list_1[1][x])])
for x in list_1[0].keys()]
</code></pre>
<p>This is more likely to preserve the order you want. I am still new to Python, so this may not be super Pythonic, but I think it will work.</p>
<p>output -</p>
<pre><code>In [24]: list( list_2[0].keys() )
Out[24]: ['id', 'name', 'age']
</code></pre>
<p>Docs:
<a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow">https://docs.python.org/3/library/collections.html#collections.OrderedDict</a></p>
<p>Examples:
<a href="https://pymotw.com/2/collections/ordereddict.html" rel="nofollow">https://pymotw.com/2/collections/ordereddict.html</a></p>
<p>Getting the constructors right:
<a href="http://stackoverflow.com/questions/25480089/initializing-an-ordereddict-using-its-constructor">Initializing an OrderedDict using its constructor</a></p>
| 0 | 2016-08-01T04:29:27Z | [
"python",
"list",
"dictionary",
"order"
] |
Reconstruct the list of dict in python but the result is not in order | 38,690,905 | <pre><code>list_1 = [{'1': 'name_1', '2': 'name_2', '3': 'name_3',},
{'1': 'age_1', '2': 'age_2' ,'3': 'age_3',}]
</code></pre>
<p>I want to manipulate this list so that the dicts contain all the attributes for a particular ID. The ID itself must form part of the resulting dict. An example output is shown below:</p>
<pre><code>list_2 = [{'id' : '1', 'name' : 'name_1', 'age': 'age_1'},
{'id' : '2', 'name' : 'name_2', 'age': 'age_2'},
{'id' : '3', 'name' : 'name_3', 'age': 'age_3'}]
</code></pre>
<p>Then I did following:</p>
<pre><code>>>> list_2=[{'id':x,'name':list_1[0][x],'age':list_1[1][x]} for x in list_1[0].keys()]
</code></pre>
<p>Then it gives:</p>
<pre><code>>>> list_2
[{'age': 'age_1', 'id': '1', 'name': 'name_1'},
{'age': 'age_3', 'id': '3', 'name': 'name_3'},
{'age': 'age_2', 'id': '2', 'name': 'name_2'}]
</code></pre>
<p>But I don't understand why 'id' is showing in the second position while 'age' showing first?</p>
<p>I tried other ways but the result is the same. Any one can help to figure it out?</p>
| 0 | 2016-08-01T04:10:40Z | 38,691,099 | <p>To keep the order, you should use an <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow">ordered dictionary</a>. Using your sample:</p>
<pre><code>new_list = [OrderedDict([('id', x), ('name', list_1[0][x]), ('age', list_1[1][x])]) for x in list_1[0].keys()]
</code></pre>
<p>Printing the ordered list...</p>
<pre><code>for d in new_list:
print(d[name], d[age])
</code></pre>
<blockquote>
<p>name_1 age_1 </p>
<p>name_3 age_3</p>
<p>name_2 age_2</p>
</blockquote>
| 1 | 2016-08-01T04:35:43Z | [
"python",
"list",
"dictionary",
"order"
] |
MySQL get multiple items from a table as a input for a single field of another table | 38,690,970 | <p>I have two tables one is teachers another is subjects and I need to link the subjects to the teachers , thats an easy one but the problem is that a single teacher can have multiple subjects.Thus I need a kind of array for that, so that when I do my queries with python it returns an array or should I say a 'tuple of tuple of tuples'. So can someone help me to solve that?</p>
<p>Thanks</p>
| -1 | 2016-08-01T04:20:06Z | 38,691,037 | <p>Database Architecture is most important thing to decide. Here seems 2 approach one is decided by you or other to make a mapping table.</p>
<p>For your Approach:- </p>
<pre><code>id teacher_name Subject
1 XYZ 1,5,6,7
</code></pre>
<p>Query:-</p>
<pre><code>SELECT teacher_name, subject_name
FROM subject s
INNER JOIN teacher t on FIND_IN_SET(s.id,t.subject)
</code></pre>
<p>Other is make a mapping table:-</p>
<pre><code>teacher_id subject_id
1 1
1 5
1 7
</code></pre>
<p>Query:-</p>
<pre><code>SELECT teacher_name, subject_name
FROM mapping m
INNER JOIN subject s on m.subject_id = s.id
INNER JOIN teacher t on m.teacher_id = t.id
</code></pre>
| 1 | 2016-08-01T04:27:34Z | [
"python",
"mysql"
] |
python 3.5 copying excel sheet make loss of data | 38,690,974 | <p>below is the code I<code>m writing. But the result new.xls is broken and images and text in source file hasn</code>t been copied.The source file's text data are not links they are just text values.Is this something I can`t do with it or what?.thanks in advance.
outline of the code is simple.Just coping some sheets and edit some cells, then insert it into another workbook.</p>
<pre><code>def extract_xls():
f=open('extract_sample.txt', 'r', encoding='shift_jis')
lines=f.readlines()
f.close()
old_book=xlrd.open_workbook('./frame.xlsx', on_demand=True)
ob=copy(old_book)
logic_name=''
physical_name=''
return_type=''
sheets=[]
sheets.append(deepcopy(ob.get_sheet(0)))
sheets.append(deepcopy(ob.get_sheet(1)))
sheets.append(deepcopy(ob.get_sheet(2)))
demo_sheet=deepcopy(ob.get_sheet(2))
ind=3
for line in lines:
if len(line) > 1:
ar=line.split(' ')
if len(ar)==3:
logic_name=ar[0]
return_type=ar[1]
physical_name=ar[2]
demo_sheet.set_name(str(ind)+'.'+physical_name)
demo_sheet.write(2, 14, logic_name)
demo_sheet.write(2, 30, logic_name)
ind+=1
sheets.append(demo_sheet)
demo_sheet=deepcopy(ob.get_sheet(2))
lines=None
new_book=xlwt.Workbook()
new_book._Workbook__worksheets=sheets
new_book.save('./new.xls')
</code></pre>
| 0 | 2016-08-01T04:20:16Z | 38,691,244 | <p>Have you tried to make the Excel file a CSV (Comma Separated Values) file?</p>
<p>I can read and write CSV files with Python with no problem - make sure the file is only one Excel sheet (i.e. not multiple Excel sheets).</p>
<p>Maybe this would solve your issue.</p>
| 0 | 2016-08-01T04:53:07Z | [
"python",
"excel",
"copy"
] |
module importing error exclusively when running a file | 38,690,996 | <p>I'm trying to import and use matplotlib.pyplot in a script and I'm getting the following error:</p>
<pre><code> Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
from matplotlib import pyplot as plt
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/pyplot.py", line 36, in <module>
from matplotlib.figure import Figure, figaspect
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/figure.py", line 40, in <module>
from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/__init__.py", line 4, in <module>
from ._subplots import *
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_subplots.py", line 10, in <module>
from matplotlib.axes._axes import Axes
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_axes.py", line 22, in <module>
import matplotlib.dates as _ # <-registers a date unit converter
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/dates.py", line 126, in <module>
from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/dateutil/rrule.py", line 13, in <module>
from fractions import gcd
ImportError: cannot import name 'gcd'
</code></pre>
<p>The weird part is that I can import it just fine if I restart the Python shell and import it directly, but as soon as I try to run my script, even if I run the script and then import it after running the script to generate data, I get the error. The import line, if it matters, is always the same:</p>
<pre><code>import matplotlib
from matplotlib import pyplot
</code></pre>
<p>My script is being run from a folder on my desktop, and I installed matplotlib in terminal with pip3.</p>
| 0 | 2016-08-01T04:23:01Z | 38,691,151 | <p>Your file called <code>fractions.py</code> is shadowing the builtin module of the same name, causing problems when other libraries try to use that library. Name your file something else.</p>
| 2 | 2016-08-01T04:42:26Z | [
"python",
"module"
] |
saving outlook attachments with different names in python | 38,691,009 | <p>I have been trying to save attachments from .msg file into PdF files but with different names. Could anyone please help me out how to proceed further? Here is my code. Error comes on the last line of the code. </p>
<pre><code>import win32com.client
import glob
import os
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
path = "C:\\python\\test-email"
allFiles = glob.glob(path + "/*.msg")
working_path = os.getcwd()
for file in allFiles:
msg = outlook.OpenSharedItem(file)
count_attachments = msg.Attachments.Count
refno_start = text.find('Student ID') + 8
newname = "%s.pdf" % text[refno_start + 2:refno_start + 11]
if count_attachments > 0:
for item in range(count_attachments):
attached = msg.Attachments.Item(item + 1)
attached.SaveAsFile(working_path +'\\'+newname)
</code></pre>
<p>Here is the error messgae:</p>
<pre><code> File "email-reader1.py", line 46, in <module>
attached.SaveAsFile(working_path +'\\'+newname)
File "<COMObject Item>", line 2, in SaveAsFile
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Out look', 'Cannot save the attachment. File name or directory name is not valid.',None, 0, -2147024773), None)
</code></pre>
| -1 | 2016-08-01T04:24:00Z | 38,691,137 | <p>You are getting this error because path you are trying to save to is not valid for Windows. It may contain invalid characters. See <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions" rel="nofollow">this link on MSDN</a> for what is allowed in Windows filenames and paths.</p>
| 1 | 2016-08-01T04:40:37Z | [
"python",
"python-3.x"
] |
Softlayer API -- how to check whether my order is accepted or not | 38,691,032 | <p>I placed a order to upgrade a virtual machine's hardware by api(python) "placeOrder", it returned successfully. And I used "wait_for_transaction"(function in VSManager) to wait this transaction to be finished. After a few minutes, it also returned successfully. However, when I login the website "control.softlayer.com", I found the upgrading ticket showed that it had been cancelled with saying that "XXXX is unable to be completed due to insuffcient resources in the datacenter pool. The upgrade request has been cancelled and this ticket has been closed".</p>
<p>So how could I check this order has been accepted and handled successfully? I need to know the order result.</p>
| 0 | 2016-08-01T04:26:57Z | 38,703,664 | <p>The "wait_for_transaction" function in VSManager only checks if the transaction status is not pending, that's why the result is successful despite a failed transaction.
To verify if the upgrade has effectively worked, is necessary to review the status of the last transaction.</p>
<p>You could review the next example script using the python client:</p>
<pre><code>"""
Retrieve a computing instance's associated upgrade request object if any.
Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getUpgradeRequest
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Upgrade_Request
https://sldn.softlayer.com/article/object-masks
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer
from pprint import pprint as pp
virtualGuestId = 12345678
USERNAME = 'set me'
API_KEY = 'set me'
client = SoftLayer.Client(username=USERNAME,
api_key=API_KEY)
virtualGuestService = client['SoftLayer_Virtual_Guest']
objectMask = 'mask[completedFlag,order,status,ticket[title,id],virtualGuest[id,fullyQualifiedDomainName,lastTransaction[transactionGroup]]]'
try:
upgradeRequest = virtualGuestService.getUpgradeRequest(mask=objectMask, id=virtualGuestId)
# The result should display the upgrade request status, order status, ticket associated
# and the last transaction and transaction status of the current Virtual Guest.
# Note: The upgrade request status could be the next:
# APPROVED
# PENDING
# PENDING_CUSTOMER_APPROVAL
# COMPLETE
# CANCELLED
# MAINTENANCE_UPDATE_REQUIRED
# IN_TRANSACTION
# PENDING_PAYMENT_PROCESS
# PENDING_AUTOMATED_FINALIZE
pp(upgradeRequest)
except SoftLayer.SoftLayerAPIError as e:
pp('Unable to upgrade the VSI faultCode=%s, faultString=%s'
% (e.faultCode, e.faultString))
</code></pre>
| 1 | 2016-08-01T16:23:48Z | [
"python",
"softlayer"
] |
how can I write function with optional output parameters in python | 38,691,069 | <p>how can I write function with optional output parameters.
In example</p>
<p>1) <code>mat = ReadBinFile(filename)</code>
or<br>
2) <code>[mat,titles] = ReadBinFile(filename)</code></p>
<p>if i finished the "ReadBinFile" function with </p>
<pre><code>return mat,titles
</code></pre>
<p>i have a tuple in "mat" in the first example</p>
<p>Thank You for the Help</p>
| 0 | 2016-08-01T04:32:17Z | 38,691,125 | <p>There are two ways to do this. One is to accept an argument that determines the return value. The second, (and more interesting) is to return a generator.</p>
<pre><code>def ReadBinFile(filename):
yield mat
yield titles
mat,titles = ReadBinFile(filename)
</code></pre>
<p>This will let you get only the first or get the first n return values.</p>
| -1 | 2016-08-01T04:39:02Z | [
"python"
] |
how can I write function with optional output parameters in python | 38,691,069 | <p>how can I write function with optional output parameters.
In example</p>
<p>1) <code>mat = ReadBinFile(filename)</code>
or<br>
2) <code>[mat,titles] = ReadBinFile(filename)</code></p>
<p>if i finished the "ReadBinFile" function with </p>
<pre><code>return mat,titles
</code></pre>
<p>i have a tuple in "mat" in the first example</p>
<p>Thank You for the Help</p>
| 0 | 2016-08-01T04:32:17Z | 38,692,659 | <p>You cannot do this without indicating to the function which return type is required, or masking the function name (see my comment). </p>
<p>Let me demonstrate why.</p>
<p>In Perl we can do this, by testing the <em>context</em> of the call. The first (single return value) would be scalar context, and the second in list context. We could test using a function called <code>wantarray</code> (Google "python wantarray" - other search engines are available). Perl, for this reason and many others, is unusual if not unique.</p>
<p>Python doesn't work like that, even though introspection can be taken to extremes compared to other languages. The form of an assignment is:</p>
<pre><code> name = object
</code></pre>
<p>where <code>name</code> is a typeless reference. So:</p>
<pre><code> mat = ReadBinFile(filename)
</code></pre>
<p>Even if, by some sneaky means, we inspected the byte-code, we would have no way of knowing what class of object <code>mat</code> is supposed to reference. A <code>list</code>, a <code>tuple</code>, an <code>int</code>, a <code>bird</code>, a <code>plane</code>?</p>
<p>The syntax you show:</p>
<pre><code>[mat,titles] = ReadBinFile(filename)
</code></pre>
<p>is a puzzle. Although valid, it has no practical difference to:</p>
<pre><code>mat,titles = ReadBinFile(filename)
</code></pre>
<p>which of course is a tuple. So, how can we tell if:</p>
<pre><code>mat = ReadBinFile(filename)
</code></pre>
<p>should be a <code>tuple</code>, a <code>list</code>, or whatever class of object <code>mat</code> is supposed to reference. </p>
<p>After all that, in my opinion returning objects of different classes is a dubious practice, even in Perl. There are a few exceptions, returning <code>None</code> under some circumstances for example. Why dubious? Because the code becomes difficult to read, modify, and support. </p>
| 0 | 2016-08-01T06:54:39Z | [
"python"
] |
Morse code converter looping errors | 38,691,111 | <p>EDIT: Completely fixed now.</p>
<p>EDIT: Okay so now I got it to change '... --- ...' to 'sos' (yippee!) But for some reason, it gives me a KeyError when I input '... --- ... / ... --- ...'.
This should give me 'sos sos' but I get a KeyError for ' '.
I think this is because after the '/', there's a space which the program sees as a trigger to call the dictionary value of the current key. Problem being, the current key at that time is blank since the previous character was the '/'. How would I be able to fix this?
Thanks.</p>
<p>I'm pretty new to programming with python (well, programming in general, really...) and today I had the bright idea of making a morse code converter.</p>
<p>I have the "plain text to morse code" working flawlessly, but the "morse code to plain text"?</p>
<p>Not so much.</p>
<p>The problem is that when I run the program, it doesn't give me anything, it just breaks its loop (like I told it to) without anything coming back to me.</p>
<p>If you guys could help me out, I'd very much appreciate it.</p>
<p>Oh also, 'decoding_dict' is the dictionary which I made which correlates morse code values to plain text.
For example, </p>
<pre><code>decoding_dict = {'...' : 's' , '---' : 'o'}
</code></pre>
<p>And so on and so forth.</p>
<pre><code>def decode(text):
text += ' '
#I have it set up to trigger when there's a space, hence this.
global key
global decoded_text
#I thought maybe this would fix it, it didn't. :(
key = ''
decoded_text = ''
for i in text:
if i == '.':
key += i #This adds a '.' to the key to reference later.
continue
elif i == '-':
key += i #See above comment.
continue
elif i == ' ':
decoded_text += decoding_dict[key]
text = text[(len(key) + 1) :]
key = '' #Calls the value of the key, cuts out the used text, and resets key.
continue
elif i == '/':
decoded_text += decoding_dict['/']
continue #In morse code, a '/' is a ' ' and that's in the dict.
elif text == '':
print "Result: " + decoded_text
break #This is basically the end of the loop
else:
print "Error, please try again."
break
</code></pre>
<p>Now when I run it with '... --- ...' , it goes back to the beginning and doesn't print anything.
(By beginning, I mean the menu I made beforehand.)</p>
| 0 | 2016-08-01T04:36:44Z | 38,691,230 | <p>According to your code try something like this:-</p>
<pre><code>def decode(text):
text += '$'
#I have it set up to trigger when there's a space, hence this.
global key
global decoded_text
#I thought maybe this would fix it, it didn't. :(
key = ''
decoded_text = ''
for i in text:
if i == '.':
key += i #This adds a '.' to the key to reference later.
continue
elif i == '-':
key += i #See above comment.
continue
elif i == ' ':
decoded_text += decoding_dict[key]
text = text[(len(key) + 1) :]
key = '' #Calls the value of the key, cuts out the used text, and resets key.
continue
elif i == '/':
decoded_text += decoding_dict['/']
continue #In morse code, a '/' is a ' ' and that's in the dict.
elif text == '$':
print "Result: " + decoded_text
break #This is basically the end of the loop
else:
print "Error, please try again."
break
</code></pre>
<p>According to My Suggestion Try This:-</p>
<pre><code>def decode(text):
error = False
#I have it set up to trigger when there's a space, hence this.
global key
global decoded_text
#I thought maybe this would fix it, it didn't. :(
key = ''
decoded_text = ''
for i in text:
if i == '.':
key += i #This adds a '.' to the key to reference later.
continue
elif i == '-':
key += i #See above comment.
continue
elif i == ' ':
decoded_text += decoding_dict[key]
text = text[(len(key) + 1) :]
key = '' #Calls the value of the key, cuts out the used text, and resets key.
continue
elif i == '/':
decoded_text += decoding_dict['/']
continue #In morse code, a '/' is a ' ' and that's in the dict.
else:
print "Error, please try again."
error = True
break
else:
If not error:
print "Result: " + decoded_text
</code></pre>
<p>Last else is used with for instead of if else</p>
| 0 | 2016-08-01T04:51:51Z | [
"python",
"loops",
"dictionary"
] |
Morse code converter looping errors | 38,691,111 | <p>EDIT: Completely fixed now.</p>
<p>EDIT: Okay so now I got it to change '... --- ...' to 'sos' (yippee!) But for some reason, it gives me a KeyError when I input '... --- ... / ... --- ...'.
This should give me 'sos sos' but I get a KeyError for ' '.
I think this is because after the '/', there's a space which the program sees as a trigger to call the dictionary value of the current key. Problem being, the current key at that time is blank since the previous character was the '/'. How would I be able to fix this?
Thanks.</p>
<p>I'm pretty new to programming with python (well, programming in general, really...) and today I had the bright idea of making a morse code converter.</p>
<p>I have the "plain text to morse code" working flawlessly, but the "morse code to plain text"?</p>
<p>Not so much.</p>
<p>The problem is that when I run the program, it doesn't give me anything, it just breaks its loop (like I told it to) without anything coming back to me.</p>
<p>If you guys could help me out, I'd very much appreciate it.</p>
<p>Oh also, 'decoding_dict' is the dictionary which I made which correlates morse code values to plain text.
For example, </p>
<pre><code>decoding_dict = {'...' : 's' , '---' : 'o'}
</code></pre>
<p>And so on and so forth.</p>
<pre><code>def decode(text):
text += ' '
#I have it set up to trigger when there's a space, hence this.
global key
global decoded_text
#I thought maybe this would fix it, it didn't. :(
key = ''
decoded_text = ''
for i in text:
if i == '.':
key += i #This adds a '.' to the key to reference later.
continue
elif i == '-':
key += i #See above comment.
continue
elif i == ' ':
decoded_text += decoding_dict[key]
text = text[(len(key) + 1) :]
key = '' #Calls the value of the key, cuts out the used text, and resets key.
continue
elif i == '/':
decoded_text += decoding_dict['/']
continue #In morse code, a '/' is a ' ' and that's in the dict.
elif text == '':
print "Result: " + decoded_text
break #This is basically the end of the loop
else:
print "Error, please try again."
break
</code></pre>
<p>Now when I run it with '... --- ...' , it goes back to the beginning and doesn't print anything.
(By beginning, I mean the menu I made beforehand.)</p>
| 0 | 2016-08-01T04:36:44Z | 38,691,272 | <p>The for loop only considers the initial value of <code>text</code>. Your changes to <code>text</code> in the loop have no effect, because <code>text</code> is a string, and strings are immutable, so your modifications don't modify the original object that you're iterating over. The result is that your loop iterates over all of the original <code>text</code>, completing the loop without ever entering either of your <code>break</code> conditions.</p>
<p>Just get rid of the <code>if text == ''</code> check and move the "print results" line outside the for loop. You don't need to "cut out the used text", because by the time you get to the point where you want to do that, you've already iterated past the entire key. If you just pick up where you left off, you'll begin parsing the next Morse letter on the next loop iteration anyway.</p>
| 0 | 2016-08-01T04:56:58Z | [
"python",
"loops",
"dictionary"
] |
Morse code converter looping errors | 38,691,111 | <p>EDIT: Completely fixed now.</p>
<p>EDIT: Okay so now I got it to change '... --- ...' to 'sos' (yippee!) But for some reason, it gives me a KeyError when I input '... --- ... / ... --- ...'.
This should give me 'sos sos' but I get a KeyError for ' '.
I think this is because after the '/', there's a space which the program sees as a trigger to call the dictionary value of the current key. Problem being, the current key at that time is blank since the previous character was the '/'. How would I be able to fix this?
Thanks.</p>
<p>I'm pretty new to programming with python (well, programming in general, really...) and today I had the bright idea of making a morse code converter.</p>
<p>I have the "plain text to morse code" working flawlessly, but the "morse code to plain text"?</p>
<p>Not so much.</p>
<p>The problem is that when I run the program, it doesn't give me anything, it just breaks its loop (like I told it to) without anything coming back to me.</p>
<p>If you guys could help me out, I'd very much appreciate it.</p>
<p>Oh also, 'decoding_dict' is the dictionary which I made which correlates morse code values to plain text.
For example, </p>
<pre><code>decoding_dict = {'...' : 's' , '---' : 'o'}
</code></pre>
<p>And so on and so forth.</p>
<pre><code>def decode(text):
text += ' '
#I have it set up to trigger when there's a space, hence this.
global key
global decoded_text
#I thought maybe this would fix it, it didn't. :(
key = ''
decoded_text = ''
for i in text:
if i == '.':
key += i #This adds a '.' to the key to reference later.
continue
elif i == '-':
key += i #See above comment.
continue
elif i == ' ':
decoded_text += decoding_dict[key]
text = text[(len(key) + 1) :]
key = '' #Calls the value of the key, cuts out the used text, and resets key.
continue
elif i == '/':
decoded_text += decoding_dict['/']
continue #In morse code, a '/' is a ' ' and that's in the dict.
elif text == '':
print "Result: " + decoded_text
break #This is basically the end of the loop
else:
print "Error, please try again."
break
</code></pre>
<p>Now when I run it with '... --- ...' , it goes back to the beginning and doesn't print anything.
(By beginning, I mean the menu I made beforehand.)</p>
| 0 | 2016-08-01T04:36:44Z | 38,691,302 | <p>Assuming space <code>' '</code> is a separator in the input you specify, you may use this:</p>
<pre><code>decoding_dict = {'...' : 's' , '---' : 'o'}
my_text = '... --- ...'
print(''.join(list(map(lambda x: decoding_dict.get(x, None),
</code></pre>
<hr>
<p>Output:</p>
<hr>
<pre><code>sos
</code></pre>
<p>As for the code above, there are couple of issues:</p>
<ul>
<li>modifying 'text' while iterating over it</li>
<li>checking if text == '', which never happens. Hence, the result is never printed.</li>
</ul>
<p>Try this:</p>
<pre><code>def decode(text):
text += ' '
#I have it set up to trigger when there's a space, hence this.
global key
global decoded_text
#I thought maybe this would fix it, it didn't. :(
key = ''
decoded_text = ''
for i in text:
if i == '.':
key += i #This adds a '.' to the key to reference later.
continue
elif i == '-':
key += i #See above comment.
continue
elif i == ' ':
decoded_text += decoding_dict[key]
key = '' #Calls the value of the key, cuts out the used text, and resets key.
continue
elif i == '/':
decoded_text += decoding_dict['/']
continue #In morse code, a '/' is a ' ' and that's in the dict.
else:
print("Error, please try again.")
break
print("Result: " + decoded_text)
</code></pre>
<hr>
<p>call: <code>decode(my_text)</code>
Output:</p>
<hr>
<pre><code>Result: sos
</code></pre>
| 0 | 2016-08-01T05:00:21Z | [
"python",
"loops",
"dictionary"
] |
"'module' has no attribute" when working with namedtuples | 38,691,198 | <p>I've run into a bit of a wall here, so I'm going to do my best to explain the issue.</p>
<pre><code>def playGames(jobQueue, ...):
....
nextJob = jobQueue.get()
...
def runPool(fens, timesetting, ...):
...
for fen in fens:
jobQueue.put(Job(gamefen=fen, timecontrol=timesetting))
...
if __name__ == '__main__':
Job = collections.namedtuple('Job', 'gamefen timecontrol')
...
...
playGames(jobQueue, ...) # jobQueue is a multiprocess.Queue() object
</code></pre>
<p>After running this, the following error gets thrown.</p>
<pre><code>"'module' object has no attribute 'Job'"
</code></pre>
<p>So I moved the Job = collections... line above the if name==main thing and it worked!</p>
<p>But, the way the code is written without the Job = collections... moved will work perfectly fine, on my Ubuntu system.</p>
<p>So Windows7 using python2.7.8 it does not work
Ubuntu14 using python2.7.6 it does work
Ubuntu14 using python3.4.3 it does work</p>
<p>I must be missing something here...</p>
<p>THE FULL TRACEBACK IS HERE :</p>
<pre><code>Traceback (most recent call last):
File "c:\Python27\lib\multiprocessing\process.py", line 258, in _bootstrap
self.run()
File "c:\Python27\lib\multiprocessing\process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "c:\Users\Andy\Desktop\Github\LucasZinc\Zinc.py", line 338, in play_games
_job = jobQueue.get()
File "c:\Python27\lib\multiprocessing\queues.py", line 117, in get
res = self._recv()
AttributeError: 'module' object has no attribute 'Job'
</code></pre>
| 0 | 2016-08-01T04:47:28Z | 38,691,260 | <p>On Windows, the implementation of multiprocessing places additional constraints on code - effectively what happens is a different python interpreter is started for each process, and then these new interpreters load the python code as non-main - so, to use Job, the non-main processes need to have Job defined outside the <code>if __name__=='__main__'</code> conditional statement. See heading 16.6.3.2 below <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html</a></p>
| 1 | 2016-08-01T04:55:35Z | [
"python",
"collections",
"queue",
"namedtuple"
] |
Python Selenium: How to get updated HTML DOM after scrolling down? | 38,691,218 | <p>I m accessing a <a href="https://steemit.com/trending/funny" rel="nofollow">page</a> which has implemented parallax scrolling. I am using the code to scroll bottom but <code>BeautifulSoup</code> it is not fetching updated DOM. Code is given below:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
from gensim.summarization import summarize
from selenium import webdriver
from datetime import datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from time import sleep
import sys
import os
import xmltodict
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import traceback
import random
driver = None
driver = webdriver.Firefox()
driver.maximize_window()
def fetch_links(tag):
links = []
url = 'https://steemit.com/trending/'+tag
driver.get(url)
html = driver.page_source
sleep(4)
soup = BeautifulSoup(html,'lxml')
entries = soup.select('.entry-title > a')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(5)
entries = soup.select('.entry-title > a')
for e in entries:
if e['href'].strip() not in entries:
links.append(e['href'])
return links
</code></pre>
| 0 | 2016-08-01T04:50:36Z | 38,691,668 | <p>You probably need to parse the page once the window is scrolled:</p>
<pre><code>driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(5)
soup = BeautifulSoup(driver.page_source, 'lxml')
entries = soup.select('.entry-title > a')
</code></pre>
| 1 | 2016-08-01T05:37:42Z | [
"python",
"selenium"
] |
pygame.display.flip - gives this error: "pygame.error: video system not initialized" | 38,691,253 | <p>Hi I need help on Wing IDE 101 because when I try to run my code, the actual program works fine. But after I exit out of it, the shell gives me this error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/kimh2/Desktop/project_1/projectcode_1.py", line 225, in <module>
main()
File "/Users/kimh2/Desktop/project_1/projectcode_1.py", line 223, in <module>
pygame.display.flip()
pygame.error: video system not initialized
</code></pre>
<p>So I was wondering if this is a Wing IDE issue or if there is something wrong with my code. Here is my code:</p>
<pre><code>import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import random
vertices = (
(1, -1, -1),
(1, 1, -1),
(-1, 1, -1),
(-1, -1, -1),
(1, -1, 1),
(1, 1, 1),
(-1, -1, 1),
(-1, 1, 1)
)
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7)
)
surfaces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6)
)
colors = (
(1,0,0),
(0,1,0),
(0,0,1),
(0,1,0),
(1,1,1),
(0,1,1),
(1,0,0),
(0,1,0),
(0,0,1),
(1,0,0),
(1,1,1),
(0,1,1),
)
##ground_vertices = (
## (-10, -1.1, 20),
## (10, -1.1, 20),
## (-10, -1.1, -300),
## (10, -1.1, -300),
## )
##
##
##def ground():
## glBegin(GL_QUADS)
## for vertex in ground_vertices:
## glColor3fv((0,0.5,0.5))
## glVertex3fv(vertex)
##
## glEnd()
def set_vertices(max_distance, min_distance = -20, camera_x = 0, camera_y = 0):
camera_x = -1*int(camera_x)
camera_y = -1*int(camera_y)
x_value_change = random.randrange(camera_x-75,camera_x+75)
y_value_change = random.randrange(camera_y-75,camera_y+75)
z_value_change = random.randrange(-1*max_distance,min_distance)
new_vertices = []
for vert in vertices:
new_vert = []
new_x = vert[0] + x_value_change
new_y = vert[1] + y_value_change
new_z = vert[2] + z_value_change
new_vert.append(new_x)
new_vert.append(new_y)
new_vert.append(new_z)
new_vertices.append(new_vert)
return new_vertices
def Cube(vertices):
glBegin(GL_QUADS)
for surface in surfaces:
x = 0
for vertex in surface:
x+=1
glColor3fv(colors[x])
glVertex3fv(vertices[vertex])
glEnd()
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(vertices[vertex])
glEnd()
def main():
pygame.init()
pygame.mixer.init()
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
pygame.display.set_caption("Cubez!")
max_distance = 120
gluPerspective(45, (display[0]/display[1]), 0.1, max_distance)
glTranslatef(0,0, -40)
x_move = 0
y_move = 0
cur_x = 0
cur_y = 0
game_speed = 1
dir_speed = 1
cube_dict = {}
for x in range(50):
cube_dict[x] =set_vertices(max_distance)
#glRotatef(25, 2, 1, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_move = dir_speed
if event.key == pygame.K_RIGHT:
x_move = -1*dir_speed
if event.key == pygame.K_UP:
y_move = -1*dir_speed
if event.key == pygame.K_DOWN:
y_move = dir_speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_move = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_move = 0
## if event.type == pygame.MOUSEBUTTONDOWN:
## if event.button == 4:
## glTranslatef(0,0,1.0)
##
## if event.button == 5:
## glTranslatef(0,0,-1.0)
x = glGetDoublev(GL_MODELVIEW_MATRIX)
camera_x = x[3][0]
camera_y = x[3][1]
camera_z = x[3][2]
cur_x += x_move
cur_y += y_move
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glTranslatef(x_move,y_move,game_speed)
#ground()
for each_cube in cube_dict:
Cube(cube_dict[each_cube])
for each_cube in cube_dict:
if camera_z <= cube_dict[each_cube][0][2]:
new_max = int(-1*(camera_z-(max_distance*2)))
cube_dict[each_cube] = set_vertices(new_max,int(camera_z-max_distance), cur_x, cur_y)
pygame.display.flip()
main()
pygame.quit()
</code></pre>
| 0 | 2016-08-01T04:54:31Z | 38,810,766 | <p>The error on closing the application has nothing to do with Wing IDE but rather with using OpenGL alongside with pygame, which does not handle OpenGL contexts very well. A fix that I use while working with pygame + pyopengl is the use the sys module to exit the app instead.</p>
<p>The following code reproduces the same error that your code gets on closing the window:</p>
<pre><code>from OpenGL.GL import *
from pygame.locals import *
import pygame
if __name__ == "__main__":
width, height = 550, 400
pygame.init()
pygame.display.set_mode((width, height), DOUBLEBUF|OPENGL)
clock = pygame.time.Clock()
glClear(GL_COLOR_BUFFER_BIT)
glClear(GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
glColor(1, 0, 0)
glBegin(GL_TRIANGLES)
glVertex(0, 0, 0)
glVertex(275, 400, 0)
glVertex(550, 0, 0)
glEnd()
pygame.display.flip()
clock.tick_busy_loop(60)
</code></pre>
<p>But by calling sys.exit() alongside pygame.quit(), the error is suppressed.</p>
<pre><code>from OpenGL.GL import *
from pygame.locals import *
import pygame
import sys#add this!
if __name__ == "__main__":
width, height = 550, 400
pygame.init()
pygame.display.set_mode((width, height), DOUBLEBUF|OPENGL)
clock = pygame.time.Clock()
glClear(GL_COLOR_BUFFER_BIT)
glClear(GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()#add this!
glColor(1, 0, 0)
glBegin(GL_TRIANGLES)
glVertex(0, 0, 0)
glVertex(275, 400, 0)
glVertex(550, 0, 0)
glEnd()
pygame.display.flip()
clock.tick_busy_loop(60)
</code></pre>
| 0 | 2016-08-07T04:02:48Z | [
"python",
"python-3.x",
"pygame",
"pyopengl"
] |
How can I make these two threads run one after the other constantly python? | 38,691,273 | <p>so I have this code where I need these two threads to be run one after the other CONSTANTLY.</p>
<p>So, once thread 1 finishes, thread 2 goes and once thread 2 finishes, then thread 1 goes then thread 2 etc...like constantly as if it's an infinite loop.</p>
<pre><code>import httplib, urllib
import time, sys
import serial
from threading import Thread
#from multiprocessing import Process
key = 'MY API KEY' #API Key required for ThingSpeak.
rfWaterLevelVal = 0 #Global variable that holds the final water level value.
ser = serial.Serial('/dev/ttyUSB0',9600)
#Gathers the rf data received and separated it to obtain the water level data.
def rfWaterLevel():
global rfWaterLevelVal
rfDataArray = ser.readline().strip().split()
print 'incoming: %s' %rfDataArray
if len(rfDataArray) == 5:
rfWaterLevelVal = float(rfDataArray[4])
print 'RFWater Level1: %.3f cm' % (rfWaterLevelVal)
#Created purely to making the multithreading easier.
def rfWaterLevelFinal():
while True:
try:
rfWaterLevel()
except KeyboardInterrupt:
print "caught keyboard interrupt"
sys.exit()
#Sends the sensor data over to ThingSpeak.
def sendData():
global rfWaterLevelVal
params = urllib.urlencode({'field1':rfWaterLevelVal, 'key':key})
headers = {"Content-type" : "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80", timeout = 5)
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()
#Created purely to make multithreading easier.
def sendDataFinal():
while True:
try:
sendDataFinal()
except KeyboardInterrupt:
print "caught keyboard interrupt"
sys.exit()
#start thread 1 for rf water level data.
t1 = Thread(target = rfWaterLevelFinal())
t1.start()
#start thread 2 for sending the data.
t2 = Thread(target = sendDataFinal())
t2.start()
#wait for both threads to finish
t1.join()
t2.join()
</code></pre>
<p>So essentially I need this thread 1 start then finish, thread 2 start then finish, to be constantly run (as if it's in an infinite loop).</p>
<p>I have looked at using a threadpool for this in python but i have no clue how to apply it.</p>
<p>Any ideas on what I could do to get the results that I want?</p>
<p>Cheers
Thanks in Advance!</p>
| 1 | 2016-08-01T04:57:03Z | 38,691,315 | <p>This is what you wanted,</p>
<pre><code>while True:
t1 = Thread(target = rfWaterLevelFinal())
t1.start()
t1.join()
t2 = Thread(target = sendDataFinal())
t2.start()
t2.join()
</code></pre>
<p>But no need to run like that with threads, you can just call the methods.</p>
<pre><code>while True:
rfWaterLevelFinal()
sendDataFinal()
</code></pre>
| 1 | 2016-08-01T05:01:28Z | [
"python",
"multithreading",
"loops",
"raspberry-pi",
"threadpool"
] |
Django authenticate not keeping user logged in | 38,691,374 | <p>I am attempting to learn Django's authentication system by contriving a basic login scenario. My views are set up such that a view, <code>logIn</code>, either receives a user's credentials (and prints the success/failure of the login), or it renders a login form.</p>
<p>A second view, <code>privatePage</code>, is designed as a sanity check that the user is actually logged in. The code is as follows: <br /></p>
<h2><code>views.py</code>:</h2>
<pre><code>@login_required(login_url='/logIn')
def privatePage(request):
return HttpResponse("You're viewing a private page")
@csrf_exempt
def logIn(request):
if request.method == "POST" and \
request.POST.get('email') and \
request.POST.get('password'):
user = authenticate(username=request.POST['email'],
password=request.POST['password'])
return HttpResponse('Valid login' if user is not None else 'Invalid login')
# render login form
return HttpResponse("<form>...</form>")
</code></pre>
<p>I'm finding that after succcessfully logging in via the <code>logIn</code> view, I am still redirected to the login view upon trying to visit <code>privatePage</code>. FYI, I'm attempting to visit the <code>privatePage</code> view directly by URL, as opposed to navigating through provided links (e.g. I'm not sure if I'm violating some CSRF rule). </p>
<p>Any idea what's going on?</p>
| 0 | 2016-08-01T05:07:57Z | 38,691,409 | <p>You've not actually logged in. You need to <em>login</em> the user after verifying their identity with <code>authenticate</code>:</p>
<pre><code>from django.contrib.auth import login
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
</code></pre>
<p><code>login</code> should only be used on users that have been confirmed to exist.</p>
<hr>
<p>What <code>authenticate</code> does:</p>
<blockquote>
<p>verifies a user is who they claim to be</p>
</blockquote>
<p>It does not perform the actual <em>login</em>.</p>
| 4 | 2016-08-01T05:12:18Z | [
"python",
"django",
"authentication",
"web",
"login"
] |
Django authenticate not keeping user logged in | 38,691,374 | <p>I am attempting to learn Django's authentication system by contriving a basic login scenario. My views are set up such that a view, <code>logIn</code>, either receives a user's credentials (and prints the success/failure of the login), or it renders a login form.</p>
<p>A second view, <code>privatePage</code>, is designed as a sanity check that the user is actually logged in. The code is as follows: <br /></p>
<h2><code>views.py</code>:</h2>
<pre><code>@login_required(login_url='/logIn')
def privatePage(request):
return HttpResponse("You're viewing a private page")
@csrf_exempt
def logIn(request):
if request.method == "POST" and \
request.POST.get('email') and \
request.POST.get('password'):
user = authenticate(username=request.POST['email'],
password=request.POST['password'])
return HttpResponse('Valid login' if user is not None else 'Invalid login')
# render login form
return HttpResponse("<form>...</form>")
</code></pre>
<p>I'm finding that after succcessfully logging in via the <code>logIn</code> view, I am still redirected to the login view upon trying to visit <code>privatePage</code>. FYI, I'm attempting to visit the <code>privatePage</code> view directly by URL, as opposed to navigating through provided links (e.g. I'm not sure if I'm violating some CSRF rule). </p>
<p>Any idea what's going on?</p>
| 0 | 2016-08-01T05:07:57Z | 38,704,185 | <p>To keep the user logged in a <code>session</code> must be provided to user with usage of <code>login()</code> method. Login is the process of providing user with a session and <code>authenticate() verifies that the given credentials corresponds to an existing user model object in database</code> . Import django's built in login and authenticate methods <code>from django.contrib.auth import authenticate, login</code>. And then your code looks like </p>
<pre><code>user =authenticate(email, password)
If user:
login(user, request)
</code></pre>
<p>Hope it helps :)</p>
| 0 | 2016-08-01T16:53:46Z | [
"python",
"django",
"authentication",
"web",
"login"
] |
Writing to XMP metadata in python platform agnostic | 38,691,491 | <p>The most common method for writing to XMP metadata in a given file with python appears to be the <code>Python XMP Toolkit</code> <a href="https://github.com/python-xmp-toolkit/python-xmp-toolkit" rel="nofollow">https://github.com/python-xmp-toolkit/python-xmp-toolkit</a></p>
<p>Unfortunately this toolkit doesn't appear to work on Windows (or at least doesn't have very clear instructions as to how to get it to work on Windows). Is there another method to write XMP metadata to a video file with python that will work on both Windows and macOS?</p>
| 0 | 2016-08-01T05:20:31Z | 38,953,626 | <p><a href="http://tilloy.net/dev/pyexiv2/" rel="nofollow">http://tilloy.net/dev/pyexiv2/</a> is now marked obsolete, but it should hopefully work (if <a href="http://www.exiv2.org/" rel="nofollow">http://www.exiv2.org/</a> is also installed).</p>
| 0 | 2016-08-15T10:45:59Z | [
"python",
"python-3.x",
"metadata",
"xmp"
] |
Python: convert 'days since 1990' to datetime object | 38,691,545 | <p>I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10) </p>
<pre><code>time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
</code></pre>
<p>My desired output is a datetime object like so (also GMT +10):</p>
<pre><code>2015-12-01 00:00:00
</code></pre>
<p>I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming). </p>
<pre><code>import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
</code></pre>
<p>Any advice appreciated,
Cheers! </p>
| 2 | 2016-08-01T05:25:22Z | 38,691,649 | <p>The <code>datetime</code> module's <a href="https://docs.python.org/3/library/datetime.html#timedelta-objects" rel="nofollow"><code>timedelta</code></a> is probably what you're looking for.</p>
<p>For example:</p>
<pre><code>from datetime import date, timedelta
days = 9465 # This may work for floats in general, but using integers
# is more precise (e.g. days = int(9465.0))
start = date(1990,1,1) # This is the "days since" part
delta = timedelta(days) # Create a time delta object from the number of days
offset = start + delta # Add the specified number of days to 1990
print(offset) # >>> 2015-12-01
print(type(offset)) # >>> <class 'datetime.date'>
</code></pre>
<p>You can then use and/or manipulate the offset object, or convert it to a string representation however you see fit.</p>
<p>You can use the same format as for this date object as you do for your <code>time_datetime</code>:</p>
<pre><code>print(offset.strftime('%Y-%m-%d %H:%M:%S'))
</code></pre>
<p>Output:</p>
<pre><code>2015-12-01 00:00:00
</code></pre>
<hr>
<p>Instead of using a <code>date</code> object, you could use a <code>datetime</code> object instead if, for example, you were later going to add hours/minutes/seconds/timezone offsets to it.</p>
<p>The code would stay the same as above with the exception of two lines:</p>
<pre><code># Here, you're importing datetime instead of date
from datetime import datetime, timedelta
# Here, you're creating a datetime object instead of a date object
start = datetime(1990,1,1) # This is the "days since" part
</code></pre>
<p><strong>Note:</strong> Although you don't state it, but the other answer suggests you might be looking for <em>timezone aware</em> datetimes. If that's the case, <code>dateutil</code> is the way to go in Python 2 as the other answer suggests. In Python 3, you'd want to use the <code>datetime</code> module's <a href="https://docs.python.org/3/library/datetime.html#datetime.tzinfo" rel="nofollow"><code>tzinfo</code></a>.</p>
| 2 | 2016-08-01T05:36:29Z | [
"python",
"datetime"
] |
Python: convert 'days since 1990' to datetime object | 38,691,545 | <p>I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10) </p>
<pre><code>time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
</code></pre>
<p>My desired output is a datetime object like so (also GMT +10):</p>
<pre><code>2015-12-01 00:00:00
</code></pre>
<p>I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming). </p>
<pre><code>import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
</code></pre>
<p>Any advice appreciated,
Cheers! </p>
| 2 | 2016-08-01T05:25:22Z | 38,691,712 | <p>We can do this in a couple steps. First, we are going to use the <a href="https://dateutil.readthedocs.io/en/latest/" rel="nofollow"><code>dateutil</code></a> library to handle our work. It will make some of this easier.</p>
<p>The first step is to <a class='doc-link' href="http://stackoverflow.com/documentation/python/484/date-and-time/1592/parsing-a-string-into-a-timezone-aware-datetime-object#t=201608010534009420764">get a <code>datetime</code> object from your string</a> (<code>1990-01-01 00:00:00 +10</code>). We'll do that with the following code:</p>
<pre><code>from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateutil.parser
days_since = '1990-01-01 00:00:00 +10'
days_since_dt = dateutil.parser.parse(days_since)
</code></pre>
<p>Now, our <code>days_since_dt</code> will look like this:</p>
<pre><code>datetime.datetime(1990, 1, 1, 0, 0, tzinfo=tzoffset(None, 36000))
</code></pre>
<p>We'll use that in our next step, of determining the new date. We'll use <code>relativedelta</code> in dateutils to handle this math.</p>
<pre><code>new_date = days_since_dt + relativedelta(days=9465.0)
</code></pre>
<p>This will result in your value in <code>new_date</code> having a value of:</p>
<pre><code>datetime.datetime(2015, 12, 1, 0, 0, tzinfo=tzoffset(None, 36000))
</code></pre>
<hr>
<p>This method ensures that the answer you receive continues to be in GMT+10. </p>
| 2 | 2016-08-01T05:42:20Z | [
"python",
"datetime"
] |
Python: convert 'days since 1990' to datetime object | 38,691,545 | <p>I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10) </p>
<pre><code>time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
</code></pre>
<p>My desired output is a datetime object like so (also GMT +10):</p>
<pre><code>2015-12-01 00:00:00
</code></pre>
<p>I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming). </p>
<pre><code>import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
</code></pre>
<p>Any advice appreciated,
Cheers! </p>
| 2 | 2016-08-01T05:25:22Z | 38,698,583 | <p><a href="http://unidata.github.io/netcdf4-python/#netCDF4.num2date" rel="nofollow">netCDF num2date</a> is the correct function to use here:</p>
<pre><code>import netCDF4
ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
</code></pre>
<p>This will convert number of days since 1900-01-01 (i.e. the <code>units</code> of <code>time</code>) to python datetime objects. If <code>time</code> does not have a <code>calendar</code> attribute, you'll need to specify the calendar, or use the default of standard. </p>
| 1 | 2016-08-01T12:13:22Z | [
"python",
"datetime"
] |
how to convert timedelta which is in days into string? | 38,691,701 | <p>I have taken difference between current week start and date week start where date is column of dates. This difference is in days. When I am trying to define function to convert these days into 1 week difference, 2 week difference and so on.</p>
<p>I am getting error as: </p>
<blockquote>
<p>Cannot compare type 'Timedelta' with type 'str'</p>
</blockquote>
<p>Please help me to resolve this. I am worry about am I wrong, in defining function? here is the code which defining function: </p>
<pre><code>def check(diff):
for d in final_data['diff']:
if ((d > '0 days') and (d <= '7 days')):
weekdiff = 'OneWeekDiff'
elif ((d > '8 days') and (d <= '14 days')):
weekdiff = 'TwoWeekDiff'
else:
weekdiff = 'Current Week'
return weekdiff
</code></pre>
<p>To find out difference between two columns, simply I have subtraction like this:
final_data['diff'] = final_data['CurrentWeekStartDay'] - final_data['InvoiceWeekstartDay']</p>
<p>print(final_data['diff']
0 14 days
1 14 days
2 14 days</p>
| 1 | 2016-08-01T05:41:11Z | 38,691,762 | <p>You need convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a> strings <code>0 days</code>, <code>7 days</code>...:</p>
<p>Then I little bit modify function - remove loop and <code>else</code>. You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> function for column of <code>DataFrame</code>:</p>
<pre><code>def check(d):
weekdiff = 'Current Week'
if ((d > pd.to_timedelta('0 days')) and (d <= pd.to_timedelta('7 days'))):
weekdiff = 'OneWeekDiff'
elif ((d > pd.to_timedelta('8 days')) and (d <= pd.to_timedelta('14 days'))):
weekdiff = 'TwoWeekDiff'
return weekdiff
print (final_data['diff'].apply(check))
</code></pre>
<p>Sample:</p>
<pre><code>final_data = pd.DataFrame({'b': {0: pd.Timestamp('2016-01-13 00:00:00'),
1: pd.Timestamp('2016-01-05 00:00:00'),
2: pd.Timestamp('2016-01-03 00:00:00')},
'a': {0: pd.Timestamp('2016-01-01 00:00:00'),
1: pd.Timestamp('2016-01-02 00:00:00'),
2: pd.Timestamp('2016-01-03 00:00:00')},
'diff': {0: pd.Timedelta('12 days 00:00:00'),
1: pd.Timedelta('3 days 00:00:00'),
2: pd.Timedelta('0 days 00:00:00')}})
print (final_data)
a b diff
0 2016-01-01 2016-01-13 12 days
1 2016-01-02 2016-01-05 3 days
2 2016-01-03 2016-01-03 0 days
print (final_data['diff'].apply(check))
0 TwoWeekDiff
1 OneWeekDiff
2 Current Week
Name: diff, dtype: object
</code></pre>
| 1 | 2016-08-01T05:47:27Z | [
"python",
"string",
"pandas",
"dataframe",
"timedelta"
] |
process input image & make duplicate image,& store in another directory | 38,691,888 | <p>i want it to read input image from a directory & make duplicate image and store in another output directory.Now problem is input image,output image and script is in same path.I want input image directory and output image directory</p>
<p>This is what I have so far</p>
<pre><code>import pandas as pd
import os
import shutil
import re
#reads csv
df = pd.read_csv('rosary.csv')
df['Image'] = df.ImageName + "_" + df.ImageWChain + ".jpg"
#checking if column "ImageWChain" has "jpg" extension,then concat .jpg
if ".jpg" not in df.ImageWChain:
df['ImageWChain'] = df.ImageWChain + ".jpg"
if ".jpg" not in df.ImageName:
df['ImageName'] = df.ImageName + ".jpg"
#writes to new csv
df.to_csv('new.csv',index=False)
old_image = df.ImageName
new_image = df.Image
#creates duplicate images with renamed imagename
input_path='D:/New/Input_ImageFolder'
output_path='D:/New/Output_ImageFolder'
input_file=os.path.join(input_path,old_image)
output_file=os.path.join(output_path,new_image)
for old_image, new_image in zip(df.ImageName, df.Image):
shutil.copy2(input_file, output_file)
</code></pre>
| 0 | 2016-08-01T05:59:34Z | 38,692,298 | <p>Instead of copying by shutil.copy2, you have to indicate the input and output file path.</p>
<p>For example you have the paths defined as:</p>
<pre><code>input_path='D:\\New\\Input_ImageFolder\\'
output_path='D:\\New\\Output_ImageFolder\\'
</code></pre>
<p>Next, you have to issue the following codes BEFORE you run the copy command:</p>
<pre><code>input_file=os.path.join(input_path,old_image)
output_file=os.path.join(output_path,new_image)
</code></pre>
<p>Then, you can perform the copy operation as you mentioned:</p>
<pre><code>shutil.copy2(input_file, output_file)
</code></pre>
| 0 | 2016-08-01T06:32:25Z | [
"python"
] |
How to display an error message in mpl_connect() callback function | 38,691,900 | <p>My understanding is that: Normally, when an error happens, it's thrown down through all the calling functions, and then displayed in the console. Now there's some packages that do their own error handling, especially GUI related packages often don't show errors at all but just continue excecution. </p>
<p>How can we override such behaviour in general? When I write GUI functions, I would like to see the errors! I found <a href="http://stackoverflow.com/questions/15246523/handling-exception-in-python-tkinter">this post</a> where it's explained how to do it for the case of Tkinter. How can this be done in Matplotlib?</p>
<p>Example code:</p>
<pre><code>import matplotlib.pyplot as plt
def onclick(event):
print(event.x, event.y)
raise ValueError('SomeError') # this error is thrown but isn't displayed
fig = plt.figure(5)
fig.clf()
try: # if figure was open before, try to disconnect the button
fig.canvas.mpl_disconnect(cid_button)
except:
pass
cid_button = fig.canvas.mpl_connect('button_press_event', onclick)
</code></pre>
| 0 | 2016-08-01T06:01:21Z | 38,950,668 | <p>Indeed, when the python interpreter encounters an exception that is never caught, it will print a so-called traceback to stdout before exciting. However, GUI packages usually catch and swallow all exceptions, in order to prevent the python interpreter from exciting. You would like to display that traceback somewhere, but in case of GUI applications, you will have to decide where to show that traceback. The standard library has a module that helps you working with such traceback, aptly named <a href="https://docs.python.org/3.5/library/traceback.html" rel="nofollow"><code>traceback</code></a>. Then, you will have to catch the exception before the GUI toolkit does it. I do not know a general way to insert a callback error handler, but you can manually add error handling to each of your callbacks. The best way to do this is to write a function decorator that you then apply to your callback.</p>
<pre><code>import traceback, functools
def print_errors_to_stdout(fun):
@functools.wraps(fun)
def wrapper(*args,**kw):
try:
return fun(*args,**kw)
except Exception:
traceback.print_exc()
raise
return wrapper
@print_errors_to_stdout
def onclick(event):
print(event.x, event.y)
raise ValueError('SomeError')
</code></pre>
<p>The decorator <code>print_errors_to_stdout</code> takes a function and returns a new function that embeds the original function in a <code>try ... except</code> block and in case of an exception prints the traceback to stdout with the help of <a href="https://docs.python.org/3.5/library/traceback.html#traceback.print_exc" rel="nofollow"><code>traceback.print_exc()</code></a>. (The wrapper itself is decorated with <a href="https://docs.python.org/3.5/library/functools.html#functools.wraps" rel="nofollow"><code>functools.wraps</code></a> such that the generated wrapper function, among other things, keeps the docstring of the original function). If you would like to show the traceback somewhere else <a href="https://docs.python.org/3.5/library/traceback.html#traceback.format_exc" rel="nofollow"><code>traceback.format_exc()</code></a> would give you a string that you could then show/store somwhere. The decorator also reraises the exception, such that the GUI toolkit still gets a chance to take it's own actions, typically just swallowing the exception.</p>
| 1 | 2016-08-15T07:06:57Z | [
"python",
"matplotlib",
"error-handling"
] |
How to select consecutive rows from a multi-index pandas dataframe? | 38,691,910 | <p>I have a multi-index pandas dataframe (groupbydataframe) as below:</p>
<pre><code>Store Year Month
1 2013 1 4922.0
2 5315.5
3 5603.0
4 4625.0
5 4995.0
6 4407.0
7 4421.0
8 4494.0
9 4212.0
10 4148.5
11 5033.5
12 6111.0
2014 1 4547.5
2 4726.5
3 4455.0
4 4577.5
5 4909.0
6 4788.0
7 4507.0
8 4124.0
9 3970.5
10 4431.0
11 5220.0
12 6466.0
2015 1 4690.0
2 4467.5
3 4294.5
4 4256.0
5 4529.0
6 4102.0
...
1112 2013 2 10991.0
3 12322.0
4 10705.0
5 12096.0
6 11029.0
7 10419.0
8 8994.0
9 9448.0
10 9019.0
11 9294.0
12 11163.0
2014 1 8156.5
2 8862.5
3 8606.5
4 9662.0
5 10375.0
6 8755.0
7 8262.0
8 8454.0
9 7621.5
10 8779.0
11 9638.0
12 9592.0
2015 1 9345.0
2 8466.5
3 8457.0
4 8715.0
5 9125.0
6 8528.0
7 7728.0
</code></pre>
<p>The last column is "Sales". </p>
<ol>
<li>If <code>FindYear=2014</code> and <code>FindMonth=01</code> how do I extract sales for <code>2013-12</code> to <code>2014-02</code> for <code>Store=1</code>?</li>
<li>if <code>FindYear</code> and <code>FindMonth</code> are lists with <code>length(FindYear)=length(Store)</code>. How do do (1) without looping through all stores individually?</li>
<li>Or am I looking at this the wrong way? do I need to <code>unstack()</code> and go from there?</li>
</ol>
| 1 | 2016-08-01T06:01:55Z | 38,693,194 | <p>You can first convert second and third level of <code>Multiindex</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.to_period.html" rel="nofollow"><code>to_period</code></a>:</p>
<pre><code>s = pd.Series({(1, 2013, 2): 5315.5, (1, 2014, 8): 4124.0, (1, 2014, 9): 3970.5, (1112, 2013, 8): 8994.0, (1, 2013, 12): 6111.0, (1, 2015, 3): 4294.5, (1112, 2014, 10): 8779.0, (1, 2014, 10): 4431.0, (1112, 2013, 9): 9448.0, (1112, 2014, 12): 9592.0, (1, 2015, 2): 4467.5, (1, 2014, 11): 5220.0, (1112, 2013, 10): 9019.0, (1, 2015, 1): 4690.0, (1112, 2013, 11): 9294.0, (1112, 2015, 2): 8466.5, (1, 2013, 9): 4212.0, (1112, 2015, 1): 9345.0, (1112, 2013, 4): 10705.0, (1, 2013, 8): 4494.0, (1112, 2014, 9): 7621.5, (1112, 2013, 5): 12096.0, (1, 2014, 4): 4577.5, (1, 2013, 11): 5033.5, (1, 2015, 6): 4102.0, (1112, 2013, 6): 11029.0, (1, 2014, 5): 4909.0, (1, 2013, 10): 4148.5, (1, 2015, 5): 4529.0, (1112, 2014, 8): 8454.0, (1112, 2013, 7): 10419.0, (1, 2014, 6): 4788.0, (1, 2015, 4): 4256.0, (1, 2014, 7): 4507.0, (1112, 2014, 5): 10375.0, (1112, 2015, 3): 8457.0, (1112, 2014, 4): 9662.0, (1, 2013, 5): 4995.0, (1112, 2013, 2): 10991.0, (1, 2014, 1): 4547.5, (1112, 2014, 7): 8262.0, (1, 2013, 4): 4625.0, (1112, 2013, 3): 12322.0, (1, 2014, 2): 4726.5, (1112, 2014, 6): 8755.0, (1, 2013, 7): 4421.0, (1, 2014, 3): 4455.0, (1112, 2014, 1): 8156.5, (1, 2013, 6): 4407.0, (1112, 2014, 11): 9638.0, (1, 2014, 12): 6466.0, (1, 2013, 1): 4922.0, (1112, 2015, 7): 7728.0, (1112, 2013, 12): 11163.0, (1112, 2014, 3): 8606.5, (1112, 2015, 4): 8715.0, (1112, 2014, 2): 8862.5, (1, 2013, 3): 5603.0, (1112, 2015, 6): 8528.0, (1112, 2015, 5): 9125.0})
</code></pre>
<pre><code>per = pd.DatetimeIndex(s.index.map(lambda x: pd.to_datetime(str(x[1])
+ str(x[2]), format='%Y%m')))
.to_period('m')
print (per)
PeriodIndex(['2013-01', '2013-02', '2013-03', '2013-04', '2013-05', '2013-06',
'2013-07', '2013-08', '2013-09', '2013-10', '2013-11', '2013-12',
'2014-01', '2014-02', '2014-03', '2014-04', '2014-05', '2014-06',
'2014-07', '2014-08', '2014-09', '2014-10', '2014-11', '2014-12',
'2015-01', '2015-02', '2015-03', '2015-04', '2015-05', '2015-06',
'2013-02', '2013-03', '2013-04', '2013-05', '2013-06', '2013-07',
'2013-08', '2013-09', '2013-10', '2013-11', '2013-12', '2014-01',
'2014-02', '2014-03', '2014-04', '2014-05', '2014-06', '2014-07',
'2014-08', '2014-09', '2014-10', '2014-11', '2014-12', '2015-01',
'2015-02', '2015-03', '2015-04', '2015-05', '2015-06', '2015-07'],
dtype='int64', freq='M')
</code></pre>
<p>Then assign new <code>Multiindex</code>, where second level is <code>PeriodIndex</code>:</p>
<pre><code>new_index = list(zip(df.index.get_level_values('Store'), per))
s.index = pd.MultiIndex.from_tuples(new_index, names = ('Store','Period'))
print (s)
Store Period
1 2013-01 4922.0
2013-02 5315.5
2013-03 5603.0
2013-04 4625.0
2013-05 4995.0
2013-06 4407.0
2013-07 4421.0
2013-08 4494.0
2013-09 4212.0
2013-10 4148.5
2013-11 5033.5
2013-12 6111.0
2014-01 4547.5
2014-02 4726.5
2014-03 4455.0
...
...
...
</code></pre>
<p>Selecting with <code>loc</code>:</p>
<pre><code>print (s.loc[1,pd.Period('2014-01')])
4547.5
print (s.loc[1,pd.Period('2013-12'):pd.Period('2014-02')])
Store Period
1 2013-12 6111.0
2014-01 4547.5
2014-02 4726.5
Name: Sales, dtype: float64
per1 = pd.Period('2014-01')
per2 = pd.Period('2015-01')
per = [per1, per2]
print (s.loc[1, per1 - 1: per1 + 1])
Store Period
1 2013-12 6111.0
2014-01 4547.5
2014-02 4726.5
Name: Sales, dtype: float64
</code></pre>
<p>Multiple selecting by list comprehension:</p>
<pre><code>print ([s.loc[1, x - 1: x + 1] for x in per])
[Store Period
1 2013-12 6111.0
2014-01 4547.5
2014-02 4726.5
Name: Sales, dtype: float64, Store Period
1 2014-12 6466.0
2015-01 4690.0
2015-02 4467.5
Name: Sales, dtype: float64]
</code></pre>
<p>which can be concated:</p>
<pre><code>print (pd.concat([s.loc[1, x - 1: x + 1] for x in per]))
Store Period
1 2013-12 6111.0
2014-01 4547.5
2014-02 4726.5
2014-12 6466.0
2015-01 4690.0
2015-02 4467.5
Name: Sales, dtype: float64
</code></pre>
| 1 | 2016-08-01T07:29:54Z | [
"python",
"pandas",
"dataframe"
] |
How can I include dependencies from brew in a MacOS X python wheel? | 38,692,003 | <p>I built an application, Caffe, on Mac OS X. It has many dependencies in <code>brew</code>, a common package manager, and the build artifact is an importable Python module.</p>
<p>I believe I can package this module as a wheel, a module package of sorts. But I also want to ship all the dependencies. You can see the main binary dependencies here:</p>
<pre><code>$ otool -L /Users/bberman/Library/Python/2.7/lib/python/site-packages/caffe/_caffe.so
/Users/bberman/Library/Python/2.7/lib/python/site-packages/caffe/_caffe.so:
python/caffe/_caffe.so (compatibility version 0.0.0, current version 0.0.0)
/Users/bberman/Library/Python/2.7/lib/python/site-packages/caffe/libcaffe.so.1.0.0-rc3 (compatibility version 0.0.0, current version 0.0.0)
/System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate (compatibility version 1.0.0, current version 4.0.0)
@rpath/libcudart.7.5.dylib (compatibility version 0.0.0, current version 7.5.27)
@rpath/libcublas.7.5.dylib (compatibility version 0.0.0, current version 7.5.27)
@rpath/libcurand.7.5.dylib (compatibility version 0.0.0, current version 7.5.27)
/usr/local/opt/glog/lib/libglog.0.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/gflags/lib/libgflags.2.dylib (compatibility version 2.0.0, current version 2.1.2)
/usr/local/opt/protobuf/lib/libprotobuf.9.dylib (compatibility version 10.0.0, current version 10.1.0)
/usr/local/opt/boost159/lib/libboost_system.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/boost159/lib/libboost_filesystem.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1226.10.1)
/usr/local/opt/hdf5/lib/libhdf5_hl.10.dylib (compatibility version 11.0.0, current version 11.2.0)
/usr/local/opt/hdf5/lib/libhdf5.10.dylib (compatibility version 12.0.0, current version 12.0.0)
/usr/local/opt/leveldb/lib/libleveldb.1.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/snappy/lib/libsnappy.1.dylib (compatibility version 5.0.0, current version 5.0.0)
/usr/local/opt/lmdb/lib/liblmdb.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/opencv/lib/libopencv_core.2.4.dylib (compatibility version 2.4.0, current version 2.4.13)
/usr/local/opt/opencv/lib/libopencv_highgui.2.4.dylib (compatibility version 2.4.0, current version 2.4.13)
/usr/local/opt/opencv/lib/libopencv_imgproc.2.4.dylib (compatibility version 2.4.0, current version 2.4.13)
/usr/local/opt/boost159/lib/libboost_thread-mt.dylib (compatibility version 0.0.0, current version 0.0.0)
@rpath/libcudnn.5.dylib (compatibility version 0.0.0, current version 5.1.3)
/usr/local/opt/boost-python159/lib/libboost_python.dylib (compatibility version 0.0.0, current version 0.0.0)
/System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.10)
/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
</code></pre>
<p>You can check out those build steps here: <a href="https://gist.github.com/doctorpangloss/f8463bddce2a91b949639522ea1dcbe4" rel="nofollow">https://gist.github.com/doctorpangloss/f8463bddce2a91b949639522ea1dcbe4</a> .</p>
<p>Caffee is a complex library and it's very helpful to use it through the Python module. How could I ship all these pieces in a wheel?</p>
| 0 | 2016-08-01T06:11:15Z | 38,696,495 | <p>If you want to create a standalone executable (out of python project) you might want to use <a href="http://undefined.org/python/#py2app" rel="nofollow">py2app</a>.</p>
<p><a href="https://wiki.python.org/moin/DistributionUtilities" rel="nofollow">Here</a> you can find the documentation for all the Executable Applications
NOTE: py2exe is the same thing for windows </p>
<p>I might misunderstood your question, if so I would like to know :)</p>
| 0 | 2016-08-01T10:26:14Z | [
"python",
"osx",
"machine-learning",
"compilation",
"caffe"
] |
How can I include dependencies from brew in a MacOS X python wheel? | 38,692,003 | <p>I built an application, Caffe, on Mac OS X. It has many dependencies in <code>brew</code>, a common package manager, and the build artifact is an importable Python module.</p>
<p>I believe I can package this module as a wheel, a module package of sorts. But I also want to ship all the dependencies. You can see the main binary dependencies here:</p>
<pre><code>$ otool -L /Users/bberman/Library/Python/2.7/lib/python/site-packages/caffe/_caffe.so
/Users/bberman/Library/Python/2.7/lib/python/site-packages/caffe/_caffe.so:
python/caffe/_caffe.so (compatibility version 0.0.0, current version 0.0.0)
/Users/bberman/Library/Python/2.7/lib/python/site-packages/caffe/libcaffe.so.1.0.0-rc3 (compatibility version 0.0.0, current version 0.0.0)
/System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate (compatibility version 1.0.0, current version 4.0.0)
@rpath/libcudart.7.5.dylib (compatibility version 0.0.0, current version 7.5.27)
@rpath/libcublas.7.5.dylib (compatibility version 0.0.0, current version 7.5.27)
@rpath/libcurand.7.5.dylib (compatibility version 0.0.0, current version 7.5.27)
/usr/local/opt/glog/lib/libglog.0.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/local/opt/gflags/lib/libgflags.2.dylib (compatibility version 2.0.0, current version 2.1.2)
/usr/local/opt/protobuf/lib/libprotobuf.9.dylib (compatibility version 10.0.0, current version 10.1.0)
/usr/local/opt/boost159/lib/libboost_system.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/boost159/lib/libboost_filesystem.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1226.10.1)
/usr/local/opt/hdf5/lib/libhdf5_hl.10.dylib (compatibility version 11.0.0, current version 11.2.0)
/usr/local/opt/hdf5/lib/libhdf5.10.dylib (compatibility version 12.0.0, current version 12.0.0)
/usr/local/opt/leveldb/lib/libleveldb.1.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/snappy/lib/libsnappy.1.dylib (compatibility version 5.0.0, current version 5.0.0)
/usr/local/opt/lmdb/lib/liblmdb.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/opencv/lib/libopencv_core.2.4.dylib (compatibility version 2.4.0, current version 2.4.13)
/usr/local/opt/opencv/lib/libopencv_highgui.2.4.dylib (compatibility version 2.4.0, current version 2.4.13)
/usr/local/opt/opencv/lib/libopencv_imgproc.2.4.dylib (compatibility version 2.4.0, current version 2.4.13)
/usr/local/opt/boost159/lib/libboost_thread-mt.dylib (compatibility version 0.0.0, current version 0.0.0)
@rpath/libcudnn.5.dylib (compatibility version 0.0.0, current version 5.1.3)
/usr/local/opt/boost-python159/lib/libboost_python.dylib (compatibility version 0.0.0, current version 0.0.0)
/System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.10)
/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
</code></pre>
<p>You can check out those build steps here: <a href="https://gist.github.com/doctorpangloss/f8463bddce2a91b949639522ea1dcbe4" rel="nofollow">https://gist.github.com/doctorpangloss/f8463bddce2a91b949639522ea1dcbe4</a> .</p>
<p>Caffee is a complex library and it's very helpful to use it through the Python module. How could I ship all these pieces in a wheel?</p>
| 0 | 2016-08-01T06:11:15Z | 38,838,890 | <p>Adding to Armitage.apk's answer, using py2app an example of how you can actually convert python file to standalone application, this tutorial is great:
<a href="https://www.metachris.com/2015/11/create-standalone-mac-os-x-applications-with-python-and-py2app/" rel="nofollow">https://www.metachris.com/2015/11/create-standalone-mac-os-x-applications-with-python-and-py2app/</a> </p>
| 0 | 2016-08-08T21:36:16Z | [
"python",
"osx",
"machine-learning",
"compilation",
"caffe"
] |
Difficulty parsing text file Python 2.7 | 38,692,160 | <p>Using Python 2.7, I want to take a file as input, remove some charachters from it, and write that to another file.
I'm not entirely succeeding with the below code:</p>
<pre><code>print 'processing .ujc file for transmit'
infile, outfile = open('app_code.ujc','r'), open('app_code_transmit.ujc','w')
data = infile.read()
data = data.replace("#include <avr/pgmspace.h> const unsigned char uj_code[] PROGMEM = {", "")
data = data.replace("0x", "")
data = data.replace(", ", "")
data = data.replace("};", "")
outfile.write(data)
</code></pre>
<p>The input file (example) is:</p>
<pre><code>#include <avr/pgmspace.h>
const unsigned char uj_code[] PROGMEM = {
0x00, 0x03, 0xB1, 0x4B, 0xEC, 0x00, 0x1D, 0x00, 0x1E, 0x00, 0x21, 0x00, 0x02, 0x6A, 0x00, 0x02,
0x6A, 0x00, 0x02, 0xE3, 0x3F, 0x00, 0x1F, 0x00, 0x02, 0x2C, 0x00, 0x01, 0x3B, 0x00, 0x02, 0x36, 0x00, 0x00
};
</code></pre>
<p>And this should become (the etc is a continuation of the above and not actually present):</p>
<pre><code>0003B14BEC001D001E002100026A00(...etc...)02360000
</code></pre>
<p>What I get with the above code is:</p>
<pre><code>#include <avr/pgmspace.h>
const unsigned char uj_code[] PROGMEM = {
0003B14BEC001D001E002100026A00(...etc...)
02360000
</code></pre>
<p>In other words, I want to remove all character, empty lines, and 0x and stuff except the actual bytes in a single continuous line but I'm tripping a little bit on the nuances, I'm expecting. Any help?</p>
| 0 | 2016-08-01T06:22:43Z | 38,692,392 | <p>@MKesper is right. When you read the file, there are \n or \r\n (line separators) depending on your OS. Looking at the expected output, I feel the better way would be to extract the data you need rather than delete the unwanted data. I would take some help from regular expression and here is my attempt:</p>
<pre><code>import re
print 'processing .ujc file for transmit'
infile, outfile = open('app_code.ujc','r'), open('app_code_transmit.ujc','w')
data = infile.read()
# Expect 0003B14BEC001D001E002100026A00026A0002E33F001F00022C00013B0002360000 to be the output
outfile.write(''.join(re.findall('0x([0-9a-fA-F][0-9a-fA-F])', data)))
</code></pre>
<p>Update 1: This is based on assumption that you do not have any other 0x. Else we need to update our regular expression</p>
| 1 | 2016-08-01T06:37:40Z | [
"python",
"python-2.7",
"file",
"parsing"
] |
Difficulty parsing text file Python 2.7 | 38,692,160 | <p>Using Python 2.7, I want to take a file as input, remove some charachters from it, and write that to another file.
I'm not entirely succeeding with the below code:</p>
<pre><code>print 'processing .ujc file for transmit'
infile, outfile = open('app_code.ujc','r'), open('app_code_transmit.ujc','w')
data = infile.read()
data = data.replace("#include <avr/pgmspace.h> const unsigned char uj_code[] PROGMEM = {", "")
data = data.replace("0x", "")
data = data.replace(", ", "")
data = data.replace("};", "")
outfile.write(data)
</code></pre>
<p>The input file (example) is:</p>
<pre><code>#include <avr/pgmspace.h>
const unsigned char uj_code[] PROGMEM = {
0x00, 0x03, 0xB1, 0x4B, 0xEC, 0x00, 0x1D, 0x00, 0x1E, 0x00, 0x21, 0x00, 0x02, 0x6A, 0x00, 0x02,
0x6A, 0x00, 0x02, 0xE3, 0x3F, 0x00, 0x1F, 0x00, 0x02, 0x2C, 0x00, 0x01, 0x3B, 0x00, 0x02, 0x36, 0x00, 0x00
};
</code></pre>
<p>And this should become (the etc is a continuation of the above and not actually present):</p>
<pre><code>0003B14BEC001D001E002100026A00(...etc...)02360000
</code></pre>
<p>What I get with the above code is:</p>
<pre><code>#include <avr/pgmspace.h>
const unsigned char uj_code[] PROGMEM = {
0003B14BEC001D001E002100026A00(...etc...)
02360000
</code></pre>
<p>In other words, I want to remove all character, empty lines, and 0x and stuff except the actual bytes in a single continuous line but I'm tripping a little bit on the nuances, I'm expecting. Any help?</p>
| 0 | 2016-08-01T06:22:43Z | 38,692,393 | <p>Your input file is split on multiple lines and you are after a single line output.</p>
<p>You simply need to strip any newline characters before writing:</p>
<pre><code>data.strip("\n")
</code></pre>
| 1 | 2016-08-01T06:37:47Z | [
"python",
"python-2.7",
"file",
"parsing"
] |
How to make function from a list of tuples in Python? | 38,692,371 | <p>I'd like to make a function using the list of tuples, from the first element to the second element,</p>
<pre><code>Tuplelist = [(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)]
</code></pre>
<p>I want the following result :</p>
<pre><code>func(1)=17
func(2)=13
func(3)=17
func(4)=4
...
</code></pre>
<p>It seems easy but I can't find relevant questions in the web.
Thanks in advance!</p>
| -5 | 2016-08-01T06:36:22Z | 38,692,455 | <pre><code>def func(item):
return dict(Tuplelist)[item]
</code></pre>
<p>or better, if you do not want to create the dictionary every time you call the function,</p>
<pre><code>dictTuplelist = dict(Tuplelist)
def func(item):
return dictTuplelist[item]
print func(1), func(2), func(3)
# 17 13 17
</code></pre>
| 1 | 2016-08-01T06:42:12Z | [
"python",
"function",
"tuples"
] |
How to make function from a list of tuples in Python? | 38,692,371 | <p>I'd like to make a function using the list of tuples, from the first element to the second element,</p>
<pre><code>Tuplelist = [(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)]
</code></pre>
<p>I want the following result :</p>
<pre><code>func(1)=17
func(2)=13
func(3)=17
func(4)=4
...
</code></pre>
<p>It seems easy but I can't find relevant questions in the web.
Thanks in advance!</p>
| -5 | 2016-08-01T06:36:22Z | 38,692,716 | <p>if that is all the values-result that you are going to handle, then a <a href="https://docs.python.org/3/library/stdtypes.html#typesmapping" rel="nofollow">dictionary</a> is what you need</p>
<pre><code>>>> Tuplelist = [(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)]
>>> my_map = dict(Tuplelist)
>>> my_map[1]
17
>>> my_map[5]
12
>>> my_map[23]
39
</code></pre>
<p>if you want to make a function of it is a simple as</p>
<pre><code>def my_fun(key):
return dict(Tuplelist)[key]
</code></pre>
<p>or some other variation like</p>
<pre><code>def my_fun(key):
Tuplelist = dict([(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)] )
return Tuplelist[key]
</code></pre>
<p>or </p>
<pre><code>MyValues = dict([(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)] )
def my_fun(key):
return MyValues[key]
</code></pre>
<p>anyway if that is all you need, I would use the dictionary directly rather that making a function that do the same in a more limiting way.</p>
<p>You can also do a simple linear search in the list, but this lose in the speed that a dictionary offer</p>
<pre><code>Tuplelist = [(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)]
def my_func(key):
for k,v in Tuplelist:
if k == key:
return v
</code></pre>
| 0 | 2016-08-01T06:58:46Z | [
"python",
"function",
"tuples"
] |
Python Cannot find file although the error says it exists | 38,692,487 | <p>I have been trying to load the files in python but somehow I cant do so? any help or suggestions would be really helpful.</p>
<pre><code>import numpy as np
import pandas as pd
df=pd.read_csv('C:/Users/user/Desktop/Work/a.csv')
type(df)
print df
</code></pre>
<p>Error shown:</p>
<pre><code>File C:/Users/user/Desktop/Work/a.csv does not exist
</code></pre>
| -4 | 2016-08-01T06:44:11Z | 38,692,791 | <p>Seems like you are using windows. Windows directory separator is <code>\</code> not <code>/</code>
try this way:</p>
<pre><code>df=pd.read_csv('C:\\Users\\user\\Desktop\\Work\\a.csv')
</code></pre>
<p>or </p>
<pre><code>import os
file_path = os.path.sep.join(["C:", "Users", "user", "Desktop", "Work", "a.csv"])
df = pd.read_csv(file_path)
</code></pre>
| 0 | 2016-08-01T07:04:34Z | [
"python"
] |
what is the difference between fit_transform and transform in sklearn countvectorizer? | 38,692,520 | <p><em>i have just started learning random forest , so if this sounds stupid i am very sorry for it</em></p>
<p>I was recently practicing <a href="https://www.kaggle.com/c/word2vec-nlp-tutorial/details/part-1-for-beginners-bag-of-words" rel="nofollow">bag of words introduction : kaggle</a> , i want to clear few things : </p>
<p><strong>using vectorizer.fit_transform( " * on the list of <em>cleaned</em> reviews* " )</strong></p>
<p>Now when we were preparing the bag of words array on train reviews we used <strong><em>fit_predict</em></strong> on the list of train reviews , now i know that fit_predict does two things , > first it fits on the data and knows the <strong>vocabulary</strong> and then it makes vectors on each review . </p>
<p>thus when we used <strong>vectorizer.transform( "<em>list of cleaned train reviews</em> " )</strong> this just transform the list of test reviews into the vector for each review . </p>
<p>my question is ..... why not use <strong>fit_transform</strong> on the test list too !! i mean in the documents it says it leads to <em>overfitting</em> , but wait it does makes sense to me to use it anyways , let me give you my prospective : </p>
<p>when we don't use fit_transform we are essentially saying to make feature vector of test reviews using the most frequent words of train reviews !! Why not make test features array using the most frequent words in the test inself ? </p>
<p>i mean does random cares ? if we give random forest <strong>the train feature array and train feature sentiment</strong> to work and train itself with and then give it the <strong>test</strong> <strong>feature array</strong> won't it just give its prediction on sentiment.</p>
<p>note : i may not have asked in the right way but as you people attempt to answer i will update the question to be more clear .. </p>
| 1 | 2016-08-01T06:46:27Z | 38,709,963 | <p>You do not do a <code>fit_transform</code> on the test data because, when you fit a Random Forest, the Random Forest learns the classification rules based on the values of the features that you provide it. If these rules are to be applied to classify the test set then you need to make sure that the test features are calculated in the same way using the same vocabulary. If the vocabulary of the training and the test features is different, then features will not really make sense as they will reflect a vocabulary that is separate from the one the document was trained on.</p>
<p>Now if we specifically talk about <code>CountVectorizer</code>, then consider the following example, let your training data have the following 3 sentences:</p>
<ol>
<li>Dog is black.</li>
<li>Sky is blue.</li>
<li>Dog is dancing.</li>
</ol>
<p>Now the vocabulary set for this will be {Dog, is, black, sky, blue, dancing}. Now the Random Forest that you will train will try to learn rules based on the count of these 6 vocabulary terms. So your features will be vector of length 6. Now if the test set is as follows:</p>
<ol>
<li>Dog is white.</li>
<li>Sky is black.</li>
</ol>
<p>Now if you use the test data for fit_transform your vocabulary will look like {Dog, white, is, Sky, black}. So here your each document will be represented by a vector of length 5 denoting the counts of each of these terms. Now, this will be like comparing apples with oranges. You learn rules for counts of the previous vocabulary and those rules can not be applied to this vocabulary. This is the reason why you only <code>fit</code> on the training data.</p>
<p>Hope that helps!</p>
| 0 | 2016-08-02T00:20:17Z | [
"python",
"scikit-learn",
"tokenize",
"random-forest"
] |
Python generating xml file by python | 38,692,544 | <p>The image below is the result of performance testing. One of my issue is: How can I transfer my result into a XML file? </p>
<p><a href="http://i.stack.imgur.com/J7PSu.png" rel="nofollow"><img src="http://i.stack.imgur.com/J7PSu.png" alt="testdata"></a></p>
<p>I've been trying file writing method. But what if the data I need to parse is massive? Is there a method or plugin to done it with a smarter way?</p>
<p>My code so far:</p>
<pre><code>def generate_xml(jank_perc):
with open('jankyresult.xml','a') as f:
f.write('<?xml version="1.0" ?>\n')
f.write("<root>\n")
f.write(" <doc>\n")
f.write(" <Jankyframes>" + jank_perc + '%' + "</Jankyframes>\n")
f.write(" </doc>\n")
f.write("</root>\n")
</code></pre>
<p>I don't want to create manually. I hope there is a smarter way to do it. Thanks for answering!</p>
| 1 | 2016-08-01T06:47:40Z | 38,692,683 | <p>Have a look at the <a href="https://pypi.python.org/pypi/yattag/" rel="nofollow">yattag</a> library:</p>
<blockquote>
<p>Generate HTML or XML in a pythonic way. Pure python alternative to web template engines.Can fill HTML forms with default values and error messages.</p>
</blockquote>
<p>Here's an example based on your code sample:</p>
<pre><code>doc, tag, text = Doc().tagtext()
doc.asis('<?xml version="1.0"?>')
with tag('root'):
with tag('doc'):
with tag('Jankyframes'):
text(jank_perc + '%')
with open('jankyresult.xml','a') as f:
f.write(doc.getvalue())
</code></pre>
<p>Depending on how you get your input data (e.g. a <code>list</code> or <code>dict</code>), you could iterate over it and write your results to the XML while still keeping the code readable.</p>
| 0 | 2016-08-01T06:56:16Z | [
"python",
"xml",
"python-2.7",
"xml-parsing",
"ipython"
] |
Python generating xml file by python | 38,692,544 | <p>The image below is the result of performance testing. One of my issue is: How can I transfer my result into a XML file? </p>
<p><a href="http://i.stack.imgur.com/J7PSu.png" rel="nofollow"><img src="http://i.stack.imgur.com/J7PSu.png" alt="testdata"></a></p>
<p>I've been trying file writing method. But what if the data I need to parse is massive? Is there a method or plugin to done it with a smarter way?</p>
<p>My code so far:</p>
<pre><code>def generate_xml(jank_perc):
with open('jankyresult.xml','a') as f:
f.write('<?xml version="1.0" ?>\n')
f.write("<root>\n")
f.write(" <doc>\n")
f.write(" <Jankyframes>" + jank_perc + '%' + "</Jankyframes>\n")
f.write(" </doc>\n")
f.write("</root>\n")
</code></pre>
<p>I don't want to create manually. I hope there is a smarter way to do it. Thanks for answering!</p>
| 1 | 2016-08-01T06:47:40Z | 38,692,704 | <p>Use this <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a>. An example of it is,</p>
<pre><code>from xml.etree import ElementTree, cElementTree
from xml.dom import minidom
root = ElementTree.Element('root')
child1 = ElementTree.SubElement(root, 'doc')
child1_1 = ElementTree.SubElement(child1, 'Jankyframes')
child1_1.text = jank_perc
print ElementTree.tostring(root)
tree = cElementTree.ElementTree(root) # wrap it in an ElementTree instance, and save as XML
t = minidom.parseString(ElementTree.tostring(root)).toprettyxml() # Since ElementTree write() has no pretty printing support, used minidom to beautify the xml.
tree1 = ElementTree.ElementTree(ElementTree.fromstring(t))
tree1.write("filename.xml",encoding='utf-8', xml_declaration=True)
</code></pre>
| 1 | 2016-08-01T06:57:49Z | [
"python",
"xml",
"python-2.7",
"xml-parsing",
"ipython"
] |
Django view is not loading changes | 38,692,693 | <p>I am a django beginner. I have a deployed django app with nginx, uwSGI and postgresql. When I try to change some code in a view, this one is reflected in the client side but the error continues existing, thanks.</p>
<p><strong>Here is the output failure:</strong> </p>
<pre><code>Django Version: 1.6.5
Exception Type: NameError
Exception Value:
global name 'buffer_desc' is not defined
Exception Location: ./vitrasa/views.py in change_priority, line 140
Python Executable: /usr/local/bin/uwsgi
</code></pre>
<p><strong>Here is the code:</strong></p>
<pre><code>def change_priority(id_zone):
zone_pet=Zone.objects.filter(id=id_zone)
buffer_desc = 0
buffer_actv = 0
for i in zone_pet:
if i.vitrasa_pet == True & i.esycsa_pet == True:
buffer_actv=struct.pack("!7i",2,5,5,int(float(i.zone_regulator)),int(float(i.zone_detector)),1,3)
buffer_desc=struct.pack("!9i",2,5,0,5,0,int(float(i.zone_regulator)),int(float(i.zone_detector)),0,3)
Zone.objects.filter(id=id_zone).update(pet_state=True,expire_pet=expire_hour())
#riteLog("System","ACTV",i.zone_name,"")
t = data_send(i.id , i.zone_ip , buffer_actv , buffer_desc)
t.start()
else:
Zone.objects.filter(id=id_zone).update(pet_state=False, expire_pet="")
#riteLog("System","DESC",i.zone_name,"")
</code></pre>
<p>As you can see, the name of the variable is already defined</p>
| 0 | 2016-08-01T06:57:07Z | 38,693,744 | <p>Thanks, the problem was that, you have to restart uwsgi process to apply changes in the project</p>
| 1 | 2016-08-01T08:02:24Z | [
"python",
"django",
"postgresql",
"nginx"
] |
xml subelements in python query | 38,692,914 | <p>I am trying to replicate some XML code in python to put into a program I am currently working on which does some panoramic captures. At the end the idea is to export an XML file of the capture detail to allow for easier importing into one of the various panorama capture programs.</p>
<p>I am fairly new to Python, but have been using xml.etree.ElementTree, with this I can set information like the root declaration and the header and sub-header but I get a bit lost in two points, the first is how through a sub-element I can set a value (e.g. GPS) and the second is how a sub-element can have multiple values (e.g. mosaic / overlap minimium).</p>
<p>For the elements I had the below working;</p>
<pre><code>root = etree.Element("papywizard")
root.set("version", "c")
header = etree.SubElement(root,"header")
general = etree.SubElement(header, "general")
title = etree.SubElement(general,"title")
</code></pre>
<p>I then thought i could do something like <code>title.text("Test123")</code> but this did not work. The full XML I am trying to replicate is below, is someone able to point me in the right direction on how I can set text within a sub-element tag, and beyond that how many tags can be aggregated into one sub-element?</p>
<p>Many Thanks!</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<papywizard version="c">
<header>
<general>
<title>
Test Capture 1
</title>
<gps>
37.8022697,-122.4056749
</gps>
<comment>
Add your comments here
</comment>
</general>
<shooting mode="mosaic">
<headOrientation>
up
</headOrientation>
<cameraOrientation>
landscape
</cameraOrientation>
<stabilizationDelay>
5.0
</stabilizationDelay>
<counter>
001
</counter>
<startTime>
2014-02-23_13h59m01s
</startTime>
<endTime>
2014-02-23_13h53m33s
</endTime>
</shooting>
<camera>
<timeValue>
5.0
</timeValue>
<bracketing nbPicts="1"/>
<sensor coef ="4.74" ratio="4:3"/>
</camera>
<lens type="rectilinear">
<focal>
12.7
</focal>
</lens>
<mosaic>
<nbPicts pitch="5" yaw="10"/>
<overlap minimum="0.25" pitch="0.25" yaw="0.25"/>
</mosaic>
</header>
<shoot>
<pict bracket="1" id="1">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="37.96" roll="0.0" yaw="-99.96"/>
</pict>
<pict bracket="1" id="2">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="18.98" roll="0.0" yaw="-99.96"/>
</pict>
<pict bracket="1" id="3">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="0.00" roll="0.0" yaw="-99.96"/>
</pict>
</shoot>
</papywizard>
</code></pre>
| 0 | 2016-08-01T07:13:01Z | 38,693,112 | <p>You must use the following command:</p>
<pre><code>title.text = "some text"
</code></pre>
| 2 | 2016-08-01T07:24:03Z | [
"python",
"xml"
] |
xml subelements in python query | 38,692,914 | <p>I am trying to replicate some XML code in python to put into a program I am currently working on which does some panoramic captures. At the end the idea is to export an XML file of the capture detail to allow for easier importing into one of the various panorama capture programs.</p>
<p>I am fairly new to Python, but have been using xml.etree.ElementTree, with this I can set information like the root declaration and the header and sub-header but I get a bit lost in two points, the first is how through a sub-element I can set a value (e.g. GPS) and the second is how a sub-element can have multiple values (e.g. mosaic / overlap minimium).</p>
<p>For the elements I had the below working;</p>
<pre><code>root = etree.Element("papywizard")
root.set("version", "c")
header = etree.SubElement(root,"header")
general = etree.SubElement(header, "general")
title = etree.SubElement(general,"title")
</code></pre>
<p>I then thought i could do something like <code>title.text("Test123")</code> but this did not work. The full XML I am trying to replicate is below, is someone able to point me in the right direction on how I can set text within a sub-element tag, and beyond that how many tags can be aggregated into one sub-element?</p>
<p>Many Thanks!</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<papywizard version="c">
<header>
<general>
<title>
Test Capture 1
</title>
<gps>
37.8022697,-122.4056749
</gps>
<comment>
Add your comments here
</comment>
</general>
<shooting mode="mosaic">
<headOrientation>
up
</headOrientation>
<cameraOrientation>
landscape
</cameraOrientation>
<stabilizationDelay>
5.0
</stabilizationDelay>
<counter>
001
</counter>
<startTime>
2014-02-23_13h59m01s
</startTime>
<endTime>
2014-02-23_13h53m33s
</endTime>
</shooting>
<camera>
<timeValue>
5.0
</timeValue>
<bracketing nbPicts="1"/>
<sensor coef ="4.74" ratio="4:3"/>
</camera>
<lens type="rectilinear">
<focal>
12.7
</focal>
</lens>
<mosaic>
<nbPicts pitch="5" yaw="10"/>
<overlap minimum="0.25" pitch="0.25" yaw="0.25"/>
</mosaic>
</header>
<shoot>
<pict bracket="1" id="1">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="37.96" roll="0.0" yaw="-99.96"/>
</pict>
<pict bracket="1" id="2">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="18.98" roll="0.0" yaw="-99.96"/>
</pict>
<pict bracket="1" id="3">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="0.00" roll="0.0" yaw="-99.96"/>
</pict>
</shoot>
</papywizard>
</code></pre>
| 0 | 2016-08-01T07:13:01Z | 38,695,064 | <p>Text nodes and element nodes are two kinds of nodes and an XML element node can have any number of text and/or element child nodes in any order.</p>
<p>If you want to add text to a node, you can do it with the <code>.text</code> attribute </p>
<pre><code>title.text = "Sometext"
</code></pre>
<p>If you want to add attributes, you can do it with the <code>set</code> command</p>
<pre><code>title.set('Attribute name', 'Attributevalue')
</code></pre>
| 1 | 2016-08-01T09:15:58Z | [
"python",
"xml"
] |
xml subelements in python query | 38,692,914 | <p>I am trying to replicate some XML code in python to put into a program I am currently working on which does some panoramic captures. At the end the idea is to export an XML file of the capture detail to allow for easier importing into one of the various panorama capture programs.</p>
<p>I am fairly new to Python, but have been using xml.etree.ElementTree, with this I can set information like the root declaration and the header and sub-header but I get a bit lost in two points, the first is how through a sub-element I can set a value (e.g. GPS) and the second is how a sub-element can have multiple values (e.g. mosaic / overlap minimium).</p>
<p>For the elements I had the below working;</p>
<pre><code>root = etree.Element("papywizard")
root.set("version", "c")
header = etree.SubElement(root,"header")
general = etree.SubElement(header, "general")
title = etree.SubElement(general,"title")
</code></pre>
<p>I then thought i could do something like <code>title.text("Test123")</code> but this did not work. The full XML I am trying to replicate is below, is someone able to point me in the right direction on how I can set text within a sub-element tag, and beyond that how many tags can be aggregated into one sub-element?</p>
<p>Many Thanks!</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<papywizard version="c">
<header>
<general>
<title>
Test Capture 1
</title>
<gps>
37.8022697,-122.4056749
</gps>
<comment>
Add your comments here
</comment>
</general>
<shooting mode="mosaic">
<headOrientation>
up
</headOrientation>
<cameraOrientation>
landscape
</cameraOrientation>
<stabilizationDelay>
5.0
</stabilizationDelay>
<counter>
001
</counter>
<startTime>
2014-02-23_13h59m01s
</startTime>
<endTime>
2014-02-23_13h53m33s
</endTime>
</shooting>
<camera>
<timeValue>
5.0
</timeValue>
<bracketing nbPicts="1"/>
<sensor coef ="4.74" ratio="4:3"/>
</camera>
<lens type="rectilinear">
<focal>
12.7
</focal>
</lens>
<mosaic>
<nbPicts pitch="5" yaw="10"/>
<overlap minimum="0.25" pitch="0.25" yaw="0.25"/>
</mosaic>
</header>
<shoot>
<pict bracket="1" id="1">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="37.96" roll="0.0" yaw="-99.96"/>
</pict>
<pict bracket="1" id="2">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="18.98" roll="0.0" yaw="-99.96"/>
</pict>
<pict bracket="1" id="3">
<time>
2014-02-23_13h59m01s
</time>
<position pitch="0.00" roll="0.0" yaw="-99.96"/>
</pict>
</shoot>
</papywizard>
</code></pre>
| 0 | 2016-08-01T07:13:01Z | 38,701,464 | <pre><code>import xml.etree.ElementTree as ET
root = ET.Element("papywizard")
root.set("version", "c")
header = ET.SubElement(root,"header")
general = ET.SubElement(header, "general")
title = ET.SubElement(general,"title")
title.text = str('Test123') # This is how you set it
tree = ET.ElementTree(root) # This step will form a tree
tree.write('expected.xml') # This step will save the xml file.
</code></pre>
| 1 | 2016-08-01T14:31:08Z | [
"python",
"xml"
] |
How do I incorporate quotation marks into a user input? I want them to input a string but it is akward to say put in quotes | 38,692,931 | <pre><code>def palindrome(s):
s=input ("Enter a phrase (**use quotation marks for words**): ")
s.lower()
return s[::-1]==s
palindrome(s)
</code></pre>
<p>This is my code. How do I change it so I can take out the bolded section? I use python 2 and it won't accept string inputs without the quotation marks.</p>
| 2 | 2016-08-01T07:14:04Z | 38,693,021 | <p>Use <code>raw_input</code> instead of <code>input</code>. In Python 2 <code>input</code> tries to evaluate the user's input, so letters are evaluated as variables.</p>
| 1 | 2016-08-01T07:19:23Z | [
"python",
"python-2.x"
] |
How do I incorporate quotation marks into a user input? I want them to input a string but it is akward to say put in quotes | 38,692,931 | <pre><code>def palindrome(s):
s=input ("Enter a phrase (**use quotation marks for words**): ")
s.lower()
return s[::-1]==s
palindrome(s)
</code></pre>
<p>This is my code. How do I change it so I can take out the bolded section? I use python 2 and it won't accept string inputs without the quotation marks.</p>
| 2 | 2016-08-01T07:14:04Z | 38,693,043 | <p>A <a class='doc-link' href="http://stackoverflow.com/documentation/python/266/basic-input-and-output/973/using-input-and-raw-input#t=201608010718573153743"><code>raw_input</code></a> will do the job. <a href="http://stackoverflow.com/q/4915361/5018771">This question</a> about input differences in Python 2 and 3 might help you.</p>
<p>Besides, I think the parameter <code>s</code> is not necessary. And <code>s.lower()</code> alone does not change the value of <code>s</code>.</p>
<pre><code>def palindrome():
s = raw_input("Enter a phrase : ")
s = s.lower()
return s[::-1] == s
palindrome()
</code></pre>
| 1 | 2016-08-01T07:20:42Z | [
"python",
"python-2.x"
] |
python accessing returned variable | 38,692,971 | <p>I'm still not comfortable with python. Experimenting with a deep learning open source code, I'm writting a test code and I can see it runs like below. (using datasets package and pascal_voc module in it, BTW, this is from py-faster-rcnn code)</p>
<pre><code>>>> import datasets
>>> import datasets.pascal_voc as pv
>>> d = datasets.pascal_voc('trainval', '2007')
>>> d._load_pascal_annotation('{0:06d}'.format(5))
Removed 2 difficult objects
{'boxes': array([[262, 210, 323, 338],
[164, 263, 252, 371],
[240, 193, 294, 298]], dtype=uint16), 'flipped': False, 'gt_classes': array([9, 9, 9], dtype=int32), 'gt_overlaps': <3x21 sparse matrix of type '<type 'numpy.float32'>'
</code></pre>
<p>the function <code>_load_pascal_annotation</code> returns values as shown below.</p>
<pre><code>def _load_pascal_annotation(self, index):
....
return {'boxes' : boxes,
'gt_classes': gt_classes,
'gt_overlaps' : overlaps,
'flipped' : False}
</code></pre>
<p>I want to extract the array of the 'boxes' from the returned dictionary and use it to draw something. I tried <code>d['boxes']</code> but give me error below.</p>
<pre><code>>>> d['boxes']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'pascal_voc' object has no attribute '__getitem__'
</code></pre>
<p>How can I extract the coordinate values from returned value of _load_pascal_annotation? </p>
| 1 | 2016-08-01T07:16:14Z | 38,693,083 | <p>I don't know your library at all, but from what you've shown, you probably want to assign the results of <code>_load_pascal_annotation</code> to a new variable, then access the <code>boxes</code> item in the dictionary. Try something like this:</p>
<pre><code>data = d._load_pascal_annotation('{0:06d}'.format(5))
print(data['boxes'])
</code></pre>
<p>One thing I'd note however is that methods with a single leading underscore in their names are generally intended to be private (e.g. they're not part of the class's public API). There may be some other method or attribute on your <code>d</code> object that you should be using instead which will call <code>_load_pascal_annotation</code> in the background (and do something appropriate with its return value).</p>
| 1 | 2016-08-01T07:22:20Z | [
"python",
"caffe",
"pycaffe"
] |
python accessing returned variable | 38,692,971 | <p>I'm still not comfortable with python. Experimenting with a deep learning open source code, I'm writting a test code and I can see it runs like below. (using datasets package and pascal_voc module in it, BTW, this is from py-faster-rcnn code)</p>
<pre><code>>>> import datasets
>>> import datasets.pascal_voc as pv
>>> d = datasets.pascal_voc('trainval', '2007')
>>> d._load_pascal_annotation('{0:06d}'.format(5))
Removed 2 difficult objects
{'boxes': array([[262, 210, 323, 338],
[164, 263, 252, 371],
[240, 193, 294, 298]], dtype=uint16), 'flipped': False, 'gt_classes': array([9, 9, 9], dtype=int32), 'gt_overlaps': <3x21 sparse matrix of type '<type 'numpy.float32'>'
</code></pre>
<p>the function <code>_load_pascal_annotation</code> returns values as shown below.</p>
<pre><code>def _load_pascal_annotation(self, index):
....
return {'boxes' : boxes,
'gt_classes': gt_classes,
'gt_overlaps' : overlaps,
'flipped' : False}
</code></pre>
<p>I want to extract the array of the 'boxes' from the returned dictionary and use it to draw something. I tried <code>d['boxes']</code> but give me error below.</p>
<pre><code>>>> d['boxes']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'pascal_voc' object has no attribute '__getitem__'
</code></pre>
<p>How can I extract the coordinate values from returned value of _load_pascal_annotation? </p>
| 1 | 2016-08-01T07:16:14Z | 38,693,084 | <p>You call the <code>_load_pascal_annotation</code> method but you don't keep a reference to its return value.</p>
<p>Try:</p>
<pre><code>r_value = d._load_pascal_annotation('{0:06d}'.format(5))
r_value['boxes']
</code></pre>
| 2 | 2016-08-01T07:22:21Z | [
"python",
"caffe",
"pycaffe"
] |
Python how to get function formula given it's inputs and results | 38,693,093 | <p>Assume we have a function with unknown formula, given few inputs and results of this function, how can we get the function's formula.</p>
<p>For example we have inputs x and y and result r in format (x,y,r)</p>
<pre><code>[ (2,4,8) , (3,6,18) ]
</code></pre>
<p>And the desired function can be</p>
<pre><code>f(x,y) = x * y
</code></pre>
| -3 | 2016-08-01T07:22:44Z | 38,695,132 | <p>As you post the question, the problem is too generic. If you want to find <em>any</em> formula mapping the given inputs to the given result, there are simply too many possible formulas. In order to make sense of this, you need to somehow restrict the set of functions to consider. For example you could say that you're only interested in polynomial solutions, i.e. where</p>
<pre><code>r = sum a_ij * x^i * y^j for i from 0 to n and j from 0 to n - i
</code></pre>
<p>then you have a system of equations, with the <code>a_ij</code> as parameters to solve for. The higher the degree <code>n</code> the more such parameters you'd have to find, so the more input-output combinations you'd need to know. Variations of this use rational functions (so you divide by another polynomial), or allow some trigonometric functions, or something like that.</p>
<p>If your setup were particularly easy, you'd have just linear equations, i.e. <code>r = a*x + b*y + c</code>. As you can see, even that has three parameters <code>a,b,c</code> so you can't uniquely find all three of them just given the two inputs you provided in your question. And even then the result would not be the <code>r = x*y</code> you were aiming for, since that's technically of degree 2.</p>
<p>If you want to point out that <code>r = x*y</code> is a particularly simple formula, and you would like to look for simple formulas, then one approach would be enumerating formulas in order of increasing complexity. But if you do this without parameters (since ugly parameters will make a simple formula like <code>a*x + b*y + c</code> appear complex), then it's hard to guilde this enumeration towards the one you want, so you'd really have to enumerate all possible formulas, which will become infeasible <em>very</em> quickly.</p>
| 0 | 2016-08-01T09:18:54Z | [
"python",
"algorithm",
"math",
"interpolation"
] |
python counter with closure | 38,693,236 | <p>I'm trying to build a counter in python with the property of closure. The code in the following works:</p>
<pre><code>def generate_counter():
CNT = [0]
def add_one():
CNT[0] = CNT[0] + 1
return CNT[0]
return add_one
</code></pre>
<p>However when I change the list CNT to a var, it did not work:</p>
<pre><code>def generate_counter1():
x = 0
def add_one():
x = x + 1
return x
return add_one
</code></pre>
<p>when I print the closure property of an instance, I found the <code>__closure__</code> of the second case is none:</p>
<pre><code>>>> ct1 = generate_counter()
>>> ct2 = generate_counter1()
>>> print(ct1.__closure__[0])
<cell at 0xb723765c: list object at 0xb724370c>
>>> print(ct2.__closure__)
None
</code></pre>
<p>Just wondering why the index in outer function has to be a list?</p>
<hr>
<p>Thanks for the answers! Found the docs which clearly explained this problem
<a href="https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="nofollow">https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value</a></p>
| 0 | 2016-08-01T07:32:26Z | 38,693,333 | <p>Python determines the scope of a name by looking at name binding behaviour; assignment is one such behaviour (function parameters, importing, the target in <code>for target ...</code> or <code>while .. as target</code> are other examples). A name you bind to in a function is considered <em>local</em>. See the <a href="https://docs.python.org/3/reference/executionmodel.html#naming-and-binding" rel="nofollow"><em>Naming and Binding</em> section</a> of the reference documentation.</p>
<p>So the name <code>x</code> in your second example is a <em>local</em> variable, because you assigned directly to it:</p>
<pre><code>x = x + 1
</code></pre>
<p>In fact, because you never gave that <code>x</code> a local value, you'll get an exception when you try to use that function; the local name is <em>unbound</em> when you try to read it:</p>
<pre><code>>>> generate_counter1()()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in add_one
UnboundLocalError: local variable 'x' referenced before assignment
</code></pre>
<p>In your first example no such binding takes place; you are instead altering the <em>contents</em> of <code>CNT</code>, what that name references is not altered.</p>
<p>If you are using Python 3, you can override the decision to make a name local, by using a <a href="https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement" rel="nofollow"><code>nonlocal</code> statement</a>:</p>
<pre><code>def generate_counter2():
x = 0
def add_one():
nonlocal x
x = x + 1
return x
return add_one
</code></pre>
<p>By making <code>x</code> non-local, Python finds it in the parent context and creates a closure for it again.</p>
<pre><code>>>> def generate_counter2():
... x = 0
... def add_one():
... nonlocal x
... x = x + 1
... return x
... return add_one
...
>>> generate_counter2().__closure__
(<cell at 0x1078c62e8: int object at 0x1072c8070>,)
</code></pre>
<p><code>nonlocal</code> is new in Python 3; in Python 2 you are limited to tricks like using a mutable list object to evade the binding rule. Another trick would be to assign the counter to an attribute of the nested function; again, this avoids binding a name in the current scope:</p>
<pre><code>def generate_counter3():
def add_one():
add_one.x += 1
return add_one.x
add_one.x = 0
return add_one
</code></pre>
| 3 | 2016-08-01T07:38:24Z | [
"python",
"closures"
] |
python counter with closure | 38,693,236 | <p>I'm trying to build a counter in python with the property of closure. The code in the following works:</p>
<pre><code>def generate_counter():
CNT = [0]
def add_one():
CNT[0] = CNT[0] + 1
return CNT[0]
return add_one
</code></pre>
<p>However when I change the list CNT to a var, it did not work:</p>
<pre><code>def generate_counter1():
x = 0
def add_one():
x = x + 1
return x
return add_one
</code></pre>
<p>when I print the closure property of an instance, I found the <code>__closure__</code> of the second case is none:</p>
<pre><code>>>> ct1 = generate_counter()
>>> ct2 = generate_counter1()
>>> print(ct1.__closure__[0])
<cell at 0xb723765c: list object at 0xb724370c>
>>> print(ct2.__closure__)
None
</code></pre>
<p>Just wondering why the index in outer function has to be a list?</p>
<hr>
<p>Thanks for the answers! Found the docs which clearly explained this problem
<a href="https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="nofollow">https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value</a></p>
| 0 | 2016-08-01T07:32:26Z | 38,693,347 | <p>It doesn't <em>have</em> to be a list, it just has to be an mutable object which you <em>mutate</em>, not reassign.</p>
<p>From the <a href="https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python" rel="nofollow">docs</a>:</p>
<blockquote>
<p>If a variable is assigned a value anywhere within the functionâs body, itâs assumed to be a local unless explicitly declared as global.</p>
</blockquote>
<p>Thus, in your second example, <code>x</code> is considered local (to the inner function), and, after your first assignment, you're shadowing the outer 'x'.</p>
<p>On the other hand, in the first example (since you don't assign a value to <code>CNT</code>) it operates on the <code>CNT</code> defined in the outer function.</p>
| 0 | 2016-08-01T07:39:19Z | [
"python",
"closures"
] |
What is the Python equivalent of RequestConfig in Java? | 38,693,254 | <p>I have the following piece of code in Java:</p>
<pre><code>RequestConfig.custom().setSocketTimeout(10).setConnectTimeout(20).build();
</code></pre>
<p>How do I achieve the same thing in Python?</p>
| 2 | 2016-08-01T07:33:37Z | 38,693,836 | <p>Please, take a look to this <a href="http://stackoverflow.com/a/3432222/3014866">answer</a> where is shown how to set <code>timeout</code>. </p>
<p>It results from <a href="https://docs.python.org/2/library/socket.html#socket.socket.settimeout" rel="nofollow">documentation</a> that <code>setSocketTimeout</code> and <code>setConnectTimeout</code> are the same things in Python.</p>
<blockquote>
<p>Note that the <code>connect()</code> operation is subject to the timeout setting,
and in general it is recommended to call <code>settimeout()</code> before calling
<code>connect()</code> or pass a timeout parameter to <code>create_connection()</code>. The
system network stack may return a connection timeout error of its own
regardless of any Python socket timeout setting.</p>
</blockquote>
| 1 | 2016-08-01T08:06:32Z | [
"java",
"python",
"apache",
"python-2.7",
"http"
] |
How to establish communication between a python script running on Linux with a .NET C# application running on windows? | 38,693,270 | <p>I am working on an application that requires me to interface a python script running on linux OS on a virtual machine with a .net c# application having wpf forms running on windows such that that the c# application sends files to the python script for processing. What are my options in light of this setting? </p>
<p>I tried using monodevelop on linux in an effort to run .NET applications but it didn't work out as monodevelop doesn't support wpf forms. </p>
<p><a href="http://imgur.com/gallery/wzwef" rel="nofollow">http://imgur.com/gallery/wzwef</a></p>
| 0 | 2016-08-01T07:34:50Z | 38,693,427 | <p>Use sockets to send the file bytes and the result between them.</p>
<p>Some documentation here:</p>
<p><a href="https://msdn.microsoft.com/en-us/library/b6xa24z5(v=vs.110).aspx" rel="nofollow">C# Sockets</a></p>
<p><a href="https://docs.python.org/2/howto/sockets.html" rel="nofollow">Python Sockets</a></p>
<p>EDIT: This should work using virtual machines</p>
| 1 | 2016-08-01T07:44:05Z | [
"c#",
"python",
".net",
"linux",
"cross-platform"
] |
How to establish communication between a python script running on Linux with a .NET C# application running on windows? | 38,693,270 | <p>I am working on an application that requires me to interface a python script running on linux OS on a virtual machine with a .net c# application having wpf forms running on windows such that that the c# application sends files to the python script for processing. What are my options in light of this setting? </p>
<p>I tried using monodevelop on linux in an effort to run .NET applications but it didn't work out as monodevelop doesn't support wpf forms. </p>
<p><a href="http://imgur.com/gallery/wzwef" rel="nofollow">http://imgur.com/gallery/wzwef</a></p>
| 0 | 2016-08-01T07:34:50Z | 38,693,523 | <p>If you have network connection between machines (local network, host only or Internet) then you could listen for files on python using:</p>
<ol>
<li><a class='doc-link' href="http://stackoverflow.com/documentation/python/1309/python-networking/5718/creating-a-udp-server#t=201608010743374011557">UDP </a></li>
<li><a class='doc-link' href="http://stackoverflow.com/documentation/python/1309/python-networking/5717/creating-a-tcp-server#t=201608010744086514768">TCP</a></li>
<li><a class='doc-link' href="http://stackoverflow.com/documentation/python/1309/python-networking/5678/creating-a-simple-http-server#t=201608010744456201397">SimpleHTTPServer</a></li>
</ol>
<p>Then in C# app use:</p>
<ol>
<li><code>UDPClient</code></li>
<li><code>TCPClient</code></li>
<li><code>WebClient</code></li>
</ol>
| 0 | 2016-08-01T07:49:02Z | [
"c#",
"python",
".net",
"linux",
"cross-platform"
] |
Can't correctly parse cisco cli command output | 38,693,276 | <p>I am trying to parse Cisco <code>show ip interface vrf all</code> command output from txt file by reading line by line in loop.</p>
<p>The output is:</p>
<pre class="lang-none prettyprint-override"><code>IP Interface Status for VRF "default"
loopback1, Interface status: protocol-up/link-up/admin-up, iod: 212,
IP address: 10.1.0.1, IP subnet: 10.1.0.0/30
...
Ethernet1/1, Interface status: protocol-up/link-up/admin-up, iod: 278,
IP address: 10.0.0.1, IP subnet: 10.0.0.0/30
IP Interface Status for VRF "TEST"
Vlan99, Interface status: protocol-up/link-up/admin-up, iod: 147,
IP address: 172.16.0.1, IP subnet: 172.16.0.0/24
...
Vlan888, Interface status: protocol-up/link-up/admin-up, iod: 115,
IP address: 172.16.1.1, IP subnet: 172.16.1.0/24
...
</code></pre>
<p>And so on.</p>
<p>I need to extract only VRF that have VLAN and subnet.
For example from this output I should have variables in every iteration:</p>
<pre><code>vrf -> vlan -> subnet (TEST -> 99 -> 172.16.0.0/24)
vrf -> vlan -> subnet (TEST -> 888 -> 172.16.1.0/24)
</code></pre>
<p>But I don't need info from <code>default vrf</code> because it has no VLans.</p>
<p>I wrote some regular expressions to find this info:</p>
<pre><code> vrf = re.findall( r'VRF "(.*)"', line)
vlan = re.findall( r'Vlan(\d+)', line)
subnet= re.findall( r'IP address.*subnet:\s(.*)$', line)
</code></pre>
<p>But I do not know how to ignore VRFs with no vlans.</p>
| 1 | 2016-08-01T07:35:11Z | 38,693,509 | <p>You can use this expression:</p>
<pre><code>^(Vlan\d+).+[\n\r]
.+?subnet:\ (.+)
</code></pre>
<p><hr>
In <code>Python</code> code:</p>
<pre><code>import re
rx = re.compile("""
^(Vlan\d+).+[\n\r] # capture Vlan, followed by digits at the beginning of line
.+?subnet:\ (.+) # match anything lazily, followed by subnet and capture the address
""",re.MULTILINE|re.VERBOSE)
for match in rx.finditer(your_string_here):
print match.group(1) # Vlan99
print match.group(2) # the subnet ip
</code></pre>
<p><hr>
See <a href="https://regex101.com/r/kZ8jA6/1" rel="nofollow"><strong>a demo on regex101.com</strong></a>.</p>
| 0 | 2016-08-01T07:48:07Z | [
"python",
"regex",
"parsing"
] |
creating new numpy array dataset for each loop | 38,693,417 | <p>I need to create a new dataset variable everytime within a for loop
using .append as below wont work. Note the shape of each numpy array type variable is (56, 25000)</p>
<pre><code>ps=[1,2,3,4]
for subj in ps:
datapath = '/home/subj%d' % (subj)
mydata.append = np.genfromtext(datapath, mydatafile)
</code></pre>
<p>so basically I need her 4 instances of mydata, each with a shape of (56, 25000), or that for each loop a new dataset variable is created eg mydata1, ..., mydata4....however .append won't do it. I could do this with </p>
<pre><code>if ps==1: mydata1 = np.genfromtext(datapath, mydatafile)
if ps==2: mydata2 = np.genfromtext(datapath, mydatafile)
</code></pre>
<p>etc but I have far to many instances of ps, so would be nice to loop it</p>
<p>thanks!</p>
| 2 | 2016-08-01T07:43:32Z | 38,693,470 | <p>It's hard to say without more code, but <code>.append</code> is generally a method, and should be called like this:</p>
<pre><code>some_container.append(your_object)
</code></pre>
<p>Note I'm also initializing <code>mydata</code> to be an empty list -- you don't show how you initialize it (if you do at all), so just be aware:</p>
<pre><code>mydata = []
for subj in [1,2,3,4]:
datapath = '/home/subj%d' % (subj)
mydata.append( np.genfromtext(datapath, mydatafile) )
</code></pre>
<p>Then, <code>mydata</code> will be a 4-element Python list of numpy arrays. </p>
<p>There is also numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofollow"><code>vstack()</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>concatenate()</code></a> functions which may be worth looking in to.</p>
<p>Lastly, just wanted to point out that</p>
<pre><code>ps = [1,2,3,4]
for sub in ps:
...
</code></pre>
<p>Can be written as (as I do above):</p>
<pre><code>for sub in [1,2,3,4]:
...
</code></pre>
<p>but also as:</p>
<pre><code>for sub in range(1,5):
...
# or
for sub in range(4):
datapath = '/home/subj%d' % (subj + 1)
...
</code></pre>
| 2 | 2016-08-01T07:46:24Z | [
"python",
"numpy"
] |
How do I extract data from a Bokeh ColumnDatasource | 38,693,444 | <p>I was trying to avoid using a ColumnDataSource and instead of that I was passing pandas dataframe columns directly to Bokeh plots.</p>
<p>Soon though I had to implement a HoverTool which requires to have the data in a ColumnDataSource. So, I started using ColumnDataSource.</p>
<p>Now, I was creating a box annotation and I had to use the maximum value of a certain column from my data to define the top border of the box.</p>
<p>I can do that easily using pandas:</p>
<pre><code>low_box = BoxAnnotation(
top=flowers['petal_width'][flowers['species']=='setosa'].max(),
fill_alpha=0.1, fill_color='red')
</code></pre>
<p>But I can't figure out how to extract the maximum from a ColumnDataSource.</p>
<p>Is there a way to extract a maximum value from it, or is my approach all wrong in the first place?</p>
| 1 | 2016-08-01T07:44:51Z | 38,726,028 | <p>A ColumnDataSource object has an attribute <code>data</code> which will return the python dictionary used to create the object in the first place. </p>
<pre><code>from bokeh.plotting import ColumnDataSource
# define ColumnDataSource
source = ColumnDataSource(
data=dict(
x=[1, 2, 3, 4, 5],
y=[2, 5, 8, 2, 7],
desc=['A', 'b', 'C', 'd', 'E'],
)
)
# find max for variable 'x' from 'source'
print( max( source.data['x'] ))
</code></pre>
| 1 | 2016-08-02T16:35:33Z | [
"python",
"pandas",
"data-visualization",
"bokeh"
] |
My user input takes uppercase letters different as lower case letters. It interferes with the results. Any tips? | 38,693,515 | <pre><code> def palindrome(): #Before I had parameter s, but it is repetitive.
s=raw_input ("Enter a phrase : ") #Raw input makes the input not considered as a variable but as a string
s.lower()
return s[::-1]==s
palindrome()
</code></pre>
<p>2 questions. </p>
<ol>
<li>Does the raw_input makes an input considered like a string? </li>
<li>And also I used the s.lower because when I tried to run "Eat Tae", it would say it wasn't a palindrome. The s.lower did not work. How do I solve this? </li>
</ol>
| 1 | 2016-08-01T07:48:33Z | 38,693,538 | <p><code>lower()</code> is not in-place, it returns a new string.</p>
<p>You should either reassign it to <code>s</code> (<code>s = s.lower()</code>) or call <code>lower</code> on the input itself:</p>
<pre><code> s = raw_input("Enter a phrase : ").lower()
</code></pre>
| 1 | 2016-08-01T07:50:00Z | [
"python"
] |
My user input takes uppercase letters different as lower case letters. It interferes with the results. Any tips? | 38,693,515 | <pre><code> def palindrome(): #Before I had parameter s, but it is repetitive.
s=raw_input ("Enter a phrase : ") #Raw input makes the input not considered as a variable but as a string
s.lower()
return s[::-1]==s
palindrome()
</code></pre>
<p>2 questions. </p>
<ol>
<li>Does the raw_input makes an input considered like a string? </li>
<li>And also I used the s.lower because when I tried to run "Eat Tae", it would say it wasn't a palindrome. The s.lower did not work. How do I solve this? </li>
</ol>
| 1 | 2016-08-01T07:48:33Z | 38,693,571 | <p>In python, the two main ways of taking input is through <code>raw_input</code>, which takes the input in as a string, and <code>input</code>, which takes the variable in as the type entered like a int.</p>
<p>The <code>s.lower()</code> function returns a string so the proper format would be</p>
<pre><code>s = s.lower()
</code></pre>
| 1 | 2016-08-01T07:52:02Z | [
"python"
] |
Softlayer API -- exception happened when calling softlayer api | 38,693,625 | <p>I got an exception: "TransportError: TransportError(0): ('Connection aborted.', error(110, 'Connection timed out'))" when I called the api: Virtual_Guest::getBandwidthTotal.</p>
<p>It happened in this situation:</p>
<ol>
<li><p>one <strong>same</strong> softlayer-api username and key</p></li>
<li><p>I called the functions <strong>concurrently</strong> <strong>thousands times</strong> at one moment.</p></li>
</ol>
<p>So I do not know the exception happened due to "huge concurrent api callings" or just a network problem, or some other reasons.</p>
<p>If it causes since "huge concurrent api callings", here is an additional question:</p>
<p>As I says before that I called with one same username and key, if I calls concurrently with <strong>different</strong> username and key, will this exception happen as well?</p>
| 0 | 2016-08-01T07:55:00Z | 38,699,490 | <p>The timeout errors are usually generated when the client is waiting a response of the API, this situation is documented <a href="https://sldn.softlayer.com/blog/phil/How-Solve-Error-fetching-http-headers" rel="nofollow">here</a>, in your case you can try to increase the timeout of your client, if you are using the Softlayer Python client please see the documentation to increase the timeout <a href="http://softlayer-api-python-client.readthedocs.io/en/latest/api/client/" rel="nofollow">here</a>, and aslo please review that you network connection is fine.</p>
<p>Regards</p>
| 1 | 2016-08-01T12:55:08Z | [
"python",
"softlayer"
] |
Softlayer API -- exception happened when calling softlayer api | 38,693,625 | <p>I got an exception: "TransportError: TransportError(0): ('Connection aborted.', error(110, 'Connection timed out'))" when I called the api: Virtual_Guest::getBandwidthTotal.</p>
<p>It happened in this situation:</p>
<ol>
<li><p>one <strong>same</strong> softlayer-api username and key</p></li>
<li><p>I called the functions <strong>concurrently</strong> <strong>thousands times</strong> at one moment.</p></li>
</ol>
<p>So I do not know the exception happened due to "huge concurrent api callings" or just a network problem, or some other reasons.</p>
<p>If it causes since "huge concurrent api callings", here is an additional question:</p>
<p>As I says before that I called with one same username and key, if I calls concurrently with <strong>different</strong> username and key, will this exception happen as well?</p>
| 0 | 2016-08-01T07:55:00Z | 38,880,747 | <p>There is a limit on the number of API calls that can be made by an account per second. I believe this limit is per username, however I would not recommend using a bunch of different users to get around this limit. </p>
<p>My suggestion would be to use an objectMask to get as much data as possible in one API call, instead of making numerous api calls. </p>
<p>Instead of calling Virtual_Guest::getBandwidthTotal on every virtual guest on your account, you could call</p>
<pre><code>SoftLayer_Account::getVirtualGuests(mask="mask[inboundPrivateBandwidthUsage,inboundPublicBandwidthUsage,outboundPrivateBandwidthUsage,outboundPublicBandwidthUsage]")
</code></pre>
<p>You might also need to use <a href="https://sldn.softlayer.com/article/using-result-limits-softlayer-api" rel="nofollow">result Limits</a> so that one big call doesn't time out as well. </p>
| 0 | 2016-08-10T18:15:39Z | [
"python",
"softlayer"
] |
How to process a large text file to get part of this file more efficiently? | 38,693,716 | <p>I have a text file like this:</p>
<pre><code> A B C D E F ... X Y Z
a 1 0 1 2 1 0 ... 1 0 2
b 1 2 0 1 1 2 ... 1 0 0
c . . . . . . ..... . .
d . . . . . . ..... . .
e . . . . . . ..... . .
f . . . . . . ..... . .
. . . . . . . ..... . .
. . . . . . . ..... . .
. . . . . . . ..... . .
x 1 0 1 2 1 0 ... 1 0 2
y 0 0 1 0 1 1 ... 1 0 2
z 1 2 0 1 1 2 ... 1 0 0
</code></pre>
<p>what i need to do is that :load this file and get 1000 lines of E&F rows to a new text file
I had used itertools to load this large file but can't to get E&F rows efficient</p>
<pre><code>#!/usr/bin/env python
# -*- coding:UTF-8 -*-
from itertools import islice
fout = open('a.txt','w')
with open('b.txt','r') as fin:
n = 50
while n > 0:
next_n_lines = list(islice(fin,0,20))
if not next_n_lines:
break
fout.write(''.join(next_n_lines))
n = n - 1
fin.close()
fout.close()
</code></pre>
| 2 | 2016-08-01T08:00:51Z | 38,694,223 | <p>You can use this code</p>
<pre><code>with open('a.txt','w') as fout:
with open('b.txt','r') as fin:
lines_done=0
fin.readline() # skip the first line (" A B C D E F ... X Y Z" in your example)
# fout.write("E F\n") # uncomment this line if you want the column headings in fout
for line in fin:
if lines_done>=1000: # you said 100 lines only
break
ef=line[10:13] # solution A
# ef=" ".join(line.split()[5:7]) # solution B
fout.write(ef+"\n")
lines_done+=1
</code></pre>
<p>please make sure if which solution you need</p>
<ul>
<li><strong>A</strong> works on your example data (E at 10, F at 12) and is faster </li>
<li><strong>B</strong> works on more general whitespace-seperated lines (E 5th entriy in row, F
6th entry in row) and is a bit slower</li>
</ul>
| 0 | 2016-08-01T08:30:35Z | [
"python",
"dataset"
] |
How to process a large text file to get part of this file more efficiently? | 38,693,716 | <p>I have a text file like this:</p>
<pre><code> A B C D E F ... X Y Z
a 1 0 1 2 1 0 ... 1 0 2
b 1 2 0 1 1 2 ... 1 0 0
c . . . . . . ..... . .
d . . . . . . ..... . .
e . . . . . . ..... . .
f . . . . . . ..... . .
. . . . . . . ..... . .
. . . . . . . ..... . .
. . . . . . . ..... . .
x 1 0 1 2 1 0 ... 1 0 2
y 0 0 1 0 1 1 ... 1 0 2
z 1 2 0 1 1 2 ... 1 0 0
</code></pre>
<p>what i need to do is that :load this file and get 1000 lines of E&F rows to a new text file
I had used itertools to load this large file but can't to get E&F rows efficient</p>
<pre><code>#!/usr/bin/env python
# -*- coding:UTF-8 -*-
from itertools import islice
fout = open('a.txt','w')
with open('b.txt','r') as fin:
n = 50
while n > 0:
next_n_lines = list(islice(fin,0,20))
if not next_n_lines:
break
fout.write(''.join(next_n_lines))
n = n - 1
fin.close()
fout.close()
</code></pre>
| 2 | 2016-08-01T08:00:51Z | 38,694,467 | <p>Since columns are separated by ' ' You can use <a href="https://docs.python.org/3.6/library/stdtypes.html?highlight=split#str.split" rel="nofollow">str.split</a>.</p>
<pre><code>def extract(nin,nout,cidx,rows):
with open(nout,'w') as fout:
with open(nin,'r') as fin:
offest = 0
for line in fin:
cols = line.strip().split(' ')
for cc in cidx:
fout.write(cols[cc+offest] )
fout.write(' ')
fout.write('\n')
offest = 1
rows -= 1
if rows == 0:
break
extract('b.txt','a.txt',[4,5],1000)
</code></pre>
| 0 | 2016-08-01T08:44:26Z | [
"python",
"dataset"
] |
Django - How to show dropdown value instead object? | 38,693,722 | <p>It seems i can't get dropdown value instead object.</p>
<p><a href="http://i.stack.imgur.com/2XzHW.png" rel="nofollow"><img src="http://i.stack.imgur.com/2XzHW.png" alt="enter image description here"></a></p>
<p>form.html</p>
<pre><code>{% extends "base.html" %}
{% load i18n %}
{% block content %}
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
</code></pre>
<p>models.py</p>
<pre><code>class FacebookAccount(models.Model):
user = models.ForeignKey(User)
account_description = models.CharField(max_length=50)
facebook_application_id = models.CharField(max_length=50)
facebook_application_secret = models.CharField(max_length=50)
ouath_token = models.CharField(max_length=50)
class FacebookFanPage(models.Model):
facebook_account = models.ForeignKey(FacebookAccount)
fan_page_description = models.CharField(max_length=50)
fan_page_id = models.CharField(max_length=30)
class PredefinedMessage(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length=50)
list_description = models.CharField(max_length=50)
class Campaign(models.Model):
user = models.ForeignKey(User)
campaign_name = models.CharField(max_length=50)
autoresponder_type = (
('Send replies to inbox messages','Send replies to inbox messages'),
('Post replies to users comments','Post replies to users comments'),
)
facebook_account_to_use = models.ForeignKey(FacebookAccount)
set_auto_reply_for_fan_page = models.ForeignKey(FacebookFanPage)
message_list_to_use = models.ForeignKey(PredefinedMessage)
reply_only_for_this_keyword = models.CharField(max_length=50)
</code></pre>
<p>views.py </p>
<pre><code>class AutoresponderForm(ModelForm):
class Meta:
model = Campaign
fields = ['campaign_name','facebook_account_to_use','set_auto_reply_for_fan_page','message_list_to_use','reply_only_for_this_keyword']
exclude = ('user',)
def autoresponder_create(request, template_name='form.html'):
form = AutoresponderForm(request.POST or None)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.save()
return redirect('autoresponder_list')
return render(request, template_name, {'form':form})
</code></pre>
<p>Please advice. Thank you.</p>
| 1 | 2016-08-01T08:01:08Z | 38,693,811 | <p>You should implement <code>__str__</code> (or <code>__unicode__</code> if Python 2) in the object's model.</p>
<p>From Django's <a href="https://docs.djangoproject.com/en/1.9/ref/models/instances/#str" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable representation of the model from the <strong>str</strong>() method.</p>
</blockquote>
| 3 | 2016-08-01T08:05:39Z | [
"python",
"django"
] |
Django - How to show dropdown value instead object? | 38,693,722 | <p>It seems i can't get dropdown value instead object.</p>
<p><a href="http://i.stack.imgur.com/2XzHW.png" rel="nofollow"><img src="http://i.stack.imgur.com/2XzHW.png" alt="enter image description here"></a></p>
<p>form.html</p>
<pre><code>{% extends "base.html" %}
{% load i18n %}
{% block content %}
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
</code></pre>
<p>models.py</p>
<pre><code>class FacebookAccount(models.Model):
user = models.ForeignKey(User)
account_description = models.CharField(max_length=50)
facebook_application_id = models.CharField(max_length=50)
facebook_application_secret = models.CharField(max_length=50)
ouath_token = models.CharField(max_length=50)
class FacebookFanPage(models.Model):
facebook_account = models.ForeignKey(FacebookAccount)
fan_page_description = models.CharField(max_length=50)
fan_page_id = models.CharField(max_length=30)
class PredefinedMessage(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length=50)
list_description = models.CharField(max_length=50)
class Campaign(models.Model):
user = models.ForeignKey(User)
campaign_name = models.CharField(max_length=50)
autoresponder_type = (
('Send replies to inbox messages','Send replies to inbox messages'),
('Post replies to users comments','Post replies to users comments'),
)
facebook_account_to_use = models.ForeignKey(FacebookAccount)
set_auto_reply_for_fan_page = models.ForeignKey(FacebookFanPage)
message_list_to_use = models.ForeignKey(PredefinedMessage)
reply_only_for_this_keyword = models.CharField(max_length=50)
</code></pre>
<p>views.py </p>
<pre><code>class AutoresponderForm(ModelForm):
class Meta:
model = Campaign
fields = ['campaign_name','facebook_account_to_use','set_auto_reply_for_fan_page','message_list_to_use','reply_only_for_this_keyword']
exclude = ('user',)
def autoresponder_create(request, template_name='form.html'):
form = AutoresponderForm(request.POST or None)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.save()
return redirect('autoresponder_list')
return render(request, template_name, {'form':form})
</code></pre>
<p>Please advice. Thank you.</p>
| 1 | 2016-08-01T08:01:08Z | 38,694,010 | <p>Update your models.py like this:</p>
<pre><code>class Campaign(models.Model):
user = models.ForeignKey(User)
campaign_name = models.CharField(max_length=50)
autoresponder_type = (
('Send replies to inbox messages','Send replies to inbox
messages'),
('Post replies to users comments','Post replies to users comments'),
)
facebook_account_to_use = models.ForeignKey(FacebookAccount)
set_auto_reply_for_fan_page = models.ForeignKey(FacebookFanPage)
message_list_to_use = models.ForeignKey(PredefinedMessage)
reply_only_for_this_keyword = models.CharField(max_length=50)
def __unicode__(self):
return self.campaign_name # or you can use any string value instead of campaign_name
</code></pre>
| 0 | 2016-08-01T08:18:53Z | [
"python",
"django"
] |
Python setup.py - install only modifed files | 38,693,968 | <p>Here is my setup.py:</p>
<pre><code>from setuptools import setup, find_packages
import sys
if sys.version_info < (2, 6):
sys.exit('requires python 2.6 and up')
package = '*****'
version_string = '0'
setup(name=package,
version=version_string,
author='*****',
author_email='*****',
url='',
platforms='Platform Independent',
tests_require=['nose'],
test_suite='nose.collector',
packages=find_packages(exclude=['utest']),
include_package_data=True,
install_requires=['colorlog', 'netifaces', 'flufl.enum==4.0.1', 'ipaddr', 'rpyc==3.2.3'],
zip_safe=False)
</code></pre>
<p>Which I have to run every time I make changes in my project even after a small change to a single file, but I have a lot of files in my project that very rarely change. Is there a way to do installation of only modified files? </p>
| 1 | 2016-08-01T08:16:49Z | 38,694,142 | <p>If you are developing the code, this is preferable to use <code>python setup.py develop</code>. Regarding the files that have to be installed, they are handle by setuptools.</p>
| 1 | 2016-08-01T08:26:16Z | [
"python",
"installation",
"setup.py"
] |
install Jupyter extension | 38,694,087 | <p>I want to install check spelling jupyter's extension.
I followed <a href="http://www.simulkade.com/posts/2015-04-07-spell-checking-in-jupyter-notebooks.html" rel="nofollow">this instruction</a> but it required root privileges.
I want to do it on computing cluster so obviously I don't have it.
Is it a way to install this extension without super user?
In other word can you show me equivalent to pip --user flag? </p>
| 1 | 2016-08-01T08:23:38Z | 38,694,323 | <p>Would using the newer command helps? The article uses <code>ipython</code> command, which is superceded by <code>jupyter</code>.</p>
<p>Download the tools using this in the terminal instead:-</p>
<pre><code>$ jupyter nbextension install https://bitbucket.org/ipre/calico/downloads/calico-spell-check-1.0.zip
$ jupyter nbextension install https://bitbucket.org/ipre/calico/downloads/calico-document-tools-1.0.zip
$ jupyter nbextension install https://bitbucket.org/ipre/calico/downloads/calico-cell-tools-1.0.zip
</code></pre>
<p>Then, enable them using:-</p>
<pre><code>$ jupyter nbextension enable calico-spell-check
$ jupyter nbextension enable calico-document-tools
$ jupyter nbextension enable calico-cell-tools
</code></pre>
| -1 | 2016-08-01T08:35:56Z | [
"python",
"installation",
"jupyter"
] |
tuple one number with list of numbers python | 38,694,107 | <p>Suppose I have a number <code>15</code> and list of numbers: </p>
<pre><code>[5, 6, 7, 8]
</code></pre>
<p>Now I want to make a list of tuples like</p>
<pre><code>[(15,6), (15,5), (15,7), (15,8)]
</code></pre>
<p>How does one do that quickly?</p>
| 1 | 2016-08-01T08:24:39Z | 38,694,181 | <p>Use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>list_of_nums = [5, 6, 7, 8]
result = [(15, num) for num in list_of_nums]
</code></pre>
<p>Whenever you have a process producing a list based on the output of another sequence, <em>usually</em> a list comprehension can do the job.</p>
<p>Demo:</p>
<pre><code>>>> list_of_nums = [5, 6, 7, 8]
>>> [(15, num) for num in list_of_nums]
[(15, 5), (15, 6), (15, 7), (15, 8)]
</code></pre>
| 2 | 2016-08-01T08:28:40Z | [
"python",
"python-3.x",
"tuples"
] |
tuple one number with list of numbers python | 38,694,107 | <p>Suppose I have a number <code>15</code> and list of numbers: </p>
<pre><code>[5, 6, 7, 8]
</code></pre>
<p>Now I want to make a list of tuples like</p>
<pre><code>[(15,6), (15,5), (15,7), (15,8)]
</code></pre>
<p>How does one do that quickly?</p>
| 1 | 2016-08-01T08:24:39Z | 38,694,584 | <p>You can also try the <code>zip</code> function</p>
<pre><code>result = zip([15]*len(list_of_nums),list_of_nums)
print(result)
[(15, 5), (15, 6), (15, 7), (15, 8)]
</code></pre>
| 1 | 2016-08-01T08:50:33Z | [
"python",
"python-3.x",
"tuples"
] |
Is it thread-safe when using tf.Session in inference service? | 38,694,111 | <p>Now we have used TensorFlow to train and export an model. We can implement the inference service with this model just like how <code>tensorflow/serving</code> does.</p>
<p>I have a question about whether the <code>tf.Session</code> object is thread-safe or not. If it's true, we may initialize the object after starting and use the singleton object to process the concurrent requests.</p>
| 1 | 2016-08-01T08:24:48Z | 38,702,895 | <p>The <code>tf.Session</code> object is thread-safe for <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/client.html#Session.run" rel="nofollow"><code>Session.run()</code></a> calls from multiple threads. </p>
<p>Before TensorFlow 0.10 graph modification was not thread-safe. This was fixed in the 0.10 release, so you can add nodes to the graph concurrently with <code>Session.run()</code> calls, although this is not advised for performance reasons; instead, it is recommended to call <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#Graph.finalize" rel="nofollow"><code>sess.graph.finalize()</code></a> before using the session from multiple threads, to <a class='doc-link' href="http://stackoverflow.com/documentation/tensorflow/3883/how-to-debug-a-memory-leak-in-tensorflow/13426/use-graph-finalize-to-catch-nodes-being-added-to-the-graph#t=20160801153734584585">prevent accidental memory leaks</a>.</p>
| 2 | 2016-08-01T15:39:39Z | [
"python",
"multithreading",
"tensorflow",
"tensorflow-serving"
] |
input-output program doesn't output the correct integer in python 3 | 38,694,281 | <p>So i've designed a program that you write a football(soccer) stat and it prints you the number of the times you write it. Its been working but i have added the option to quit the function which caused me the follow promblems. If you havent write a stat at least once it would crash. So I fixed it but now when i try to run it, it starts to count but it counts 0 too, which it didnt before. Here is only one stat's as i figured it will be unappropriate to copy-paste over 1000 lines of code here:</p>
<pre><code> pk_range_goal = range(0, 1000)
pk_list_goal = list(pk_range_goal)
pk_input = '''goal/saved/missed
'''
def body():
while True:
choice = input("")
first_number_pk_goal = pk_list_goal[0]
integer_pk_number_goal = int(first_number_pk_goal)
if choice == "pk":
good_bad_input_pk = input(pk_input)
if good_bad_input_pk == "goal":
pk_list_goal.remove(first_number_pk_goal)
integer_pk_number_goal = int(first_number_pk_goal)
string_number_pk_goal = str(first_number_pk_goal)
print("Penalty Kick goal(s): ", string_number_pk_goal)
elif choice == "q":
print("Are you sure that you want to finish the stat counting? (yes/no)")
quit_choice = input()
if quit_choice == "yes":
if integer_pk_number_goal >= 1:
print("Penalty Kick goal(s): ", string_number_pk_goal)
elif integer_pk_number_goal == 0:
print("Penalty Kick goal(s): 0")
else:
pass
break
else:
pass
body()
</code></pre>
<p>EDIT: I tried to make the range to start from 1 but then you would need to write it twice in order to go to 2</p>
<p>Complete</p>
<pre><code> # -----> * INTRODUCTION * <-----
Commands = ''' STAT ------------> COMMAND
Penalty Kick -----> pk
-> Goal ----------> goal
-> Saved ---------> saved
-> Missed --------> missed
Free Kick --------> fk
Corner Kick ------> ck
Throw In ---------> ti
Cross ------------> cross
-> Good Delivery -> gd
-> Good Delivery -> pd
1 versus 1 ------> 1v1
-> Won ----------> w
-> Lost ---------> l
Shot ------------> shot
Header ----------> header
-> On Target ----> on target
-> Off Target ---> off target
Save ------------> save
To quit press q
'''
print(Commands)
# -----> * Penalty Kicks Variables * <-----
pk_range = range(0, 1000)
pk_list = list(pk_range)
pk_range_goal = range(0, 1000)
pk_list_goal = list(pk_range_goal)
pk_range_saved = range(0, 1000)
pk_list_saved = list(pk_range_saved)
pk_range_missed = range(0, 1000)
pk_list_missed = list(pk_range_missed)
pk_input = '''goal/saved/missed
'''
# -----> * Free Kicks Variables <-----
fk_range = range(0, 1000)
fk_list = list(fk_range)
fk_range_gd = range(0, 1000)
fk_list_gd = list(fk_range_gd)
fk_range_pd = range(0, 1000)
fk_list_pd = list(fk_range_pd)
fk_input = '''gd/pd
'''
# -----> * Corner Kicks Variables * <-----
ck_range = range(0, 1000)
ck_list = list(ck_range)
ck_range_gd = range(0, 1000)
ck_list_gd = list(ck_range_gd)
ck_range_pd = range(0, 1000)
ck_list_pd = list(ck_range_pd)
ck_input = '''gd/pd
'''
# -----> * Throw Ins Variables * <-----
ti_range = range(0, 1000)
ti_list = list(ti_range)
ti_range_gd = range(0, 1000)
ti_list_gd = list(ti_range_gd)
ti_range_pd = range(0, 1000)
ti_list_pd = list(ti_range_pd)
ti_input = '''gd/pd
'''
# -----> * Crosses Variables * <-----
crosses_range = range(0, 1000)
crosses_list = list(crosses_range)
crosses_range_gd = range(0, 1000)
crosses_list_gd = list(crosses_range_gd)
crosses_range_pd = range(0, 1000)
crosses_list_pd = list(crosses_range_pd)
crosses_input = '''gd/pd
'''
# -----> * 0 vs 0 Variables * <-----
v1_range = range(0, 1000)
v1_list = list(v1_range)
v1_range_w = range(0, 1000)
v1_list_w = list(v1_range_w)
v1_range_l = range(0, 1000)
v1_list_l = list(v1_range_l)
v1_input = '''w/l
'''
# -----> * Shots Variables * <-----
shots_range = range(0, 1000)
shots_list = list(shots_range)
shots_range_gd = range(0, 1000)
shots_list_gd = list(shots_range_gd)
shots_range_pd = range(0, 1000)
shots_list_pd = list(shots_range_pd)
shots_input = '''on target/off target
'''
# -----> * Headers Variables * <-----
headers_range = range(0, 1000)
headers_list = list(headers_range)
headers_range_gd = range(0, 1000)
headers_list_gd = list(headers_range_gd)
headers_range_pd = range(0, 1000)
headers_list_pd = list(headers_range_pd)
headers_input = '''on target/off target
'''
# -----> * Saves Variables * <-----
saves_range = range(1, 1000)
saves_list = list(saves_range)
# -----> * Long Pass Variables * <-----
long_passes_range = range(1, 1000)
long_passes_list = list(long_passes_range)
long_passes_range_first_touch = range(1, 1000)
long_passes_list_first_touch = list(long_passes_range_first_touch)
long_passes_range_second_touch = range(1, 1000)
long_passes_list_second_touch = list(long_passes_range_second_touch)
long_passes_input = '''first touch/second touch
'''
# -----> * Main Function * <-----
def body():
while True:
choice = input("")
# -----> * Penalty Kicks Goal Variables * <-----
# -----> * Penalty Kicks Missed Variables * <-----
first_number_pk_missed = pk_list_missed[0]
integer_pk_number_missed = int(first_number_pk_missed)
number_pk_missed = integer_pk_number_missed - 1
string_number_pk_missed = str(number_pk_missed)
# -----> * Penalty Kicks Saved Variables * <-----
first_number_pk_saved = pk_list_saved[0]
integer_pk_number_saved = int(first_number_pk_saved)
number_pk_saved = integer_pk_number_saved - 1
string_number_pk_saved = str(number_pk_saved)
# -----> * Total Penalty Kicks Variables * <-----
first_number_pk = pk_list[0]
integer_pk_number = int(first_number_pk)
number_pk = integer_pk_number - 1
string_number_pk = str(number_pk)
# -----> * Penalty Kicks Function * <-----
first_number_pk_goal = pk_list_goal[0]
integer_pk_number_goal = int(first_number_pk_goal)
if choice == "pk":
good_bad_input_pk = input(pk_input)
if good_bad_input_pk == "goal":
integer_pk_number_goal = 0
string_number_pk_goal = str(first_number_pk_goal)
pk_list_goal.remove(first_number_pk_goal)
print("Penalty Kick goal(s): ", string_number_pk_goal)
elif good_bad_input_pk == "saved":
print("Penalty Kick(s) saved: ", string_number_pk_saved)
elif good_bad_input_pk == "missed":
print("Penalty Kick(s) missed: ", string_number_pk_missed)
else:
pass
print("Penalty Kick(s) : ", string_number_pk)
# -----> * Free Kicks with Good Delivery Variables * <-----
first_number_fk_gd = fk_list_gd[0]
integer_fk_number_gd = int(first_number_fk_gd)
number_fk_gd = integer_fk_number_gd - 1
string_number_fk_gd = str(number_fk_gd)
# -----> * Free Kicks with Poor Delivery Variables * <-----
first_number_fk_pd = fk_list_pd[0]
integer_fk_number_pd = int(first_number_fk_pd)
number_fk_pd = integer_fk_number_pd - 1
string_number_fk_pd = str(number_fk_pd)
# -----> * Free Kicks Variables * <-----
first_number_pk = pk_list[0]
integer_pk_number = int(first_number_pk)
number_pk = integer_pk_number - 1
string_number_pk = str(number_pk)
# -----> * Free Kicks Function * <-----
if choice == "fk":
good_bad_input_fk = input(fk_input)
if good_bad_input_fk == "gd":
print("Free Kick(s) with a Good Delivery: ", string_number_fk_gd)
elif good_bad_input_fk == "pd":
print("Free Kick(s) with a Poor Delivery: ", string_number_fk_pd)
else:
pass
print("Free Kick(s)", string_number_fk)
# -----> * Corner Kick Variables * <-----
elif choice == "ck":
good_bad_input_ck = input(ck_input)
if good_bad_input_ck == "gd":
first_number_ck_gd = ck_list_gd[0]
ck_list_gd.remove(first_number_ck_gd)
number_ck_gd = ck_list_gd[0]
string_number_ck_gd = str(number_ck_gd)
print("Corner Kick(s) with a Good Delivery: ", string_number_ck_gd)
elif good_bad_input_ck == "pd":
first_number_ck_pd = ck_list_pd[0]
ck_list_pd.remove(first_number_ck_pd)
number_ck_pd = ck_list_pd[0]
string_number_ck_pd = str(number_ck_pd)
print("Corner Kick(s) with a Poor Delivery: ", string_number_ck_pd)
else:
pass
first_number_ck = ck_list[0]
ck_list.remove(first_number_ck)
number_ck = ck_list[0]
string_number_ck = str(number_ck)
print("Corner Kick(s): ", string_number_ck)
# -----> * Throw Ins Functions * <-----
elif choice == "ti":
good_bad_input_ti = input(ti_input)
if good_bad_input_ti == "gd":
first_number_ti_gd = ti_list_gd[0]
ti_list_gd.remove(first_number_ti_gd)
number_ti_gd = ti_list_gd[0]
string_number_ti_gd = str(number_ti_gd)
print("Throw In(s) with a Good Delivery: ", string_number_ti_gd)
elif good_bad_input_ti == "pd":
first_number_ti_pd = ti_list_pd[0]
ti_list_pd.remove(first_number_ti_pd)
number_ti_pd = ti_list_pd[0]
string_number_ti_pd = str(number_ti_pd)
print("Throw In(s) with a Poor Delivery: ", string_number_ti_pd)
else:
pass
first_number_ti = ti_list[0]
ti_list.remove(first_number_ti)
number_ti = ti_list[0]
string_number_ti = str(number_ti)
print("Throw In(s): ", string_number_ti)
# -----> * Crosses Function * <-----
elif choice == "cross":
good_bad_input_crosses = input(crosses_input)
if good_bad_input_crosses == "gd":
first_number_crosses_gd = crosses_list_gd[0]
crosses_list_gd.remove(first_number_crosses_gd)
number_crosses_gd = crosses_list_gd[0]
string_number_crosses_gd = str(number_crosses_gd)
print("Cross(es) with a Good Delivery: ", string_number_crosses_gd)
elif good_bad_input_crosses == "pd":
first_number_crosses_pd = crosses_list_pd[0]
crosses_list_pd.remove(first_number_crosses_pd)
number_crosses_pd = crosses_list_pd[0]
string_number_crosses_pd = str(number_crosses_pd)
print("Cross(es) with a Good Delivery: ", string_number_crosses_pd)
else:
pass
first_number_crosses = crosses_list[0]
crosses_list.remove(first_number_crosses)
number_crosses = crosses_list[0]
string_number_crosses = str(number_crosses)
print("Cross(es): ", string_number_crosses)
# -----> * 1 versus 1 Function * <-----
elif choice == "1v1":
good_bad_input_v1 = input(v1_input)
if good_bad_input_v1 == "w":
first_number_v1_w = v1_list_w[0]
v1_list_w.remove(first_number_v1_w)
number_v1_w = v1_list_w[0]
string_number_v1_w = str(number_v1_w)
print("Won 1vs1: ", string_number_v1_w)
elif good_bad_input_v1 == "l":
first_number_v1_l = v1_list_l[0]
v1_list_l.remove(first_number_v1_l)
number_v1_l = v1_list_l[0]
string_number_v1_l = str(number_v1_l)
print("Lost 1vs1: ", string_number_v1_l)
else:
pass
first_number_v1 = v1_list[0]
v1_list.remove(first_number_v1)
number_v1 = v1_list[0]
string_number_v1 = str(number_v1)
print("1vs1: ", string_number_v1)
# -----> * Shots Function * <-----
elif choice == "shot":
good_bad_input_shots = input(shots_input)
if good_bad_input_shots == "on target":
first_number_shots_gd = shots_list_gd[0]
shots_list_gd.remove(first_number_shots_gd)
number_shots_gd = shots_list_gd[0]
string_number_shots_gd = str(number_shots_gd)
print("Shot(s) on target: ", string_number_shots_gd)
elif good_bad_input_shots == "off target":
first_number_shots_pd = shots_list_pd[0]
shots_list_pd.remove(first_number_shots_pd)
number_shots_pd = shots_list_pd[0]
string_number_shots_pd = str(number_shots_pd)
print("Shot(s) off target: ", string_number_shots_pd)
else:
pass
first_number_shots = shots_list[0]
shots_list.remove(first_number_shots)
number_shots = shots_list[0]
string_number_shots = str(number_shots)
print("Shot(s): ", string_number_shots)
# -----> * Headers Function * <-----
elif choice == "header":
good_bad_input_headers = input(headers_input)
if good_bad_input_headers == "on target":
first_number_headers_gd = headers_list_gd[0]
headers_list_gd.remove(first_number_headers_gd)
number_headers_gd = headers_list_gd[0]
string_number_headers_gd = str(number_headers_gd)
print("Header(s) on target: ", string_number_headers_gd)
elif good_bad_input_headers == "off target":
first_number_headers_pd = headers_list_pd[0]
headers_list_pd.remove(first_number_headers_pd)
number_headers_pd = headers_list_pd[0]
string_number_headers_pd = str(number_headers_pd)
print("Header(s) off target: ", string_number_headers_pd)
else:
pass
first_number_headers = headers_list[0]
headers_list.remove(first_number_headers)
number_headers = headers_list[0]
string_number_headers = str(number_headers)
print("Header(s): ", string_number_headers)
# -----> * Long Passes * <-----
elif choice == "long pass":
good_bad_input_long_passes = input(long_passes_input)
first_number_long_passes = long_passes_list[0]
long_passes_list.remove(first_number_long_passes)
number_long_passes = long_passes_list[0]
string_number_long_passes = str(number_long_passes)
print("Long Pass(es): ", string_number_long_passes)
if good_bad_input_long_passes == "first touch":
first_number_long_passes_first_touch = long_passes_list_first_touch[0]
long_passes_list_first_touch.remove(first_number_long_passes_first_touch)
number_long_passes_first_touch = long_passes_list_first_touch[0]
string_number_long_passes_first_touch = str(number_long_passes_first_touch)
print("Long Pass(es) first touch: ", string_number_long_passes_first_touch)
elif good_bad_input_long_passes == "second touch":
first_number_long_passes_second_touch = long_passes_list_second_touch[0]
long_passes_list_second_touch.remove(first_number_long_passes_second_touch)
number_long_passes_second_touch = long_passes_list_second_touch[0]
string_number_long_passes_second_touch = str(number_long_passes_second_touch)
print("Long Pass(es) second touch: ", string_number_long_passes_second_touch)
else:
pass
# -----> * Saves * <-----
elif choice == "save":
first_number_save = saves_list[0]
saves_list.remove(first_number_save)
number_save = saves_list[0]
string_number_save = str(number_save)
print("Save(s)", string_number_save)
elif choice == "q":
print("Are you sure that you want to finish the stat counting? (yes/no)")
quit_choice = input()
if quit_choice == "yes":
# -----> * Penalty_Kicks_goal_Quit_Function * <-----
if integer_pk_number_goal >= 1:
print("Penalty Kick goal(s): ", string_number_pk_goal)
elif integer_pk_number_goal == 0:
print("Penalty Kick goal(s): 0")
# -----> * Penalty_Kicks_saved_Quit_Function * <-----
if integer_pk_number_saved >= 1:
print("Saved Penalty Kick(s): ", string_number_pk_saved)
elif integer_pk_number_saved == 0:
print("Saved Penalty Kick(s): 0")
# -----> * Penalty_Kicks_missed_Quit_Function * <-----
if integer_pk_number_missed >= 1:
print("Missed Penalty Kick(s): ", string_number_pk_missed)
elif integer_pk_number_missed == 0:
print("Missed Penalty Kick(s): 0")
# -----> * Penalty_Kicks_Quit_Function * <-----
if integer_pk_number >= 1:
print("Penalty Kick(s): ", string_number_pk)
elif integer_pk_number == 0:
print("Penalty Kick(s): 0")
else:
pass
# -----> * Free_Kicks_gd_Quit_Function * <-----
if integer_fk_number_gd >= 1:
print("Free Kick(s) with Good delivery: ", string_number_fk_gd)
elif integer_fk_number_gd == 0:
print("Free Kick(s) with Good delivery: 0")
# -----> * Free_Kicks_Quit_Function * <-----
if integer_fk_number_pd >= 1:
print("Free Kick(s) with Poor delivery: ", string_number_fk_pd)
elif integer_fk_number_pd == 0:
print("Free Kick(s) with Poor delivery: 0")
# -----> * Free_Kicks_Quit_Function * <-----
if integer_fk_number >= 1:
print("Free Kick(s): ", string_number_fk)
elif integer_fk_number == 0:
print("Free Kick(s): 0")
break
elif quit_choice == "no":
pass
else:
pass
body()
</code></pre>
<p>In the complete source code i havent added the quit functionality in all stats as i did in the minimal as it doesnt work and it will be a waste of time. Also, you may find other bugs.</p>
| 0 | 2016-08-01T08:33:40Z | 39,027,292 | <p>try to define the variable as False before they get called and then true </p>
| 0 | 2016-08-18T20:52:13Z | [
"python",
"python-3.x",
"input",
"int",
"output"
] |
F2PY cannot compile Fortran with print or write | 38,694,291 | <p>I'm having problems compiling Fortran into a Python extension module when the Fortran code includes print or write function calls.</p>
<p>I am on Windows 8.1 with gfortran (through mingw-w64) and the MSVC Compiler for Python 2.7 installed. The Python distribution in use is Anaconda.</p>
<p><strong>test.f</strong></p>
<pre><code>subroutine test (a)
integer, intent(out) :: a
print *,"Output from test"
a = 10
end subroutine test
</code></pre>
<p>Running <code>f2py -c -m --fcompiler=gnu95 test test.f90</code> I see these errors:</p>
<pre><code>test.o : error LNK2019: unresolved external symbol _gfortran_st_write referenced in function test_
test.o : error LNK2019: unresolved external symbol _gfortran_transfer_character_write referenced in function test_
test.o : error LNK2019: unresolved external symbol _gfortran_st_write_done referenced in function test_
.\test.pyd : fatal error LNK1120: 3 unresolved externals
</code></pre>
<p>But it works fine when I comment out the print (or write) statement.</p>
<p>A weird thing I've noticed is that it seems to be using Python for ArcGIS.</p>
<pre><code>compile options: '-Ic:\users\[username]\appdata\local\temp\tmpqiq6ay\src.win-amd64-
2.7 -IC:\Python27\ArcGISx6410.3\lib\site-packages\numpy\core\include -IC:\Python
27\ArcGISx6410.3\include -IC:\Python27\ArcGISx6410.3\PC -c'
gfortran.exe:f90: test.f90
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 1 | 2016-08-01T08:34:27Z | 38,711,650 | <p>Answering my own question.</p>
<p>Steps to fix:</p>
<ol>
<li>Ignore or scrub the mingw-w64 install. It wasn't needed as Anaconda
comes with mingw</li>
<li>Add C_INCLUDE_PATH to the Windows system environment variables and point that to the include folder located within the anaconda path (e.g. <code>C:\userdata\[user]\Miniconda\include</code>)</li>
<li>Change <code>--compiler=msvc</code> to <code>--compiler=mingw32</code></li>
<li>In my case, it was attempting to use numpy from the ArcGIS install. To fix, I had to <code>conda uninstall numpy</code>, take note of all the packages it removed, and then <code>conda install [list of packages that were previously removed]</code></li>
</ol>
<p>The Fortran code now compiles perfectly and can be called from Python.</p>
| 0 | 2016-08-02T04:13:24Z | [
"python",
"visual-c++",
"fortran",
"gfortran",
"f2py"
] |
run python script on vagrant up | 38,694,311 | <p>I'm trying to run a vagranfile that will result in a running python flask app. I've tried using this as the last command to achieve this -
<code>config.vm.provision :shell, :path => "python app.py"</code>
But it resulted with the following error - </p>
<p><code>*</code>path<code>for shell provisioner does not exist on the host system: /Users/*****/code/app-vagrant/python app.py</code></p>
<p>I understand that the script is trying to run this command from the host machine, how do I make Vagrant run the script on the vagrant machine launched?</p>
| 2 | 2016-08-01T08:35:30Z | 38,695,172 | <p>you have 2 options to run a script using the <a href="https://www.vagrantup.com/docs/provisioning/shell.html" rel="nofollow">vagrant shell provisioner</a> you must pass either the <code>inline</code> or <code>path</code> argument:</p>
<blockquote>
<p><em>inline</em> (string) - Specifies a shell command inline to execute on the remote machine.</p>
<p><em>path</em> (string) - Path to a shell script to upload and execute. It can be a script relative to the project Vagrantfile or a remote script (like a gist).</p>
</blockquote>
<p>so when you pass <code>:path => "python app.py"</code> the system tries to find a script named <code>python app.py</code> on your host.</p>
<p>replace using <code>inline</code> argument and it will achieve what you want</p>
<pre><code>config.vm.provision :shell, :inline => "python app.py"
</code></pre>
<p>note: provisioner are run as <code>root</code> user by default, if you want to change and run it as <code>vagrant</code> user:</p>
<pre><code>config.vm.provision :shell, :inline => "python app.py", :privileged => false
</code></pre>
| 2 | 2016-08-01T09:21:07Z | [
"python",
"vagrant",
"vagrantfile"
] |
run python script on vagrant up | 38,694,311 | <p>I'm trying to run a vagranfile that will result in a running python flask app. I've tried using this as the last command to achieve this -
<code>config.vm.provision :shell, :path => "python app.py"</code>
But it resulted with the following error - </p>
<p><code>*</code>path<code>for shell provisioner does not exist on the host system: /Users/*****/code/app-vagrant/python app.py</code></p>
<p>I understand that the script is trying to run this command from the host machine, how do I make Vagrant run the script on the vagrant machine launched?</p>
| 2 | 2016-08-01T08:35:30Z | 38,695,219 | <p>If you want to start app when the machine start, you can do that:</p>
<ol>
<li><p>move your <code>python app code directory</code> to the Vagrantfile's directory </p></li>
<li><p>Config the Vagrantfile like that:</p>
<pre><code>config.vm.provision "shell", inline: <<-SHELL
python /vagrant/<your python app code directory>/app.py
SHELL
</code></pre></li>
</ol>
| 1 | 2016-08-01T09:23:00Z | [
"python",
"vagrant",
"vagrantfile"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.