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
Scrapy: overwrite DEPTH_LIMIT variable based on value read from custom config
38,635,787
<p>I am using <code>InitSpider</code> and read a custom <code>json</code> configuration within the <code>def __init__(self, *a, **kw):</code> method.</p> <p>The json config file contains a directive with which I can control the crawling depth. I can already successfully read this configuration file and extract the value. The main problem is how to tell scrapy to use this value.</p> <p>Note: I dont want to use a command line argument such as <code>-s DEPTH_LIMIT=3</code>, I actually want to parse it from my custom configuration.</p>
0
2016-07-28T12:01:54Z
38,734,764
<p><code>DEPTH_LIMIT</code> is used in <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/spidermiddlewares/depth.py" rel="nofollow"><code>scrapy.spidermiddlewares.depth.DepthMiddleware</code></a>. As you might have had a quick look at the code, you'll see that the <code>DEPTH_LIMIT</code> value is read only when initializing that middleware.</p> <p>I think this might be a good solution to you:</p> <ol> <li>In the <code>__init__</code> method of your spider, set a spider attribute <code>max_depth</code> with your custom value.</li> <li>Override <code>scrapy.spidermiddlewares.depth.DepthMiddleware</code> and have it check the <code>max_depth</code> attribute.</li> <li>Disable the default <code>DepthMiddleware</code> and enable your own one in the settings.</li> </ol> <p>See also <a href="http://doc.scrapy.org/en/latest/topics/spider-middleware.html" rel="nofollow">http://doc.scrapy.org/en/latest/topics/spider-middleware.html</a></p> <p>A quick example of the overridden middleware described in step #2:</p> <pre><code>class MyDepthMiddleware(DepthMiddleware): def process_spider_output(self, response, result, spider): if hasattr(spider, 'max_depth'): self.maxdepth = getattr(spider, 'max_depth') return super(MyDepthMiddleware, self).process_spider_output(response, result, spider) </code></pre>
1
2016-08-03T05:03:18Z
[ "python", "scrapy" ]
Its saying the variable i have defined was "referenced before assignment"
38,635,843
<p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it will say that i go bust however if i don't go bust then the next function(housePlay()) doesn't work, do you know why? This is the error:</p> <pre><code>Traceback (most recent call last): File "F:\Computing\Black Jack.py", line 112, in &lt;module&gt; housePlay() File "F:\Computing\Black Jack.py", line 78, in housePlay print("The house have a",c,"and a",d,"giving them a total of",houseCount) UnboundLocalError: local variable 'houseCount' referenced before assignment </code></pre> <p>p.s I'm quite new to coding so please use simple terms so that i can understand you</p> <pre><code> import random playerCount=0 houseCount=0 cards={"Ace of Hearts":1, "Two of Hearts":2, "Three of Hearts":3, "Four of Hearts":4, "Five of Heats":5, "Six of Hearts":6, "Seven of Hearts":7, "Eight of Hearts":8, "Nine of Hearts":9, "Ten of Hearts":10, "Jack of Hearts":10, "Queen of Hearts":10, "King of Hearts":10, "Ace of Diamonds":1, "Two of Diamonds":2, "Three of Diamonds":3, "Four of Diamonds":4, "Five of Diamonds":5, "Six of Diamonds":6, "Seven of Diamonds":7, "Eight of Diamonds":8, "Nine of Diamonds":9, "Ten of Diamonds":10, "Jack of Diamonds":10, "Queen of Diamonds":10, "King of Diamonds":10, "Ace of Spades":1, "Two of Spades":2, "Three of Spades":3, "Four of Spades":4, "Five of Spades":5, "Six of Spades":6, "Seven of Spades":7, "Eight of Spades":8, "Nine of Spades":9, "Ten of Spades":10, "Jack of Spades":10, "Queen of Spades":10, "King of Spades":10, "Ace of Clubs":1, "Two of Clubs":2, "Three of Clubs":3, "Four of Clubs":4, "Five of Clubs":5, "Six of Clubs":6, "Seven of Clubs":7, "Eight of Clubs":8, "Nine of Clubs":9, "Ten of Clubs":10, "Jack of Clubs":10, "Queen of Clubs":10, "King of Clubs":10} temp = [] for i in cards: temp.append(i) a=random.choice(temp) b=random.choice(temp) c=random.choice(temp) d=random.choice(temp) f=random.choice(temp) while a == b: b=random.choice(temp) while c == b or c== a: c=random.choice(temp) while d == b or d== a or d==c: d=random.choice(temp) while f == a or f == b or f == c or f == d: e=random.choice(temp) playerCount+=cards[a] playerCount+=cards[b] houseCount+=cards[c] def housePlay(): print("The house have a",c,"and a",d,"giving them a total of",houseCount) if houseCount&lt;17: print("The house hits and gets a",f) houseCount+=cards[f] if houseCount&gt;21: print("The house go bust, you win") else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") else: print("The house stay with a total of",houseCount) if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") print("Your cards:",a," and ",b,"Which add to ",playerCount) print("Dealers card:",c,"Which adds to ",houseCount) play=input("Would you like to Hit or Stand?") if play=="hit": e=random.choice(temp) while e == a or e== b or e==c or e==d or e == f: e=random.choice(temp) playerCount+=cards[e] if playerCount&gt;21: print("You were dealt a",e) print("Unlucky you have gone bust") else: housePlay() elif play=="stand": houseCount+=cards[d] if houseCount&lt;17: housePlay() else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") </code></pre>
1
2016-07-28T12:03:45Z
38,636,202
<p>For now, just do <code>global houseCount</code> within the <code>housePlay()</code> function - that should get you over the hump. </p>
1
2016-07-28T12:20:42Z
[ "python", "python-3.x", "blackjack" ]
Its saying the variable i have defined was "referenced before assignment"
38,635,843
<p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it will say that i go bust however if i don't go bust then the next function(housePlay()) doesn't work, do you know why? This is the error:</p> <pre><code>Traceback (most recent call last): File "F:\Computing\Black Jack.py", line 112, in &lt;module&gt; housePlay() File "F:\Computing\Black Jack.py", line 78, in housePlay print("The house have a",c,"and a",d,"giving them a total of",houseCount) UnboundLocalError: local variable 'houseCount' referenced before assignment </code></pre> <p>p.s I'm quite new to coding so please use simple terms so that i can understand you</p> <pre><code> import random playerCount=0 houseCount=0 cards={"Ace of Hearts":1, "Two of Hearts":2, "Three of Hearts":3, "Four of Hearts":4, "Five of Heats":5, "Six of Hearts":6, "Seven of Hearts":7, "Eight of Hearts":8, "Nine of Hearts":9, "Ten of Hearts":10, "Jack of Hearts":10, "Queen of Hearts":10, "King of Hearts":10, "Ace of Diamonds":1, "Two of Diamonds":2, "Three of Diamonds":3, "Four of Diamonds":4, "Five of Diamonds":5, "Six of Diamonds":6, "Seven of Diamonds":7, "Eight of Diamonds":8, "Nine of Diamonds":9, "Ten of Diamonds":10, "Jack of Diamonds":10, "Queen of Diamonds":10, "King of Diamonds":10, "Ace of Spades":1, "Two of Spades":2, "Three of Spades":3, "Four of Spades":4, "Five of Spades":5, "Six of Spades":6, "Seven of Spades":7, "Eight of Spades":8, "Nine of Spades":9, "Ten of Spades":10, "Jack of Spades":10, "Queen of Spades":10, "King of Spades":10, "Ace of Clubs":1, "Two of Clubs":2, "Three of Clubs":3, "Four of Clubs":4, "Five of Clubs":5, "Six of Clubs":6, "Seven of Clubs":7, "Eight of Clubs":8, "Nine of Clubs":9, "Ten of Clubs":10, "Jack of Clubs":10, "Queen of Clubs":10, "King of Clubs":10} temp = [] for i in cards: temp.append(i) a=random.choice(temp) b=random.choice(temp) c=random.choice(temp) d=random.choice(temp) f=random.choice(temp) while a == b: b=random.choice(temp) while c == b or c== a: c=random.choice(temp) while d == b or d== a or d==c: d=random.choice(temp) while f == a or f == b or f == c or f == d: e=random.choice(temp) playerCount+=cards[a] playerCount+=cards[b] houseCount+=cards[c] def housePlay(): print("The house have a",c,"and a",d,"giving them a total of",houseCount) if houseCount&lt;17: print("The house hits and gets a",f) houseCount+=cards[f] if houseCount&gt;21: print("The house go bust, you win") else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") else: print("The house stay with a total of",houseCount) if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") print("Your cards:",a," and ",b,"Which add to ",playerCount) print("Dealers card:",c,"Which adds to ",houseCount) play=input("Would you like to Hit or Stand?") if play=="hit": e=random.choice(temp) while e == a or e== b or e==c or e==d or e == f: e=random.choice(temp) playerCount+=cards[e] if playerCount&gt;21: print("You were dealt a",e) print("Unlucky you have gone bust") else: housePlay() elif play=="stand": houseCount+=cards[d] if houseCount&lt;17: housePlay() else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") </code></pre>
1
2016-07-28T12:03:45Z
38,636,208
<p><code>def housePlay(houseCount):</code> Pass houseCount as argument in your function defination </p> <pre><code> housePlay(houseCount) </code></pre> <p>call housePlay function like this.</p>
3
2016-07-28T12:21:03Z
[ "python", "python-3.x", "blackjack" ]
Its saying the variable i have defined was "referenced before assignment"
38,635,843
<p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it will say that i go bust however if i don't go bust then the next function(housePlay()) doesn't work, do you know why? This is the error:</p> <pre><code>Traceback (most recent call last): File "F:\Computing\Black Jack.py", line 112, in &lt;module&gt; housePlay() File "F:\Computing\Black Jack.py", line 78, in housePlay print("The house have a",c,"and a",d,"giving them a total of",houseCount) UnboundLocalError: local variable 'houseCount' referenced before assignment </code></pre> <p>p.s I'm quite new to coding so please use simple terms so that i can understand you</p> <pre><code> import random playerCount=0 houseCount=0 cards={"Ace of Hearts":1, "Two of Hearts":2, "Three of Hearts":3, "Four of Hearts":4, "Five of Heats":5, "Six of Hearts":6, "Seven of Hearts":7, "Eight of Hearts":8, "Nine of Hearts":9, "Ten of Hearts":10, "Jack of Hearts":10, "Queen of Hearts":10, "King of Hearts":10, "Ace of Diamonds":1, "Two of Diamonds":2, "Three of Diamonds":3, "Four of Diamonds":4, "Five of Diamonds":5, "Six of Diamonds":6, "Seven of Diamonds":7, "Eight of Diamonds":8, "Nine of Diamonds":9, "Ten of Diamonds":10, "Jack of Diamonds":10, "Queen of Diamonds":10, "King of Diamonds":10, "Ace of Spades":1, "Two of Spades":2, "Three of Spades":3, "Four of Spades":4, "Five of Spades":5, "Six of Spades":6, "Seven of Spades":7, "Eight of Spades":8, "Nine of Spades":9, "Ten of Spades":10, "Jack of Spades":10, "Queen of Spades":10, "King of Spades":10, "Ace of Clubs":1, "Two of Clubs":2, "Three of Clubs":3, "Four of Clubs":4, "Five of Clubs":5, "Six of Clubs":6, "Seven of Clubs":7, "Eight of Clubs":8, "Nine of Clubs":9, "Ten of Clubs":10, "Jack of Clubs":10, "Queen of Clubs":10, "King of Clubs":10} temp = [] for i in cards: temp.append(i) a=random.choice(temp) b=random.choice(temp) c=random.choice(temp) d=random.choice(temp) f=random.choice(temp) while a == b: b=random.choice(temp) while c == b or c== a: c=random.choice(temp) while d == b or d== a or d==c: d=random.choice(temp) while f == a or f == b or f == c or f == d: e=random.choice(temp) playerCount+=cards[a] playerCount+=cards[b] houseCount+=cards[c] def housePlay(): print("The house have a",c,"and a",d,"giving them a total of",houseCount) if houseCount&lt;17: print("The house hits and gets a",f) houseCount+=cards[f] if houseCount&gt;21: print("The house go bust, you win") else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") else: print("The house stay with a total of",houseCount) if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") print("Your cards:",a," and ",b,"Which add to ",playerCount) print("Dealers card:",c,"Which adds to ",houseCount) play=input("Would you like to Hit or Stand?") if play=="hit": e=random.choice(temp) while e == a or e== b or e==c or e==d or e == f: e=random.choice(temp) playerCount+=cards[e] if playerCount&gt;21: print("You were dealt a",e) print("Unlucky you have gone bust") else: housePlay() elif play=="stand": houseCount+=cards[d] if houseCount&lt;17: housePlay() else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") </code></pre>
1
2016-07-28T12:03:45Z
38,636,260
<p>Add <code>global houseCount</code> at the beginning of your function <code>housePlay()</code> </p> <p>Explanation : as it is said in a comment, the variable you are trying to look at, <code>houseCount</code>, is not found in the function before being assigned a value. You can use the other variables (<code>a</code>, <code>d</code>) without troubles, because they are not modified in the function.<br> As you change <code>houseCount</code>'s value in the function, you must declare it as global, so the function knows the variable is already defined on the global scope.</p>
1
2016-07-28T12:22:52Z
[ "python", "python-3.x", "blackjack" ]
Its saying the variable i have defined was "referenced before assignment"
38,635,843
<p>I'm trying to make a simple blackjack game using python 3.4.3. So far i have introduced options such as split or the fact the an ace can be either a 1 or 11. I get to the problem where after the program has told me my cards and the houses cards and i say i want to hit, if the next card i get gets me bust then it will say that i go bust however if i don't go bust then the next function(housePlay()) doesn't work, do you know why? This is the error:</p> <pre><code>Traceback (most recent call last): File "F:\Computing\Black Jack.py", line 112, in &lt;module&gt; housePlay() File "F:\Computing\Black Jack.py", line 78, in housePlay print("The house have a",c,"and a",d,"giving them a total of",houseCount) UnboundLocalError: local variable 'houseCount' referenced before assignment </code></pre> <p>p.s I'm quite new to coding so please use simple terms so that i can understand you</p> <pre><code> import random playerCount=0 houseCount=0 cards={"Ace of Hearts":1, "Two of Hearts":2, "Three of Hearts":3, "Four of Hearts":4, "Five of Heats":5, "Six of Hearts":6, "Seven of Hearts":7, "Eight of Hearts":8, "Nine of Hearts":9, "Ten of Hearts":10, "Jack of Hearts":10, "Queen of Hearts":10, "King of Hearts":10, "Ace of Diamonds":1, "Two of Diamonds":2, "Three of Diamonds":3, "Four of Diamonds":4, "Five of Diamonds":5, "Six of Diamonds":6, "Seven of Diamonds":7, "Eight of Diamonds":8, "Nine of Diamonds":9, "Ten of Diamonds":10, "Jack of Diamonds":10, "Queen of Diamonds":10, "King of Diamonds":10, "Ace of Spades":1, "Two of Spades":2, "Three of Spades":3, "Four of Spades":4, "Five of Spades":5, "Six of Spades":6, "Seven of Spades":7, "Eight of Spades":8, "Nine of Spades":9, "Ten of Spades":10, "Jack of Spades":10, "Queen of Spades":10, "King of Spades":10, "Ace of Clubs":1, "Two of Clubs":2, "Three of Clubs":3, "Four of Clubs":4, "Five of Clubs":5, "Six of Clubs":6, "Seven of Clubs":7, "Eight of Clubs":8, "Nine of Clubs":9, "Ten of Clubs":10, "Jack of Clubs":10, "Queen of Clubs":10, "King of Clubs":10} temp = [] for i in cards: temp.append(i) a=random.choice(temp) b=random.choice(temp) c=random.choice(temp) d=random.choice(temp) f=random.choice(temp) while a == b: b=random.choice(temp) while c == b or c== a: c=random.choice(temp) while d == b or d== a or d==c: d=random.choice(temp) while f == a or f == b or f == c or f == d: e=random.choice(temp) playerCount+=cards[a] playerCount+=cards[b] houseCount+=cards[c] def housePlay(): print("The house have a",c,"and a",d,"giving them a total of",houseCount) if houseCount&lt;17: print("The house hits and gets a",f) houseCount+=cards[f] if houseCount&gt;21: print("The house go bust, you win") else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") else: print("The house stay with a total of",houseCount) if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") print("Your cards:",a," and ",b,"Which add to ",playerCount) print("Dealers card:",c,"Which adds to ",houseCount) play=input("Would you like to Hit or Stand?") if play=="hit": e=random.choice(temp) while e == a or e== b or e==c or e==d or e == f: e=random.choice(temp) playerCount+=cards[e] if playerCount&gt;21: print("You were dealt a",e) print("Unlucky you have gone bust") else: housePlay() elif play=="stand": houseCount+=cards[d] if houseCount&lt;17: housePlay() else: if playerCount&gt;houseCount: print("Unlucky, the house total is larger than yours so you lose") elif playerCount==houseCount: print("You have then same total as the house so you get your money back") else: print("Your total is larger than the house's so you win") </code></pre>
1
2016-07-28T12:03:45Z
38,649,379
<p>A good design practice to follow when coding in Python is to break up as much as possible into small, self-contained functions. This is what you have started to do with your <code>housePlay</code> function. Unfortunately for you and your code, Python also has <strong>scoping rules</strong>. That is, a variable defined within a function is local to that function (can't be seen from outside the function), and variables called from within a function are first looked up within the enclosing function (<strong>L</strong>), then any enclosing function (<strong>E</strong>), then the top level of a module file or global (<strong>G</strong>), then built-in (<strong>B</strong>). See the top answer here - <a href="http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules">Short Description of Python Scoping Rules</a></p> <p>In your case, you just have a python script, not a module. A module has an associated <code>__init__.py</code> file in the same directory. Because of this, the variables you have defined at the top level of the file (<code>playerCount</code>, <code>houseCount</code> etc) won't be visible from within each function. (It can't be found in <strong>L</strong>, there is no <strong>E</strong>, you do not have a module and haven't defined them as global (<strong>G</strong>). This is the cause of your "variable referenced before assignment" error.</p> <p>It is good practice to pass any objects (variables) needed by a function to the function as function <strong>arguments</strong>:</p> <pre><code>def housePlay(playerCount, houseCount): ....some code here.... </code></pre> <p>You would need to call this function as:</p> <pre><code>housePlay(playerCount, houseCount) </code></pre> <p>Alternatively, you can define each top-level variable as <code>global</code>:</p> <pre><code>global playerCount = 0 global houseCount = 0 </code></pre> <p>Possibly the better option is to use the <code>if __name__ == '__main__':</code> construct.This looks like this:</p> <pre><code>import random def main(): playerCount = 0 houseCount = 0 ...rest of your code... if __name__ == '__main__': main() </code></pre> <p>All your code is contained within the <code>main()</code> function (although you would usually have other functions defined alongside <code>main</code>), and if you are running the script directly and not importing it as part of another script (that's what the <code>if __name__ == '__main__'</code> does) it will just run everything in the <code>main()</code> function.</p> <p>Doing things this way will ensure that any inner functions (such as <code>housePlay</code>) can see the variables defined in your enclosing (<strong>E</strong>) scope (in this case, the <code>main</code> function).</p>
0
2016-07-29T01:59:51Z
[ "python", "python-3.x", "blackjack" ]
better maintainable way to combine strings from multiple options
38,635,893
<p>I have a scenario where the user can pass in multiple options. For each option passed in, I will get the text and then finally merge the text from multiple options and return a single string. Here is how I'm doing it for three options that I accept today. The code already looks unmaintainable and as I add more options, the logic will get worse:</p> <pre><code>if (len(self.options.passedin.split(",")) &gt; 0): #multiple options were passed in ops = self.options.passedin.split(",") for op in ops: if (op == "option1"): op1_text = get_text_for_option1() elif (op == "option2"): op2_text = get_text_for_option2() elif (op == "option3"): op3_text = get_text_for_option3() #all three were passed in if ("option1" in ops and "option2" in ops and "option3" in ops): op1_op2 = op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split()) op3_op1_op2 = op1_op2 + " " + ' '.join(w for w in op1_op2.split() if w not in op3_text.split()) return op3_op1_op2 #option1 and option2 were passed in elif ("option1" in ops and "option2" in ops and "option3" not in ops): return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split()) #option1 and option3 were passed in elif ("option1" in ops and "option3" in ops and "option2" not in ops): return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op3_text.split()) #option2 and option3 were passed in elif ("option2" in ops and "option3" in ops and "option1" not in ops): return op2_text + " " + ' '.join(w for w in op2_text.split() if w not in op3_text.split()) </code></pre> <p>The methods <code>get_text_for_option1</code> <code>get_text_for_option2</code> <code>get_text_for_option3</code> can't be combined. </p>
0
2016-07-28T12:06:20Z
38,636,177
<p>Use a <code>dict</code> to map your option names to the appropriate function which returns the option text, join those together, then take the unique words, eg:</p> <pre><code>from collections import OrderedDict options = { 'option1': get_text_for_option1, 'option2': get_text_for_option2, 'option3': get_text_for_option3 } input_text = 'option3,option1,option2' all_text = ' '.join(options[opt]() for opt in input_text.split(',')) unique = ' '.join(OrderedDict.fromkeys(all_text.split())) </code></pre>
2
2016-07-28T12:19:29Z
[ "python", "python-2.7", "dry" ]
better maintainable way to combine strings from multiple options
38,635,893
<p>I have a scenario where the user can pass in multiple options. For each option passed in, I will get the text and then finally merge the text from multiple options and return a single string. Here is how I'm doing it for three options that I accept today. The code already looks unmaintainable and as I add more options, the logic will get worse:</p> <pre><code>if (len(self.options.passedin.split(",")) &gt; 0): #multiple options were passed in ops = self.options.passedin.split(",") for op in ops: if (op == "option1"): op1_text = get_text_for_option1() elif (op == "option2"): op2_text = get_text_for_option2() elif (op == "option3"): op3_text = get_text_for_option3() #all three were passed in if ("option1" in ops and "option2" in ops and "option3" in ops): op1_op2 = op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split()) op3_op1_op2 = op1_op2 + " " + ' '.join(w for w in op1_op2.split() if w not in op3_text.split()) return op3_op1_op2 #option1 and option2 were passed in elif ("option1" in ops and "option2" in ops and "option3" not in ops): return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split()) #option1 and option3 were passed in elif ("option1" in ops and "option3" in ops and "option2" not in ops): return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op3_text.split()) #option2 and option3 were passed in elif ("option2" in ops and "option3" in ops and "option1" not in ops): return op2_text + " " + ' '.join(w for w in op2_text.split() if w not in op3_text.split()) </code></pre> <p>The methods <code>get_text_for_option1</code> <code>get_text_for_option2</code> <code>get_text_for_option3</code> can't be combined. </p>
0
2016-07-28T12:06:20Z
38,642,258
<pre><code>if (len(self.options.passedin.split(",")) &gt; 0): #multiple options were passed in ops = self.options.passedin.split(",") opts = { 'op1': get_text_for_option1() if 'option1' in ops else ' ' 'op2': get_text_for_option2() if 'option2' in ops else ' ' 'op3': get_text_for_option3() if 'option3' in ops else ' ' } return (opts['op1'] + opts['op2'] + opts['op3']).strip() </code></pre>
0
2016-07-28T16:44:11Z
[ "python", "python-2.7", "dry" ]
Python class, data structure and proper architecture
38,635,975
<p>I'm writing a program, which request user information from different services, puts them together in some ways. manages stuff and does some slack interaction. All my python projects get problematic at a certain size. imports start to become recursive and handling data around becomes annoying. </p> <p>A quick example of a problem I just come across can be shown with this simple example. I have a main module (here A) which creates the main objects (singletons). These objects need to call functions from each other, so I use main as a connector. In this given example I don't understand when B is created the list that it requests from A is (None) NoneType. The getter function is not necessarily the way I go, but it helped in another situation. Do you have any tips, reads to point, how to structure middle-sized python programs. Thanks!</p> <pre><code>import B some_list = None b = None def get_list(): return some_list if __name__ == "__main__": some_list = [1,2,3] b = B.B() print b.my_list </code></pre> <p>And module B</p> <pre><code>from A import get_list class B: def __init__(self): self.my_list = get_list().map(lambda v : v * 2) # CRASH HERE! </code></pre>
0
2016-07-28T12:10:40Z
38,636,063
<p>You have <strong>two</strong> copies of the main module now, each a separate entry in <code>sys.modules</code>:</p> <ol> <li><p>The initial Python script, started from the command-line, is always called <code>__main__</code>.</p></li> <li><p>You imported the <code>A.py</code> file as the <code>A</code> module. This is <strong>separate</strong> from the <code>__main__</code> module.</p></li> </ol> <p>Yes, the same source file provided both modules, but Python sees them as distinct.</p> <p>As a result, that second copy does not have the <code>if __name__ == '__main__':</code> block executed, because the <code>__name__</code> variable is set to <code>'A'</code> instead. As such, <code>A.some_list</code> and <code>A.b</code> remain set to <code>None</code>; you wanted <code>__main__.some_list</code> and <code>__main__.b</code> instead.</p> <p>Don't put code in your main entry point that other modules need to import to have access to. <em>Pass in such dependencies</em>, or have them managed by a separate module that both the main module and other modules can import.</p> <p>You could, for example, pass in the function to the <code>B()</code> class:</p> <pre><code>b = B.B(get_list) </code></pre>
3
2016-07-28T12:14:59Z
[ "python", "import", "architecture" ]
How to implement non overlapping rolling functionality on MultiIndex DataFrame
38,636,293
<p>So far I've found <a href="http://stackoverflow.com/questions/25879735/how-to-implement-a-function-with-non-overlapping-and-rolling-features-simultaneo">this question</a> but it doesn't solve my problem due to the facts that: </p> <ol> <li>I have a MultiIndex DataFrame </li> <li>The inner level has different amount of data for each outer level, thus I can't use <code>len()</code></li> </ol> <p>I have the following DataFrame</p> <pre><code>Outer Inner Value A 1 2.000000 A 2 4.000000 A 3 6.000000 A 4 8.000000 B 1 3.000000 B 2 6.000000 B 3 9.000000 B 4 12.000000 B 5 15.000000 </code></pre> <p>I want to sum the last two values for each <code>outer</code> in a non-overlapping manner. So for <code>A</code> I want to sum <code>inner</code>'s 3 + 4, 1 + 2. For <code>B</code> I want to sum <code>inner</code>'s 4 + 5, 2 + 3. Note that the pairwise sum is supposed to start from the last value. Resulting in </p> <pre><code>Outer Inner Value A 2 6.000000 A 4 14.000000 B 3 15.000000 B 5 27.000000 </code></pre>
1
2016-07-28T12:24:26Z
38,637,845
<p>Ok, roll up your sleeve, this takes a bit of work:</p> <pre><code>new_level0 = [] new_level1 = [] new_values = [] for level0 in df.index.levels[0].values: #this will loop with A and B #retrieve the values level1_values = df[level0]['Value'].values #retrieve the index, we will keep some of the values of it level1_index = df[level0].index.values #split the values into two vectors #reverse so that it starts pairing values from the end level1_even = [i for enum,i in enumerate(level1_values) if enum%2==0].reverse() level1_odd = [i for enum,i in enumerate(level1_values) if enum%2==1].reverse() # # #sum and reverse again to bring back to normal order summed = [i+j for i,j in zip(level1_even,level1_odd)] summed.reverse() # # #now that we have the values, lets get the index that we need #again, reverse so that we keep the right one level1_index.reverse() #keep only the multiples of two, then undo the reverse new_index = [i for enum,i in enumerate(level1_values) if enum%2==0].reverse() #now store the combination of level0, level1 and value new_level0 += [level0 for i in summed] new_level1 += new_index new_values += summed #your final structure is: s = pd.Series(summed, index= [new_level0, new_level1]) </code></pre>
0
2016-07-28T13:27:18Z
[ "python", "python-3.x", "pandas" ]
How to implement non overlapping rolling functionality on MultiIndex DataFrame
38,636,293
<p>So far I've found <a href="http://stackoverflow.com/questions/25879735/how-to-implement-a-function-with-non-overlapping-and-rolling-features-simultaneo">this question</a> but it doesn't solve my problem due to the facts that: </p> <ol> <li>I have a MultiIndex DataFrame </li> <li>The inner level has different amount of data for each outer level, thus I can't use <code>len()</code></li> </ol> <p>I have the following DataFrame</p> <pre><code>Outer Inner Value A 1 2.000000 A 2 4.000000 A 3 6.000000 A 4 8.000000 B 1 3.000000 B 2 6.000000 B 3 9.000000 B 4 12.000000 B 5 15.000000 </code></pre> <p>I want to sum the last two values for each <code>outer</code> in a non-overlapping manner. So for <code>A</code> I want to sum <code>inner</code>'s 3 + 4, 1 + 2. For <code>B</code> I want to sum <code>inner</code>'s 4 + 5, 2 + 3. Note that the pairwise sum is supposed to start from the last value. Resulting in </p> <pre><code>Outer Inner Value A 2 6.000000 A 4 14.000000 B 3 15.000000 B 5 27.000000 </code></pre>
1
2016-07-28T12:24:26Z
38,637,883
<h1>Groupby with custom resample function</h1> <p>You will most likely need custom resampling to do this. It is a little <em>hacky</em> but might work.</p> <ol> <li>Remove all <code>MulitIndex</code>ing to deal with just regular column <code>groupby()</code>s</li> <li><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>groupby()</code></a> <code>'Outer'</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#flexible-apply" rel="nofollow"><code>.apply()</code></a> a custom function to each group</li> <li>The custom function takes a group <ol> <li>Determine the even length of the group</li> <li>Select that length backwards</li> <li>Turn index into seconds</li> <li>Resample the DataFrame every two samples by <a href="https://pandas-docs.github.io/pandas-docs-travis/timeseries.html#resampling" rel="nofollow"><code>resample(...)</code></a><code>.sum()</code></li> <li>Resample the <code>Inner</code> column every two by <a href="https://pandas-docs.github.io/pandas-docs-travis/timeseries.html#resampling" rel="nofollow"><code>resample(...)</code></a><code>.last()</code> to preserve original index numbers</li> <li>Convert index back to '<code>Inner'</code></li> </ol></li> <li>Even though we removed the <code>MultiIndex</code>, a <code>MultiIndex</code> is still returned by <code>groupby(...).apply()</code></li> </ol> <p>Note: There is an issue with <a href="http://pandas.pydata.org/pandas-docs/stable/computation.html#rolling-windows" rel="nofollow"><code>rolling</code></a>, as it <em>slides</em> thru the values instead of <em>stepping thru</em> the values (in a non-overlapping method). Using <a href="https://pandas-docs.github.io/pandas-docs-travis/timeseries.html#resampling" rel="nofollow"><code>resample</code></a> allows this. Resample is time based the index needs to be represented as seconds.</p> <h3>Example</h3> <pre><code>import math import pandas as pd df = pd.DataFrame({ 'Outer': ['A','A','A','A','B','B','B','B','B'], 'Inner': [1,2,3,4,1,2,3,4,5], 'Value': [2.00,4.00,6.00,8.00,3.00,6.00,9.00,12.00,15.00] }) def f(g): even_length = int(2.0 * math.floor(len(g) / 2.0)) every_two_backwards = g.iloc[-even_length:] every_two_backwards.index = pd.TimedeltaIndex(every_two_backwards.index * 1000000000.0) resample_via_sum = every_two_backwards.resample('2s').sum().dropna() resample_via_sum['Inner'] = every_two_backwards.resample('2s').last() resample_via_sum = resample_via_sum.set_index('Inner') return resample_via_sum resampled_df = df.groupby(['Outer']).apply(f) print resampled_df </code></pre> <hr> <pre><code> Value Outer Inner A 2.0 6.0 4.0 14.0 B 3.0 15.0 5.0 27.0 </code></pre>
1
2016-07-28T13:28:19Z
[ "python", "python-3.x", "pandas" ]
Application python.exe had been blocked from accessing graphics devices - OpenCL
38,636,308
<p>I have an OpenCL programm <a href="https://github.com/john-hu/gpgpu/tree/master/opencl/trade" rel="nofollow">here</a>. It works good at Intel integrated GPU but not at NVidia GTX950M. The question is "my windows 10 always saying my app is blocked". These are what I had done and found:</p> <ol> <li><p>I got a GPU crash in my Windows 10 only if I increase work items. So, I had googled a lot of docs about this topic. It only happens to the GPU time exceeded 2 seconds. So, I found TdrDelay registry to increase the size.</p></li> <li><p>After increasing the TdrDelay, I got the "blocked from accessing graphics devices" issue. Again, I had googled that.</p></li> <li><p>Someone said that I should upgrade the NVidia driver. I had done that but no luck.</p></li> <li><p>Someone said that I should slow down the GPU and GPU memory clock through MSI Afterburner. I had tried that and still no luck.</p></li> </ol> <p>Does anyone know how to deal with this issue???</p> <p>My working environment is a Windows PC with the following spec:</p> <ul> <li>CPU: Intel i7 6700HQ</li> <li>GPU: Intel 540 HD and NVidia GTX 950M (with 2G RAM)</li> <li>RAM: 8G</li> <li>OS: Windows 10</li> <li>Programming Language: python with pyopencl</li> </ul>
0
2016-07-28T12:25:10Z
38,656,366
<p>I found the answer finally. We are pretty close to the answer: TdrDelay.</p> <p>In Windows, there is another registry key to disable TDR (Timeout Detection and Recovery): <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff569918(v=vs.85).aspx" rel="nofollow">TdrLevel</a>. Once this registry key set to 0, Windows totally disables the TDR function.</p> <p>Hope this can help other...... :)</p>
0
2016-07-29T10:19:26Z
[ "python", "windows", "opencl", "nvidia" ]
Python Pandas self join for merge cartesian product to produce all combinations and sum
38,636,460
<p>I am brand new to Python, seems like it has a lot of flexibility and is faster than traditional RDBMS systems.</p> <p>Working on a very simple process to create random fantasy teams. I come from an RDBMS background (Oracle SQL) and that does not seem to be optimal for this data processing.</p> <p>I made a dataframe using pandas read from csv file and now have a simple dataframe with two columns -- Player, Salary:</p> <pre><code>` Name Salary 0 Jason Day 11700 1 Dustin Johnson 11600 2 Rory McIlroy 11400 3 Jordan Spieth 11100 4 Henrik Stenson 10500 5 Phil Mickelson 10200 6 Justin Rose 9800 7 Adam Scott 9600 8 Sergio Garcia 9400 9 Rickie Fowler 9200` </code></pre> <p>What I am trying to do via python (pandas) is produce all combinations of 6 players which salary is between a certain amount 45000 -- 50000.</p> <p>In looking up python options, I found the itertools combination interesting, but it would result a massive list of combinations without filtering the sum of salary.</p> <p>In traditional SQL, I would do a massive merge cartesian join w/ SUM, but then I get the players in different spots..</p> <p>Such as A, B, C then, C, B, A..</p> <p>My traditional SQL which doesn't work well enough is something like this:</p> <pre><code>` SELECT distinct ONE.name AS "1", TWO.name AS "2", THREE.name AS "3", FOUR.name AS "4", FIVE.name AS "5", SIX.name AS "6", sum(one.salary + two.salary + three.salary + four.salary + five.salary + six.salary) as salary FROM nl.pgachamp2 ONE,nl.pgachamp2 TWO,nl.pgachamp2 THREE, nl.pgachamp2 FOUR,nl.pgachamp2 FIVE,nl.pgachamp2 SIX where ONE.name != TWO.name and ONE.name != THREE.name and one.name != four.name and one.name != five.name and TWO.name != THREE.name and TWO.name != four.name and two.name != five.name and TWO.name != six.name and THREE.name != four.name and THREE.name != five.name and three.name != six.name and five.name != six.name and four.name != six.name and four.name != five.name and one.name != six.name group by ONE.name, TWO.name, THREE.name, FOUR.name, FIVE.name, SIX.name` </code></pre> <p>Is there a way to do this in Pandas/Python?</p> <p>Any documentation that can be pointed to would be great!</p>
3
2016-07-28T12:31:29Z
38,638,273
<p>I ran this for combinations of 6 and found no teams that satisfied. I used 5 instead.</p> <p>This should get you there:</p> <pre><code>from itertools import combinations import pandas as pd s = df.set_index('Name').squeeze() combos = pd.DataFrame([c for c in combinations(s.index, 5)]) combo_salary = combos.apply(lambda x: s.ix[x].sum(), axis=1) combos[(combo_salary &gt;= 45000) &amp; (combo_salary &lt;= 50000)] </code></pre> <p><a href="http://i.stack.imgur.com/yzx6k.png" rel="nofollow"><img src="http://i.stack.imgur.com/yzx6k.png" alt="enter image description here"></a></p>
2
2016-07-28T13:43:55Z
[ "python", "python-2.7", "pandas", "linear-programming" ]
Python Pandas self join for merge cartesian product to produce all combinations and sum
38,636,460
<p>I am brand new to Python, seems like it has a lot of flexibility and is faster than traditional RDBMS systems.</p> <p>Working on a very simple process to create random fantasy teams. I come from an RDBMS background (Oracle SQL) and that does not seem to be optimal for this data processing.</p> <p>I made a dataframe using pandas read from csv file and now have a simple dataframe with two columns -- Player, Salary:</p> <pre><code>` Name Salary 0 Jason Day 11700 1 Dustin Johnson 11600 2 Rory McIlroy 11400 3 Jordan Spieth 11100 4 Henrik Stenson 10500 5 Phil Mickelson 10200 6 Justin Rose 9800 7 Adam Scott 9600 8 Sergio Garcia 9400 9 Rickie Fowler 9200` </code></pre> <p>What I am trying to do via python (pandas) is produce all combinations of 6 players which salary is between a certain amount 45000 -- 50000.</p> <p>In looking up python options, I found the itertools combination interesting, but it would result a massive list of combinations without filtering the sum of salary.</p> <p>In traditional SQL, I would do a massive merge cartesian join w/ SUM, but then I get the players in different spots..</p> <p>Such as A, B, C then, C, B, A..</p> <p>My traditional SQL which doesn't work well enough is something like this:</p> <pre><code>` SELECT distinct ONE.name AS "1", TWO.name AS "2", THREE.name AS "3", FOUR.name AS "4", FIVE.name AS "5", SIX.name AS "6", sum(one.salary + two.salary + three.salary + four.salary + five.salary + six.salary) as salary FROM nl.pgachamp2 ONE,nl.pgachamp2 TWO,nl.pgachamp2 THREE, nl.pgachamp2 FOUR,nl.pgachamp2 FIVE,nl.pgachamp2 SIX where ONE.name != TWO.name and ONE.name != THREE.name and one.name != four.name and one.name != five.name and TWO.name != THREE.name and TWO.name != four.name and two.name != five.name and TWO.name != six.name and THREE.name != four.name and THREE.name != five.name and three.name != six.name and five.name != six.name and four.name != six.name and four.name != five.name and one.name != six.name group by ONE.name, TWO.name, THREE.name, FOUR.name, FIVE.name, SIX.name` </code></pre> <p>Is there a way to do this in Pandas/Python?</p> <p>Any documentation that can be pointed to would be great!</p>
3
2016-07-28T12:31:29Z
38,638,795
<p>Here's a non-Pandas solution using a simple algorithm. It generates combinations recursively from a list of players sorted by salary. This lets it skip generating combinations that exceed the salary cap.</p> <p>As piRSquared mentions, there are no teams of 6 that fall within the salary limits stated in the question, so I chose limits to generate a small number of teams.</p> <pre><code>#!/usr/bin/env python3 ''' Limited combinations Generate combinations of players whose combined salaries fall within given limits See http://stackoverflow.com/q/38636460/4014959 Written by PM 2Ring 2016.07.28 ''' data = '''\ 0 Jason Day 11700 1 Dustin Johnson 11600 2 Rory McIlroy 11400 3 Jordan Spieth 11100 4 Henrik Stenson 10500 5 Phil Mickelson 10200 6 Justin Rose 9800 7 Adam Scott 9600 8 Sergio Garcia 9400 9 Rickie Fowler 9200 ''' data = [s.split() for s in data.splitlines()] all_players = [(' '.join(u[1:-1]), int(u[-1])) for u in data] all_players.sort(key=lambda t: t[1]) for i, row in enumerate(all_players): print(i, row) print('- '*40) def choose_teams(free, num, team=(), value=0): num -= 1 for i, p in enumerate(free): salary = all_players[p][1] newvalue = value + salary if newvalue &lt;= hi: newteam = team + (p,) if num == 0: if newvalue &gt;= lo: yield newteam, newvalue else: yield from choose_teams(free[i+1:], num, newteam, newvalue) else: break #Salary limits lo, hi = 55000, 60500 #Indices of players that can be chosen for a team free = tuple(range(len(all_players))) for i, (t, s) in enumerate(choose_teams(free, 6), 1): team = [all_players[p] for p in t] names, sals = zip(*team) assert sum(sals) == s print(i, t, names, s) </code></pre> <p><strong>output</strong></p> <pre><code>0 ('Rickie Fowler', 9200) 1 ('Sergio Garcia', 9400) 2 ('Adam Scott', 9600) 3 ('Justin Rose', 9800) 4 ('Phil Mickelson', 10200) 5 ('Henrik Stenson', 10500) 6 ('Jordan Spieth', 11100) 7 ('Rory McIlroy', 11400) 8 ('Dustin Johnson', 11600) 9 ('Jason Day', 11700) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1 (0, 1, 2, 3, 4, 5) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Phil Mickelson', 'Henrik Stenson') 58700 2 (0, 1, 2, 3, 4, 6) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Phil Mickelson', 'Jordan Spieth') 59300 3 (0, 1, 2, 3, 4, 7) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Phil Mickelson', 'Rory McIlroy') 59600 4 (0, 1, 2, 3, 4, 8) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Phil Mickelson', 'Dustin Johnson') 59800 5 (0, 1, 2, 3, 4, 9) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Phil Mickelson', 'Jason Day') 59900 6 (0, 1, 2, 3, 5, 6) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Henrik Stenson', 'Jordan Spieth') 59600 7 (0, 1, 2, 3, 5, 7) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Henrik Stenson', 'Rory McIlroy') 59900 8 (0, 1, 2, 3, 5, 8) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Henrik Stenson', 'Dustin Johnson') 60100 9 (0, 1, 2, 3, 5, 9) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Henrik Stenson', 'Jason Day') 60200 10 (0, 1, 2, 3, 6, 7) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Justin Rose', 'Jordan Spieth', 'Rory McIlroy') 60500 11 (0, 1, 2, 4, 5, 6) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Phil Mickelson', 'Henrik Stenson', 'Jordan Spieth') 60000 12 (0, 1, 2, 4, 5, 7) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Phil Mickelson', 'Henrik Stenson', 'Rory McIlroy') 60300 13 (0, 1, 2, 4, 5, 8) ('Rickie Fowler', 'Sergio Garcia', 'Adam Scott', 'Phil Mickelson', 'Henrik Stenson', 'Dustin Johnson') 60500 14 (0, 1, 3, 4, 5, 6) ('Rickie Fowler', 'Sergio Garcia', 'Justin Rose', 'Phil Mickelson', 'Henrik Stenson', 'Jordan Spieth') 60200 15 (0, 1, 3, 4, 5, 7) ('Rickie Fowler', 'Sergio Garcia', 'Justin Rose', 'Phil Mickelson', 'Henrik Stenson', 'Rory McIlroy') 60500 16 (0, 2, 3, 4, 5, 6) ('Rickie Fowler', 'Adam Scott', 'Justin Rose', 'Phil Mickelson', 'Henrik Stenson', 'Jordan Spieth') 60400 </code></pre> <hr> <p>If you're using an older version of Python that doesn't support the <code>yield from</code> syntax you can replace </p> <pre><code>yield from choose_teams(free[i+1:], num, newteam, newvalue) </code></pre> <p>with</p> <pre><code>for t, v in choose_teams(free[i+1:], num, newteam, newvalue): yield t, v </code></pre>
1
2016-07-28T14:04:10Z
[ "python", "python-2.7", "pandas", "linear-programming" ]
Python Pandas self join for merge cartesian product to produce all combinations and sum
38,636,460
<p>I am brand new to Python, seems like it has a lot of flexibility and is faster than traditional RDBMS systems.</p> <p>Working on a very simple process to create random fantasy teams. I come from an RDBMS background (Oracle SQL) and that does not seem to be optimal for this data processing.</p> <p>I made a dataframe using pandas read from csv file and now have a simple dataframe with two columns -- Player, Salary:</p> <pre><code>` Name Salary 0 Jason Day 11700 1 Dustin Johnson 11600 2 Rory McIlroy 11400 3 Jordan Spieth 11100 4 Henrik Stenson 10500 5 Phil Mickelson 10200 6 Justin Rose 9800 7 Adam Scott 9600 8 Sergio Garcia 9400 9 Rickie Fowler 9200` </code></pre> <p>What I am trying to do via python (pandas) is produce all combinations of 6 players which salary is between a certain amount 45000 -- 50000.</p> <p>In looking up python options, I found the itertools combination interesting, but it would result a massive list of combinations without filtering the sum of salary.</p> <p>In traditional SQL, I would do a massive merge cartesian join w/ SUM, but then I get the players in different spots..</p> <p>Such as A, B, C then, C, B, A..</p> <p>My traditional SQL which doesn't work well enough is something like this:</p> <pre><code>` SELECT distinct ONE.name AS "1", TWO.name AS "2", THREE.name AS "3", FOUR.name AS "4", FIVE.name AS "5", SIX.name AS "6", sum(one.salary + two.salary + three.salary + four.salary + five.salary + six.salary) as salary FROM nl.pgachamp2 ONE,nl.pgachamp2 TWO,nl.pgachamp2 THREE, nl.pgachamp2 FOUR,nl.pgachamp2 FIVE,nl.pgachamp2 SIX where ONE.name != TWO.name and ONE.name != THREE.name and one.name != four.name and one.name != five.name and TWO.name != THREE.name and TWO.name != four.name and two.name != five.name and TWO.name != six.name and THREE.name != four.name and THREE.name != five.name and three.name != six.name and five.name != six.name and four.name != six.name and four.name != five.name and one.name != six.name group by ONE.name, TWO.name, THREE.name, FOUR.name, FIVE.name, SIX.name` </code></pre> <p>Is there a way to do this in Pandas/Python?</p> <p>Any documentation that can be pointed to would be great!</p>
3
2016-07-28T12:31:29Z
38,642,499
<p>As mentioned in the comments, this is a constraint satisfaction problem. It has a combinatorial part but since you defined no objectives to minimize or maximize, it is not an optimization problem (yet). You can approach this problems in many ways: you can try brute-force like piRSquared or use a heuristic algorithm like PM 2Ring. I will present a solution with 0-1 linear programming, and use <a href="https://pypi.python.org/pypi/PuLP" rel="nofollow">PuLP</a> library to model and solve the problem.</p> <pre><code>from pulp import * import pandas as pd df = df.set_index('Name') feasible_solutions = [] </code></pre> <p>In order to model the problem, first you need to define <em>decision variables</em>. Here, the decision variable will be an indicator variable for each player: it will be 1 if that player is selected, 0 otherwise. Here's how you do it in PuLP:</p> <pre><code>players = LpVariable.dicts('player', df.index.tolist(), 0, 1, LpInteger) </code></pre> <p>Next, you create a problem:</p> <pre><code>prob = pulp.LpProblem('Team Selection', pulp.LpMinimize) </code></pre> <p>As I mentioned earlier, your question does not state any objectives. You only want to create all possible teams. Therefore, we will define an arbitrary objective function (I will turn back to this arbitrary function again).</p> <pre><code>prob += 0 </code></pre> <p>You mainly have two constraints:</p> <p>1) The team will have 5 players:</p> <pre><code>prob += lpSum([players[player] for player in players]) == 5 </code></pre> <p>Remember that players dictionary stores our decision variables. <code>players[player]</code> is either 1 (if that player is in the team) or 0 (otherwise). Therefore, if you sum all of them, the result should be equal to 5.</p> <p>2) Total salary should be between 45k and 50k.</p> <pre><code>prob += lpSum([players[player] * df.at[player, 'Salary'] for player in players]) &lt;= 50000 prob += lpSum([players[player] * df.at[player, 'Salary'] for player in players]) &gt;= 45000 </code></pre> <p>This is similar to the first constraint. Here, we are not counting but instead summing the salaries (when the player is in the team, the value will be 1 so it will be multiplied by the corresponding salary. Otherwise, the value will be zero and the multiplication will also be zero).</p> <p>The main modeling is done here. If you call <code>prob.solve()</code>, it will find <em>a</em> solution that satisfies these constraints. Normally, in optimization problems, we provide an objective function and try to maximize or minimize that. For example, assume that you have scores for the skills of players. Your budget is limited, you cannot go ahead and select top 5 players. So, in the part where we stated <code>prob += 0</code>, you can define an objective function to maximize total skill score. But that wasn't what you were looking for so let's continue.</p> <p>Once you find a solution, you can add another constraint to the problem stating that the next solution should be different than this, you can generate all solutions.</p> <pre><code>while prob.solve() == 1: current_solution = [player for player in players if value(players[player])] feasible_solutions.append(current_solution) prob += lpSum([players[player] for player in current_solution]) &lt;= 4 </code></pre> <p><code>prob.solve()</code> is the method that solves the problem. Based on the result, it returns an integer. If it finds an optimal solution, the result is 1. For infeasible or unbounded solutions there are different codes. So as long as we can find new solutions, we continue the loop.</p> <p>In the loop we first append the current solution to our <code>feasible_solutions</code> list. Then, we add another constraint: for these 5 players, the sum of the variables cannot exceed 4 (The largest value 5 and if it is 5, we know that this is the same solution).</p> <p>If you run this, you will have the same result piRSquared got.</p> <p><a href="http://i.stack.imgur.com/XxpkU.png" rel="nofollow"><img src="http://i.stack.imgur.com/XxpkU.png" alt="enter image description here"></a></p> <p>So, what is the advantage of this?</p> <p>The main reason we use integer/binary linear programming is that number of combinations grows really quickly. This is called <a href="https://en.wikipedia.org/wiki/Combinatorial_explosion" rel="nofollow">combinatorial explosion</a>. Take a look at the number of possible teams (without any constraint):</p> <pre><code>from scipy.misc import comb comb(10, 5) Out: 252.0 comb(20, 5) Out: 15504.0 comb(50, 5) Out: 2118760.0 comb(100, 5) Out: 75287520.0 </code></pre> <p>It becomes almost impossible to evaluate all combinations. </p> <p>Of course when you want to list all combinations that satisfies those constraints you are still running that risk. If the number of combinations satisfying the constraints is large, it will take a lot of time to compute. You cannot avoid that. However, if that subset is small or it is still large but you are evaluating a function on that set, it will be much better.</p> <p>For example, consider the following DataFrame:</p> <pre><code>import numpy as np np.random.seed(0) df = pd.DataFrame({'Name': ['player' + str(i).zfill(3) for i in range(100)], 'Salary': np.random.randint(0, 9600, 100)}) </code></pre> <p>268 of 75287520 solutions satisfy the salary constraint. It took 44 seconds in my computer to list them. It would take hours to find them using brute-force (update: it takes 8 hours and 21 minutes).</p> <p>PuLP uses an open source solver, <a href="https://projects.coin-or.org/Cbc" rel="nofollow">Cbc</a>, by default. There are other open source/commercial alternative solvers that you can use with PuLP. Commercial ones are generally faster as expected (they are very expensive though).</p> <p>Another alternative is constraint programming as I mentioned in the comments. For these kind of problems, you can find many smart ways to reduce the search space with constraint programming. I am comfortable with integer programming so I showed a model based on that but I should note that constraint programming might be way better for this. </p>
1
2016-07-28T16:56:49Z
[ "python", "python-2.7", "pandas", "linear-programming" ]
Solving simultaneous equations in python
38,636,482
<p>I have following test program. My query is two folded: (1) Some how the solution is giving zero and (2) Is it appropriate to use this <code>x2= np.where(x &gt; y, 1, x)</code> kind of conditions on variables ? Are there any constrained optimization routines in Scipy ? </p> <pre><code>a = 13.235 b = 70.678 def system(X, a,b): x=X[0] y=X[1] x2= np.where(x &gt; y, 1, x) f=np.zeros(3) f[0] = 2*x2 - y - a f[1] = 3*x2 + 2*y- b return (X) func= lambda X: system(X, a, b) guess=[5,5] sol = optimize.root(func,guess) print(sol) </code></pre> <p>edit: (2a) Here with <code>x2= np.where(x &gt; y, 1, x)</code> condition, two equations becomes one equation. (2b) In another variation requirement is: <code>x2= np.where(x &gt; y, x^2, x^3)</code>. Let me comments on these two as well. Thanks !</p>
2
2016-07-28T12:32:28Z
39,234,606
<p>First up, your <code>system</code> function is an identity, since you <code>return X</code> instead of <code>return f</code>. The return should be the same shape as the <code>X</code> so you had better have </p> <pre><code>f = np.array([2*x2 - y - a, 3*x2 + 2*y- b]) </code></pre> <p>Next the function, as written has a discontinuity where x=y, and this is causing there to be be a problem for the initial guess of (5,5). Setting the initial guess to (5,6) allows for the the solution [13.87828571, 14.52157143] to be found rapidly.</p> <p>With the second example, again using an initial guess of [5,5] causes problems of discontinuity, using [5,6] gives a solution of [ 2.40313743, 14.52157143].</p> <p>Here is my code: </p> <pre><code>import numpy as np from scipy import optimize def system(X, a=13.235, b=70.678): x = np.where(X[0] &gt; X[1], X[0]**2, X[0]**3) y=X[1] return np.array( [2*x - y - a, 3*x + 2*y - b]) guess = [5,6] sol = optimize.root(system, guess) print(sol) </code></pre>
1
2016-08-30T18:25:20Z
[ "python", "python-3.x", "numpy" ]
Histogram of my cam in real time
38,636,520
<p>Im trying to show the histogram in real time from grayscale of my webcam, the problem is that histogram is not being update and my cam stop until i close histogram's window. How can i fix this? I want to show the grayscale img from my webcam and its histogram in same time, is possible do that?</p> <pre><code>import numpy as np import cv2 from matplotlib import pyplot as plt cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('Janela', frame) cv2.imshow('Outra', gray) plt.hist(gray.ravel(), 256, [0, 256]) plt.show() if (cv2.waitKey(1) &amp; 0xFF == 27): break cap.release() cv2.destroyAllWindows() </code></pre>
0
2016-07-28T12:34:09Z
38,709,401
<p>I have been working for a while in the same task. After some time, I have a piece of code that works very good. It displays the camera image in a window and a histogram in other. Since I'm interested in finding colors, I'm working with the "hue" channel of each frame.</p> <pre><code># import the necessary packages import cv2 import numpy as np #Create window to display image cv2.namedWindow('colorhist', cv2.CV_WINDOW_AUTOSIZE) #Set hist parameters hist_height = 64 hist_width = 256 nbins = 32 bin_width = hist_width/nbins camera_id = 0 # type fo webcam [0 built-in | 1 external] cameraWidth = 320 cameraHeight = 240 if camera_id == 0: cameraId = "PC webcam" elif camera_id == 1: cameraId = "External webcam" camera = cv2.VideoCapture(camera_id) # set camera image to 320 x 240 pixels camera.set(3,cameraWidth) camera.set(4,cameraHeight) cameraInfo = "Image size (%d,%d)" % (camera.get(3),camera.get(4)) # initialize mask matrix mask = np.zeros((cameraHeight,cameraWidth), np.uint8) # draw a circle in mask matrix cv2.circle(mask,(cameraWidth/2,cameraHeight/2), 50, 255, -1) #Create an empty image for the histogram h = np.zeros((hist_height,hist_width)) #Create array for the bins bins = np.arange(nbins,dtype=np.int32).reshape(nbins,1) while True: # grab the current frame (grabbed, frame) = camera.read() if not grabbed: "Camera could not be started." break hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #Calculate and normalise the histogram hist_hue = cv2.calcHist([hsv],[0],mask,[nbins],[0,256]) cv2.normalize(hist_hue,hist_hue,hist_height,cv2.NORM_MINMAX) hist=np.int32(np.around(hist_hue)) pts = np.column_stack((bins,hist)) #Loop through each bin and plot the rectangle in white for x,y in enumerate(hist): cv2.rectangle(h,(x*bin_width,y),(x*bin_width + bin_width-1,hist_height),(255),-1) #Flip upside down h=np.flipud(h) #Show the histogram cv2.imshow('Color Histogram',h) h = np.zeros((hist_height,hist_width)) frame = cv2.bitwise_and(frame,frame,mask = mask) cv2.putText(frame, cameraInfo, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) cv2.imshow(cameraId, frame) key = cv2.waitKey(1) &amp; 0xFF # if the `q` key is pressed, break from the loop if key == ord("q"): break camera.release() cv2.destroyAllWindows() </code></pre> <p>The code is based on the code from JohnLinux (<a href="http://stackoverflow.com/questions/19203388/how-do-i-plot-a-32-bin-histogram-for-a-grayscale-image-in-python-using-opencv">How do I plot a 32-Bin Histogram for a Grayscale Image in Python using OpenCV</a>) and other lines of code come from what I have learnt from Adrian Rosenbrock's site <a href="https://www.pyimagesearch.com/" rel="nofollow">https://www.pyimagesearch.com/</a>. </p>
2
2016-08-01T23:06:19Z
[ "python", "opencv", "histogram" ]
Python Webdriver -unexpected EOF while parsing (<string>, line 1)
38,636,729
<p>I'm using Python with webdriver</p> <p>I'm trying to locate element with find element with xpath and get :"unexpected EOF while parsing (, line 1)"</p> <p>When I try to locate it by finding element with class name, it works well.</p> <p>The problem is that I can't use it since I have several classes with the same name.</p> <p>Here is xpath:</p> <pre><code>//*[@id="j_id0:j_id5:j_id6:j_id36"]/div/div/div[2]/div[2]/div[2]/ul/li[1]/div/svg/g/g[1]/path[1] </code></pre> <p>here is the class name : st0</p> <p>here is my code line:</p> <pre><code>ss = self.SELENIUM_DRIVER.find_element_by_xpath('//*[@id="j_id0:j_id5:j_id6:j_id36"]/div/div/div[2]/div[2]/div[2]/ul/li[1]/div/svg/g/g[1]/path[1]') </code></pre> <p>-Which does not work</p> <pre><code>ddd = self.SELENIUM_DRIVER.find_element_by_class_name('st0') </code></pre> <p>-Which works </p> <p>This is the html:</p> <p></p> <p>Thanks in advance</p>
2
2016-07-28T12:43:32Z
38,639,400
<p>The following query will look for a <code>path</code> with the parent tree of <code>div/svg/g/g[1]</code>, with a class equalling <code>st0</code> and at index <code>[1]</code>:</p> <pre><code>self.SELENIUM_DRIVER.find_element_by_xpath('//div/svg/g/g[1]/path[@class=st0][1]') </code></pre> <p>If the parent tree is unique from earlier on, it may be a good idea to make the query shorter, e.g.:</p> <pre><code>self.SELENIUM_DRIVER.find_element_by_xpath('//g/g[1]/path[@class=st0][1]') </code></pre>
0
2016-07-28T14:32:34Z
[ "python", "selenium-webdriver" ]
Python Webdriver -unexpected EOF while parsing (<string>, line 1)
38,636,729
<p>I'm using Python with webdriver</p> <p>I'm trying to locate element with find element with xpath and get :"unexpected EOF while parsing (, line 1)"</p> <p>When I try to locate it by finding element with class name, it works well.</p> <p>The problem is that I can't use it since I have several classes with the same name.</p> <p>Here is xpath:</p> <pre><code>//*[@id="j_id0:j_id5:j_id6:j_id36"]/div/div/div[2]/div[2]/div[2]/ul/li[1]/div/svg/g/g[1]/path[1] </code></pre> <p>here is the class name : st0</p> <p>here is my code line:</p> <pre><code>ss = self.SELENIUM_DRIVER.find_element_by_xpath('//*[@id="j_id0:j_id5:j_id6:j_id36"]/div/div/div[2]/div[2]/div[2]/ul/li[1]/div/svg/g/g[1]/path[1]') </code></pre> <p>-Which does not work</p> <pre><code>ddd = self.SELENIUM_DRIVER.find_element_by_class_name('st0') </code></pre> <p>-Which works </p> <p>This is the html:</p> <p></p> <p>Thanks in advance</p>
2
2016-07-28T12:43:32Z
38,645,197
<p>I think this is the problem with your provided Id <code>j_id0:j_id5:j_id6:j_id36</code> and as you are saying class name is same for some other elements as well, So you should try using <code>xpath</code> by passing index as below :-</p> <pre><code>self.SELENIUM_DRIVER.find_element_by_xpath('(//path[@class=st0])[1]') </code></pre> <p>Now you can locate your desire element by just changing index value.</p> <p>Hope it works...:)</p>
0
2016-07-28T19:29:55Z
[ "python", "selenium-webdriver" ]
ValueError: too many values to unpack - Is it possible to ignore one value?
38,636,765
<p>The following line returns an error:</p> <pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True) </code></pre> <p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only 5.</p> <p>Is it possible to ignore the last value?</p>
2
2016-07-28T12:44:57Z
38,636,821
<p>You can use <code>*rest</code> from Python 3.</p> <pre><code>&gt;&gt;&gt; x, y, z, *rest = 1, 2, 3, 4, 5, 6, 7 &gt;&gt;&gt; x 1 &gt;&gt;&gt; y 2 &gt;&gt;&gt; rest [4, 5, 6, 7] </code></pre> <p>This way you can always be sure to not encounter unpacking issues.</p>
7
2016-07-28T12:47:06Z
[ "python", "unpack" ]
ValueError: too many values to unpack - Is it possible to ignore one value?
38,636,765
<p>The following line returns an error:</p> <pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True) </code></pre> <p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only 5.</p> <p>Is it possible to ignore the last value?</p>
2
2016-07-28T12:44:57Z
38,636,933
<p>It's common to use <code>_</code> to denote unneeded variables.</p> <pre><code>a, b, c, d, e, _ = my_func_that_gives_6_values() </code></pre> <p>This is also often used when iterating a certain number of times.</p> <pre><code>[random.random() for _ in range(10)] # gives 10 random values </code></pre>
2
2016-07-28T12:51:17Z
[ "python", "unpack" ]
ValueError: too many values to unpack - Is it possible to ignore one value?
38,636,765
<p>The following line returns an error:</p> <pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True) </code></pre> <p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only 5.</p> <p>Is it possible to ignore the last value?</p>
2
2016-07-28T12:44:57Z
38,636,953
<p>Just <a class='doc-link' href="http://stackoverflow.com/documentation/python/289/indexing-and-slicing#t=201607281251592864833">slice</a> the last one out:</p> <pre><code>self.m, self.userCodeToUserNameList, \ self.itemsList, self.userToKeyHash, \ self.fileToKeyHash = readUserFileMatrixFromFile(x,True)[:-1] </code></pre> <hr> <p><strong>EDIT</strong> after <a href="http://stackoverflow.com/questions/38636765/valueerror-too-many-values-to-unpack-is-it-possible-to-ignore-one-value/38636953?noredirect=1#comment64656894_38636953">TigerhawkT3's comment</a> :</p> <p>Note that this works only if the return object supports slicing.</p>
0
2016-07-28T12:52:03Z
[ "python", "unpack" ]
ValueError: too many values to unpack - Is it possible to ignore one value?
38,636,765
<p>The following line returns an error:</p> <pre><code>self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True) </code></pre> <p>The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only 5.</p> <p>Is it possible to ignore the last value?</p>
2
2016-07-28T12:44:57Z
38,637,039
<p>Just, use the <strong>throw-away</strong> variable '_'</p> <pre><code> self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash, _ = readUserFileMatrixFromFile(x,True) </code></pre> <p>here '_' is deliberately ignored.</p>
-1
2016-07-28T12:55:53Z
[ "python", "unpack" ]
Phantomjs click on checkbox
38,636,770
<p>I'm using selenium and phantomjs and I would like to learn how to click a checkbox properly. For exemple in this page: <a href="https://www.udacity.com/courses/android" rel="nofollow">https://www.udacity.com/courses/android</a></p> <p>I would like to check "Free Courses", so I tried this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By def __init__(self): self.driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs') def parse(self, response): self.driver.get(response.url) element = self.driver.find_element(By.XPATH, '//div[@class="checkbox"]/label[contains(.,"Free Courses")]') self.driver.execute_script("arguments[0].click();", element) </code></pre> <p>The problem is that it doesn't seems to be clicking anything: making a screenshot with <code>self.driver.save_screenshot('screenshot.png')</code> it gives all the results, not filtered. Is it something I'm doing wrong?</p>
2
2016-07-28T12:45:08Z
38,637,148
<p>Your <code>xpath</code> locates to <code>label</code> element while you want to click on <code>checkbox</code> element, As I'm seeing in your provided <a href="https://www.udacity.com/courses/android" rel="nofollow">website</a>, there is no need to create <code>xpath</code> to select <code>Free Course</code> checkbox, you can simply find this checkbox using <code>By.NAME</code> as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By def __init__(self): self.driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs') def parse(self, response): self.driver.get(response.url) element = self.driver.find_element(By.NAME, 'Free Course') element.click() </code></pre> <p><strong>Note</strong> :- Selenium provides <code>click()</code> function to perform click on an element, So there is no need to use <code>execute_script</code> to perform click by javascript if you could simply do this by using <code>click()</code> function.</p> <p>Hope it helps...:)</p>
0
2016-07-28T13:00:19Z
[ "python", "selenium-webdriver", "click", "phantomjs" ]
Filter on index in spark rdd
38,636,896
<p>Is it possible to filter on an specific column value in an RDD .Eg:</p> <pre><code>[(u'62d45630-587a-4290-91e1-a86fbe019bb5', (Row(process_id=1, event_id=u'62d45630-587a-4290-91e1-a86fbe019bb5', event_type=u'PlannedCustomerChoiceWasUpdated', publishedDate=u'2016-07-27T04:16:13.650Z', tgt_tbl_n=u'raw_plan', subj_area=u'plan', flag=u'R', url=u'http://gbp-router.gapinc.dev:8080/planning-service/planning/buy-plan/planned-customer-choices/a448760d-6d92-4dc9-b04a-7ec22673a158', url_id=u'a448760d-6d92-4dc9-b04a-7ec22673a158'), '{"ts":"2016-07-28T11:54:54.748Z","httpStatus":404,"errors":[{"code":"notFound","message":"Planned Customer Choice with id a448760d-6d92-4dc9-b04a-7ec22673a158 does not exist."}],"requestId":"ugM4CXkgax5qxILq"}', None, u'2016-07-27T04:16:13.650Z', 'N'))] </code></pre> <p>the RDD is in key,value form.I want to filter on the value[4] , i.e 'N'. Can anyone please help me out.</p>
-2
2016-07-28T12:49:45Z
38,638,243
<p>I do not quite understand what you want to accomplish as your question is a little unclear to me but there are different ways to filter on an RDD.</p> <p>An RDD itself does not have a schema so you cannot filter columnwise here as far as i know. If you want to run SQL queries on an RDD you can turn the RDD into a Dataframe by applying a Schema and using the toDF() function. A Dataframe can then be handled equally to a table in a Database.</p> <p><a href="http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds" rel="nofollow">http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds</a></p> <p>Another way to filter on an RDD is a filter() function. </p> <p><a href="http://spark.apache.org/docs/latest/quick-start.html#basics" rel="nofollow">http://spark.apache.org/docs/latest/quick-start.html#basics</a></p> <p>I guess your RDD has the form of a tuple with an Iterable as second value. You could run through the Iterable and filter for all values that do not match your criteria. You could also filter for the last position in your Iterable, given that the syntax of your data is always the same.</p> <p>Hope that helps!</p>
0
2016-07-28T13:42:27Z
[ "python", "apache-spark", "pyspark", "rdd" ]
Automatically run another script after i run main code in PyCharm
38,636,905
<p>I have been looking for a feature where PyCharm notifies me that a script has finished running in the console after each run. At present, I have to add <code>print('done')</code> after each code.</p> <p>I got smarter so I defined <code>d = 'done'</code> once and after each run I simply add a <code>d</code> so it prints out <code>'done'</code> which I thought to be more of a time saver.</p> <p>Now I am even more lazy and whenever I press F10 (my run command button), I want PyCharm to automatically run a small script with <code>d = 'done'</code> in it right after finishing running the main script.</p> <p>Is there a way to do this?</p>
3
2016-07-28T12:50:03Z
38,686,877
<p>All Intellij-based IDEs support shell integration, scripting, plugins etc. I bet you can insert your notifications in a build script. <em>Run</em> menu-> <em>edit configurations</em></p> <p>Actually, CLion shows notification on failed/successful build, but I did make something like this with PhpStorm. </p> <p>You're programmer, all the bells and whistles are given, just use them.</p>
0
2016-07-31T17:56:34Z
[ "python", "pycharm" ]
Design pattern for transformation of array data in Python script
38,637,020
<p>I currently have a Python class with many methods each of which performs a transformation of time series data (primarily arrays). Each method must be called in a specific order, since the inputs of each function specifically rely on the outputs of the previous. Hence my code structure looks like the following:</p> <pre><code>class Algorithm: def __init__(self, data1, data2): self.data1 = data1 self.data2 = data2 def perform_transformation1(self): ...perform action on self.data1 def perform_transformation2(self): ...perform action on self.data1 etc.. </code></pre> <p>At the bottom of the script, I instantiate the class and then proceed to call each method on the instance, procedurally. Using object orientated programming in this case seems wrong to me.</p> <p>My aims are to re-write my script in a way such that the inputs of each method are not dependent on the outputs of the preceding method, hence giving me the ability to decide whether or not to perform certain methods.</p> <p>What design pattern should I be using for this purpose, and does this move more towards functional programming? </p>
0
2016-07-28T12:55:12Z
38,637,784
<p>One option is to define your methods like this:</p> <pre><code>def perform_transformation(self, data=None): if data is None: perform action on self.data else: perform action on data </code></pre> <p>This way, you have the ability to call them at any time you want.</p>
0
2016-07-28T13:25:32Z
[ "python", "algorithm", "functional-programming", "time-series" ]
Design pattern for transformation of array data in Python script
38,637,020
<p>I currently have a Python class with many methods each of which performs a transformation of time series data (primarily arrays). Each method must be called in a specific order, since the inputs of each function specifically rely on the outputs of the previous. Hence my code structure looks like the following:</p> <pre><code>class Algorithm: def __init__(self, data1, data2): self.data1 = data1 self.data2 = data2 def perform_transformation1(self): ...perform action on self.data1 def perform_transformation2(self): ...perform action on self.data1 etc.. </code></pre> <p>At the bottom of the script, I instantiate the class and then proceed to call each method on the instance, procedurally. Using object orientated programming in this case seems wrong to me.</p> <p>My aims are to re-write my script in a way such that the inputs of each method are not dependent on the outputs of the preceding method, hence giving me the ability to decide whether or not to perform certain methods.</p> <p>What design pattern should I be using for this purpose, and does this move more towards functional programming? </p>
0
2016-07-28T12:55:12Z
38,639,220
<pre><code>class Algorithm: @staticmethod def perform_transformation_a(data): return 350 * data @staticmethod def perform_transformation_b(data): return 400 * data def perform_transformations(data): transformations = (Algorithm.perform_transformation_a, Algorithm.perform_transformation_b) for transformation in transformations: data = transformation(data) return data </code></pre> <p>You could have the <code>Algorithm</code> class just be a collection of pure functions. And then have the client code (<code>perform_transformations</code> here) be the logic of ordering which transformations to apply. This way the <code>Algorithm</code> class is only responsible for algorithms and client worries about ordering the functions.</p>
1
2016-07-28T14:22:55Z
[ "python", "algorithm", "functional-programming", "time-series" ]
pandas Panel max
38,637,032
<p>I have pandas.Panel4D object and I would like to find the maximum of the all values.</p> <p>The current way:</p> <pre><code>p4d.max().max().max().max() </code></pre> <p>In there a better way to achieve the same result?</p> <p>(np.max(p4d) does not work.)</p> <p>Also is there is an equivalent for idxmax for panel and panel4D?</p>
2
2016-07-28T12:55:43Z
38,637,324
<p>Use <code>max</code> on the <code>values</code> attribute.</p> <pre><code>pd.Panel4D(np.arange(16).reshape(2, 2, 2, 2)).values.max() 15 </code></pre> <p>numpy <code>ndarray</code> <code>max</code> method returns the maximum over the entire structure unless you specify an axis. You can access the underlying <code>ndarray</code> via the <code>values</code> attribute.</p>
3
2016-07-28T13:07:10Z
[ "python", "numpy", "pandas", "panel" ]
Join two dataframes. Add a column value if index value of first matches the second
38,637,059
<p>I have two dataframes, call them 1st and 2nd. 1st has index - 'customer'. 2nd also has index - 'customer' with some similar and some different values. 1st has columns 'P' and 'Q'. 2nd also has columns by the name 'P' and 'Q'. I want to join both dataframes like, if any index value of 1st matches index value of 2nd, then add corresonding values of 'P' and 'Q' from B to 'P' and 'Q' of 1st. Return dataframe 1st</p> <p>example 1st dataframe is:</p> <pre><code>customer P Q A 0.5 4 B 0.4 6 C 0.3 5 D 0.7 7 </code></pre> <p>2nd dataframe is:</p> <pre><code>customer P Q B 4 20 D 5 21 E 6 22 F 7 23 </code></pre> <p>Output should be:</p> <pre><code>Customer P Q A 0.5 4 B 4.4 26 (6+20) C 0.3 5 D 5.7 28 (7+21) </code></pre>
0
2016-07-28T12:56:42Z
38,637,683
<pre><code>np.random.seed([3,1415]) A = pd.DataFrame(np.random.rand(3, 2), pd.Index(list('abc'),name='customer'), list('PQ')) B = pd.DataFrame(np.random.rand(3, 2), pd.Index(list('bcd'),name='customer'), list('PQ')) A </code></pre> <p><a href="http://i.stack.imgur.com/Spu0p.png" rel="nofollow"><img src="http://i.stack.imgur.com/Spu0p.png" alt="enter image description here"></a></p> <pre><code>B </code></pre> <p><a href="http://i.stack.imgur.com/JZWr7.png" rel="nofollow"><img src="http://i.stack.imgur.com/JZWr7.png" alt="enter image description here"></a></p> <pre><code>(A + B).dropna() </code></pre> <p><a href="http://i.stack.imgur.com/EElY3.png" rel="nofollow"><img src="http://i.stack.imgur.com/EElY3.png" alt="enter image description here"></a></p> <h3>Solution</h3> <p>IIUC you want to add to <code>A</code>, the values of <code>B</code> where <code>B</code> has a common index, otherwise just take values of <code>A</code>.</p> <pre><code>A.add(B, fill_value=0).reindex_like(A) </code></pre> <p><a href="http://i.stack.imgur.com/MvBnE.png" rel="nofollow"><img src="http://i.stack.imgur.com/MvBnE.png" alt="enter image description here"></a></p>
2
2016-07-28T13:21:49Z
[ "python", "pandas" ]
Complete the relative paths to absolute using Python
38,637,191
<p>I have rewritten the complete code to fetch the href and src link using beautifulsoup this time by the request of many SO users instead of regex. Here is the code:</p> <pre><code>import os from bs4 import BeautifulSoup from urllib.parse import urlparse path = urlpars(http://www.example.com/dynamic/search.aspx?searchtype=cat&amp;class_id=2566&amp;city_id=55) lpath = os.path.dirname(path.path) html = u"&lt;html class=\"\"&gt;&lt;head id=\"pageHead\"&gt;&lt;title&gt;\n Beauty Salons | Best Beauty Care &amp;amp; Treatments | Listings @ Phonebook Online\n&lt;/title&gt;\n &lt;!--\n &lt;meta http-equiv=\"Cache-Control\" content=\"no-cache, no-store, must-revalidate\" /&gt;&lt;meta http-equiv=\"Pragma\" content=\"no-cache\" /&gt;&lt;meta http-equiv=\"Expires\" content=\"0\" /&gt;\n --&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"&gt;&lt;link rel=\"stylesheet\" href=\"../css_responsive/category.css\" type=\"text/css\" media=\"screen\"&gt;\n &lt;script async=\"\" src=\"//www.google-analytics.com/analytics.js\"&gt;&lt;/script&gt;&lt;script async=\"\" src=\"//www.google.com/adsense/search/async-ads.js\"&gt;&lt;/script&gt;&lt;script type=\"text/javascript\" src=\"../styles/scripts/jquery-1.9.1.min.js\"&gt;&lt;/script&gt;\n &lt;link rel=\"shortcut icon\" type=\"image/png\" href=\"/PhoneBook.ico\"&gt;\n &lt;!-- #Begin Css Plugin --&gt;\n &lt;link rel=\"stylesheet\" href=\"../css_responsive/fontsss.css\"&gt;&lt;link rel=\"stylesheet\" href=\"../css_responsive/bootstrap-3.3.4-dist/css/bootstrap.css\" type=\"text/css\" media=\"screen\"&gt;&lt;link rel=\"stylesheet\" href=\"../styles/scripts/fancybox/jquery.fancybox.css\" type=\"text/css\" media=\"screen\"&gt;&lt;link rel=\"stylesheet\" href=\"../css_responsive/icon-detail.css\" type=\"text/css\" media=\"screen\"&gt;\n &lt;!-- #Finish Css Plugin--&gt;\n &lt;!--&lt;script src=\"http://www.google.com/adsense/search/ads.js\" type=\"text/javascript\"&gt;&lt;/script&gt; --&gt;\n &lt;script type=\"text/javascript\" charset=\"utf-8\"&gt;\n (function (G, o, O, g, L, e) {\n G[g] = G[g] || function () {\n (G[g]['q'] = G[g]['q'] || []).push(\n arguments)\n }, G[g]['t'] = 1 * new Date; L = o.createElement(O), e = o.getElementsByTagName(\n O)[0]; L.async = 1; L.src = '//www.google.com/adsense/search/async-ads.js';\n e.parentNode.insertBefore(L, e)\n })(window, document, 'script', '_googCsa');\n &lt;/script&gt;\n &lt;!-- Script For Mobile Base Banner--&gt;\n &lt;script async=\"\" src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"&gt;&lt;/script&gt;\n &lt;script&gt;\n (adsbygoogle = window.adsbygoogle || []).push({\n google_ad_client: \"ca-pub-6517686434458516\",\n enable_page_level_ads: true\n });\n &lt;/script&gt;\n &lt;!-- Script For Mobile Base Banner END--&gt;\n\n\n &lt;script type=\"text/javascript\"&gt;\n function AddClass(Class, Element, HasPriority) {\n if (HasPriority == 0) {\n this.className = 'container ' + Class;\n }\n }\n &lt;/script&gt;\n \n&lt;meta name=\"description\" content=\"Best Beauty Salons in Abbottabad for quality beauty care and treatments. \"&gt;&lt;meta name=\"keywords\" content=\"beauty salons,beauty care,beauty treatments\"&gt;&lt;style type=\"text/css\"&gt;.fancybox-margin{margin-right:17px;}&lt;/style&gt;&lt;/head&gt;\n&lt;body style=\"text-shadow: rgba(255, 255, 255, 0.4) 0px 1px 1px; background-color: rgb(240, 240, 240);\"&gt;\n&lt;div class=\"wapper\"&gt;\n &lt;div class=\"pagecontent search_width c-no-t-margin\"&gt;\n &lt;div class=\"cblock ele-margin-t-b-15 m-on-mob-hide\"&gt;&lt;a href=\"../../default.aspx\"&gt;Home&lt;/a&gt; &amp;gt; &lt;a href=\"../../dynamic/categories.aspx\"&gt;Search by category&lt;/a&gt; &amp;gt; &lt;a href=\"../../dynamic/categories.aspx?class_id=12\"&gt;Personal Care&lt;/a&gt; &amp;gt; &lt;a href=\"../../dynamic/categories.aspx?class_id=134\"&gt;Barbers, Beauty Salons &amp;amp; Spas&lt;/a&gt; &amp;gt; Beauty Salons in Abbottabad&lt;/div&gt;\n &lt;div class=\"refine\"&gt;\n &lt;span&gt;Refine Result&lt;/span&gt;\n &lt;span&gt;Show Result With&lt;/span&gt;\n &lt;ul&gt;\n &lt;li&gt;\n &lt;input class=\"csortType csortTypeAll \" type=\"checkbox\" value=\"100\" name=\"\" checked=\"checked\" disabled=\"disabled\"&gt;\n &lt;span class=\"\"&gt;All&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;input class=\"csortType css-checkbox\" type=\"checkbox\" value=\"1\" name=\"\"&gt;\n &lt;i class=\"icon-star-full c-icon-starfull-stroke\"&gt;&lt;/i&gt;\n &lt;span&gt;Reviews&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;input class=\"csortType\" type=\"checkbox\" value=\"2\" name=\"\"&gt;\n &lt;i class=\"icon-price-tag cColor-Red\"&gt;&lt;/i&gt;\n &lt;span&gt;Deals &amp;amp; Coupons&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;input class=\"csortType\" type=\"checkbox\" value=\"5\" name=\"\"&gt;\n &lt;i class=\"icon-bullhorn\"&gt;&lt;/i&gt;\n &lt;span&gt;Announcements&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;input class=\"csortType\" type=\"checkbox\" value=\"3\" name=\"\"&gt;\n &lt;i class=\"icon-location\"&gt;&lt;/i&gt;\n &lt;span&gt;Map&lt;/span&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;input class=\"csortType\" type=\"checkbox\" value=\"4\" name=\"\"&gt;\n &lt;i class=\"icon-film\"&gt;&lt;/i&gt;\n &lt;span&gt;Video&lt;/span&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n \n &lt;div class=\"tab\" onclick=\"SlideTogle('Location')\"&gt;\n Search by location\n &lt;/div&gt;\n \n &lt;ul id=\"Location\" style=\"display: none;\"&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=1\"&gt;Karachi&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=2\"&gt;Lahore&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=56\"&gt;Islamabad&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=79\"&gt;Rawalpindi&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=49\"&gt;Faisalabad&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=81\"&gt;Gujranwala&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=78\"&gt;Peshawar&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=82\"&gt;Sialkot&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=53\"&gt;Sargodha&lt;/a&gt;&lt;/li&gt;\n \n &lt;/ul&gt;\n \n &lt;div class=\"tab\" onclick=\"SlideTogle('Category')\"&gt;\n Search by category\n &lt;/div&gt;\n \n &lt;ul id=\"Category\" style=\"display: none;\"&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2571\"&gt;Hairstylists&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2575\"&gt;Hair Removal, Wax, Threading Body &amp;amp; Face&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2584\"&gt;Manicuring&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2574\"&gt;Nail Salons &amp;amp; Services&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2572\"&gt;Spas-Beauty, Health And Destination&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2564\"&gt;Beauty Institutes&lt;/a&gt;&lt;/li&gt;\n \n &lt;li&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2569\"&gt;Estheticians&lt;/a&gt;&lt;/li&gt;\n \n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;div id=\"cResultMainControl\"&gt;\n &lt;div class=\"result_hldr\" id=\"cResultContainer\"&gt;\n &lt;div class=\"h1\"&gt;&lt;h1&gt;Beauty Salons in Abbottabad.&lt;/h1&gt;&lt;/div&gt;\n &lt;div class=\"h1 page_desc cfont-12 cNo-Margin ele-pad-r-l-20 m-on-mob-hide\"&gt;&lt;p class=\"cNo-Margin margin-t m-ele-top-no-margin \" style=\"line-height:18px;\"&gt;Best Beauty Salons in Abbottabad for quality beauty care and treatments, &lt;a href=\"http://www.phonebook.com.pk/dynamic/search.aspx?SearchType=kl&amp;amp;k=bridal+makeup\" title=\"Bridal Makeup\" target=\"_blank\"&gt;bridal makeup&lt;/a&gt;, &lt;a href=\"http://www.phonebook.com.pk/dynamic/search.aspx?SearchType=kl&amp;amp;k=body+massage\" title=\"Body Massage\" target=\"_blank\"&gt;body massage&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;\n &lt;div class=\"cMobileHidden col-md-12 col-xs-12 text-center overflow-visible cheight-25 margin-t\" style=\"background-color: rgb(240, 240, 240);\"&gt;\n &lt;script async=\"\" src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"&gt;&lt;/script&gt;\n &lt;!-- New Line Link Ad --&gt;\n &lt;ins class=\"adsbygoogle\" style=\"display:inline-block;width:468px;height:15px;background-color: rgb(240, 240, 240);\" data-ad-client=\"ca-pub-6517686434458516\" data-ad-slot=\"4522680219\"&gt;&lt;/ins&gt;\n &lt;script&gt;\n (adsbygoogle = window.adsbygoogle || []).push({});\n &lt;/script&gt;\n &lt;/div&gt;\n &lt;div id=\"cAlpNav\" class=\"margin-t-10 cAlpNav m-on-mob-hide\"&gt;\n &lt;div class=\"text-center\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55\"&gt;all&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=a\"&gt;a&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=b\"&gt;b&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=c\"&gt;c&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=d\"&gt;d&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=e\"&gt;e&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=f\"&gt;f&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=g\"&gt;g&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=h\"&gt;h&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=i\"&gt;i&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=j\"&gt;j&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=k\"&gt;k&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=l\"&gt;l&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=m\"&gt;m&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=n\"&gt;n&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=o\"&gt;o&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=p\"&gt;p&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=q\"&gt;q&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=r\"&gt;r&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=s\"&gt;s&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=t\"&gt;t&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=u\"&gt;u&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=v\"&gt;v&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=w\"&gt;w&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=x\"&gt;x&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=y\"&gt;y&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=55&amp;amp;alp=z\"&gt;z&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;\n &lt;div&gt;\n &lt;div id=\"cListingHldr\" class=\"listing\"&gt;\n \n&lt;div class=\"container\"&gt;\n &lt;div class=\"comp_info\"&gt;\n &lt;h2&gt;&lt;a href=\"../../company/51529-Beena-Beauty-Parlour\"&gt;Beena's Beauty Parlour&lt;/a&gt;&lt;/h2&gt;\n &lt;!--&lt;img class=\"margin-t\" alt=\"Comapny Rating\" src=\"../../images/Stars&gt;.png\" /&gt;--&gt;\n &lt;i class=\"cfont-12 cnoPad left icon-zero-star\"&gt;&lt;/i&gt;\n \n &lt;span class=\"blue margin-t\"&gt;(No Review)&lt;/span&gt;\n \n &lt;span class=\"cfontBold margin-t cColor-Black cColor-SilverDark\"&gt;\n Main Mansehra Road, Near Radio Pakistan, Abbottabad.\n &lt;/span&gt;\n \n &lt;div class=\"inline-block cMobile-Right\"&gt;\n &lt;ul class=\"margin-t cMobile-Text-Align-Right\"&gt;\n &lt;li&gt;\n &lt;a data-fancybox-type=\"iframe\" href=\"../../dynamic/emailtocustomer.aspx?Request_ID=26207&amp;amp;comp_name=Beena-Beauty-Parlour&amp;amp;isAdvertizer=0\" class=\"other_links fancybox\"&gt;Email&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a title=\"Call Now\" href=\"tel:+92-992-335556\" class=\"c_circle cMobileShow\"&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a class=\"other_links\" href=\"../../company/51529-Beena-Beauty-Parlour\" title=\"Company Detail\"&gt;Detail&lt;/a&gt;\n &lt;/li&gt;\n \n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"comp_info contact_info\"&gt;\n &lt;strong&gt;&lt;a class=\"tel\" href=\"tel:+92-992-335556\"&gt;+92-992-335556&lt;/a&gt;&lt;/strong&gt;\n \n &lt;/div&gt;\n&lt;/div&gt;\n&lt;div class=\"container\"&gt;\n &lt;div class=\"comp_info\"&gt;\n &lt;h2&gt;&lt;a href=\"../../company/86977-Unique-Beauty-Salon\"&gt;Unique Beauty Salon&lt;/a&gt;&lt;/h2&gt;\n &lt;!--&lt;img class=\"margin-t\" alt=\"Comapny Rating\" src=\"../../images/Stars&gt;.png\" /&gt;--&gt;\n &lt;i class=\"cfont-12 cnoPad left icon-zero-star\"&gt;&lt;/i&gt;\n \n &lt;span class=\"blue margin-t\"&gt;(No Review)&lt;/span&gt;\n \n &lt;span class=\"cfontBold margin-t cColor-Black cColor-SilverDark\"&gt;\n Palki Wedding Hall, Mandian , Abbottabad.\n &lt;/span&gt;\n \n &lt;div class=\"inline-block cMobile-Right\"&gt;\n &lt;ul class=\"margin-t cMobile-Text-Align-Right\"&gt;\n &lt;li&gt;\n &lt;a data-fancybox-type=\"iframe\" href=\"../../dynamic/emailtocustomer.aspx?Request_ID=61717&amp;amp;comp_name=Unique-Beauty-Salon&amp;amp;isAdvertizer=0\" class=\"other_links fancybox\"&gt;Email&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a title=\"Call Now\" href=\"tel:+92-313-5856739\" class=\"c_circle cMobileShow\"&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a class=\"other_links\" href=\"../../company/86977-Unique-Beauty-Salon\" title=\"Company Detail\"&gt;Detail&lt;/a&gt;\n &lt;/li&gt;\n \n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"comp_info contact_info\"&gt;\n &lt;strong&gt;&lt;a class=\"tel\" href=\"tel:+92-313-5856739\"&gt;+92-313-5856739&lt;/a&gt;&lt;/strong&gt;\n \n &lt;/div&gt;\n&lt;/div&gt;&lt;/div&gt;\n &lt;div id=\"cRecoredInfo\" class=\"listing dotted\"&gt;Displaying listings from 1 to 10 of 10&lt;/div&gt;\n &lt;div class=\"text-center m-pad-l-r-10\"&gt;\n &lt;div id=\"related-suggestions\" class=\"listing inline-block text-center cPad-b-t-10\"&gt;&lt;span class=\"left cfont-14\"&gt;&lt;b&gt;Related Searches:&lt;/b&gt;&lt;/span&gt; &lt;div class=\"newsssss left inline\" style=\"font-style: italic;font-weight:bold;\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2584\" class=\"left ele-pad-r-l-20 text-underline cfont-14\"&gt;Manicuring&lt;/a&gt;&lt;/div&gt;&lt;div class=\"newsssss left inline\" style=\"font-style: italic;font-weight:bold;\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2575\" class=\"left ele-pad-r-l-20 text-underline cfont-14\"&gt;Hair Removal, Wax, Threading Body &amp;amp; Face&lt;/a&gt;&lt;/div&gt;&lt;div class=\"newsssss left inline\" style=\"font-style: italic;font-weight:bold;\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2571\" class=\"left ele-pad-r-l-20 text-underline cfont-14\"&gt;Hairstylists&lt;/a&gt;&lt;/div&gt;\n &lt;div class=\"text-left ele-margin-t-b-15 left inline\"&gt;&lt;b&gt;Need help with your search?&lt;/b&gt; Browse by:&lt;a class=\"text-left ele-pad-r-l-20 text-underline\" onclick=\"hide_show('#related-locations',this);$('#related-categories').addClass('hide');\" href=\"javascript:void(0)\"&gt;other locations &lt;img alt=\"\" class=\"margin-l\" width=\"18\" src=\"../../images/plus.png\"&gt;&lt;/a&gt;&lt;a class=\"text-left ele-pad-r-l-20 text-underline\" onclick=\"hide_show('#related-categories',this);$('#related-locations').addClass('hide');\" href=\"javascript:void(0)\"&gt;similar categories &lt;img alt=\"\" class=\"margin-l\" width=\"18\" src=\"../../images/plus.png\"&gt;&lt;/a&gt;&lt;/div&gt;&lt;ul id=\"related-locations\" class=\"col-xs-12 col-sm-12 sugesstion-box hide\"&gt;\n &lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=1\" class=\"left\"&gt;Karachi&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=2\" class=\"left\"&gt;Lahore&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=56\" class=\"left\"&gt;Islamabad&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=79\" class=\"left\"&gt;Rawalpindi&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=49\" class=\"left\"&gt;Faisalabad&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=81\" class=\"left\"&gt;Gujranwala&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=78\" class=\"left\"&gt;Peshawar&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=82\" class=\"left\"&gt;Sialkot&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2566&amp;amp;city_id=53\" class=\"left\"&gt;Sargodha&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;\n &lt;ul id=\"related-categories\" class=\"col-xs-12 col-sm-12 sugesstion-box hide\"&gt;\n &lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2574\" class=\"left\"&gt;Nail Salons &amp;amp; Services&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2572\" class=\"left\"&gt;Spas-Beauty, Health And Destination&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2564\" class=\"left\"&gt;Beauty Institutes&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2569\" class=\"left\"&gt;Estheticians&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"text-center\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n \n&lt;div class=\"container-fluid bg-silver m-on-mob-hide\"&gt;\n &lt;div class=\"row cPad-b-t-10\" style=\"border-bottom:1px solid #ECECEC;\"&gt;\n \n &lt;/div&gt;\n&lt;/div&gt;\n&lt;script&gt;\n (function (i, s, o, g, r, a, m) {\n i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {\n (i[r].q = i[r].q || []).push(arguments)\n }, i[r].l = 1 * new Date(); a = s.createElement(o),\n m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)\n })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');\n\n ga('create', 'UA-2028280-1', 'auto');\n ga('send', 'pageview');\n&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"../css_responsive/script/global_functions.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"../styles/scripts/fancybox/jquery.fancybox.js?v=2.1.5\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"../css_responsive/bootstrap-3.3.4-dist/js/bootstrap.js\"&gt;&lt;/script&gt;\n&lt;/body&gt;&lt;/html&gt;" soup = BeautifulSoup(html, "lxml") for allLinks in soup.find_all(href=True): if allLinks['href'] and not allLinks['href'].startswith("http") and not allLinks['href'].startswith("jav"): print (allLinks['href']) for allLinks in soup.find_all(src=True): if allLinks['src'] and not allLinks['src'].startswith("http") and not allLinks['src'].startswith("jav"): print (allLinks['src']) </code></pre> <p>This code prints all the links in console and I can successfully change them into absolute paths by using if-elif-else to differentiate "../../", "../", "/" and "//". But the problem is when I try to replace them using "re.sub" the whole html gets messed up again. I use BS4 instead of regex but still the same issue. Because of character count I can't post output here but for the sake of knowledge it also messes "" or any other html tag as well. Please suggest me any way to change these links and put them back where they need to be.</p> <p><strong>NOTE:</strong> Code is most minimized as per <a href="http://stackoverflow.com/users/4559110/akash-karothiya">akashkarothiya's</a> advice.</p>
1
2016-07-28T13:01:59Z
38,653,668
<p>Its final code and everything is working perfectly thanks to <a href="http://stackoverflow.com/users/4559110/akash-karothiya">akash karothiya</a>'s solution.</p> <p>This code changes all kinds of relative links into absolute links in any given html code. </p> <pre><code>import os, re from bs4 import BeautifulSoup from urllib.parse import urlparse, unquote unquoteURL = unquote("http://webpy_server/?link=http%3A//www.example.com/dynamic/search.aspx%3Fsearchtype%3Dcat%26class_id%3D4520%26page%3D1") path = urlparse(urlparse(unquoteURL).query.replace("link=", "")) lpath = os.path.dirname(os.path.abspath(path.path)) html = u"\n&lt;!DOCTYPE html class=\"\"&gt;&lt;head id=\"pageHead\"&gt;&lt;title&gt;\n Yarn Manufacturers &amp;amp; Suppliers | Listings @ Phonebook Online\n&lt;/title&gt;\n &lt;!--\n &lt;meta http-equiv=\"Cache-Control\" content=\"no-cache, no-store, must-revalidate\" /&gt;&lt;meta http-equiv=\"Pragma\" content=\"no-cache\" /&gt;&lt;meta http-equiv=\"Expires\" content=\"0\" /&gt;\n --&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"&gt;&lt;link rel=\"stylesheet\" href=\"../css_responsive/category.css\" type=\"text/css\" media=\"screen\"&gt;\n &lt;script async=\"\" src=\"//www.google-analytics.com/analytics.js\"&gt;&lt;/script&gt;&lt;script async=\"\" src=\"//www.google.com/adsense/search/async-ads.js\"&gt;&lt;/script&gt;&lt;script type=\"text/javascript\" src=\"../styles/scripts/jquery-1.9.1.min.js\"&gt;&lt;/script&gt;\n &lt;link rel=\"shortcut icon\" type=\"image/png\" href=\"/PhoneBook.ico\"&gt;\n &lt;!-- #Begin Css Plugin --&gt;\n &lt;link rel=\"stylesheet\" href=\"../css_responsive/fontsss.css\"&gt;&lt;link rel=\"stylesheet\" href=\"../css_responsive/bootstrap-3.3.4-dist/css/bootstrap.css\" type=\"text/css\" media=\"screen\"&gt;&lt;link rel=\"stylesheet\" href=\"../styles/scripts/fancybox/jquery.fancybox.css\" type=\"text/css\" media=\"screen\"&gt;&lt;link rel=\"stylesheet\" href=\"../css_responsive/icon-detail.css\" type=\"text/css\" media=\"screen\"&gt;\n &lt;!-- #Finish Css Plugin--&gt;\n &lt;!--&lt;script src=\"http://www.google.com/adsense/search/ads.js\" type=\"text/javascript\"&gt;&lt;/script&gt; --&gt;\n &lt;script type=\"text/javascript\" charset=\"utf-8\"&gt;\n (function (G, o, O, g, L, e) {\n G[g] = G[g] || function () {\n (G[g]['q'] = G[g]['q'] || []).push(\n arguments)\n }, G[g]['t'] = 1 * new Date; L = o.createElement(O), e = o.getElementsByTagName(\n O)[0]; L.async = 1; L.src = '//www.google.com/adsense/search/async-ads.js';\n e.parentNode.insertBefore(L, e)\n })(window, document, 'script', '_googCsa');\n &lt;/script&gt;\n &lt;!-- Script For Mobile Base Banner--&gt;\n &lt;script async=\"\" src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"&gt;&lt;/script&gt;\n &lt;script&gt;\n (adsbygoogle = window.adsbygoogle || []).push({\n google_ad_client: \"ca-pub-6517686434458516\",\n enable_page_level_ads: true\n });\n &lt;/script&gt;\n &lt;!-- Script For Mobile Base Banner END--&gt;\n\n\n &lt;script type=\"text/javascript\"&gt;\n function AddClass(Class, Element, HasPriority) {\n if (HasPriority == 0) {\n this.className = 'container ' + Class;\n }\n }\n &lt;/script&gt;\n \n&lt;meta name=\"description\" content=\"Online Directory of Yarn Manufacturers &amp;amp; Suppliers in Pakistan, providing list of names, contact numbers, addresses and reviews.\"&gt;&lt;meta name=\"keywords\" content=\"Yarn Manufacturers &amp;amp; Suppliers\"&gt;&lt;style type=\"text/css\"&gt;.fancybox-margin{margin-right:17px;}&lt;/style&gt;&lt;/head&gt;\n&lt;body style=\"text-shadow: rgba(255, 255, 255, 0.4) 0px 1px 1px; background-color: rgb(240, 240, 240);\"&gt;\n &lt;!--Top Nav Bar Start --&gt;\n \n&lt;div class=\"wapper bg-h\"&gt;\n &lt;div class=\"container-fluid\"&gt;\n &lt;div class=\"col-xs-12 col-md-12\"&gt;\n &lt;div class=\"col-xs-12 col-md-12\"&gt;\n &lt;div class=\"ele-block text-right ele-color-white ele-pad-t-5 m-text-center cMobileTextCenter cfont-12\" style=\"padding-top:5px;\"&gt;\n &lt;a class=\"\" href=\"../dynamic/free-basic-listing.aspx\"&gt; Free basic listing&lt;/a&gt; \n | \n &lt;a class=\"\" href=\"/advertisement-center/\"&gt; Advertise with us&lt;/a&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"header\"&gt;\n &lt;div class=\"logo\"&gt;\n &lt;div class=\"cMobileHidden left cPad-b-t-25\"&gt;\n &lt;img alt=\"Slider\" height=\"26\" class=\"left\" src=\"../../images/list-icon-slvr.png\" onclick=\"DefaultSliderMenu()\" style=\"cursor:pointer;\"&gt;\n &lt;/div&gt;\n &lt;div class=\"cDesktopHidden cMobileShow\"&gt;\n &lt;img alt=\"Slider\" height=\"26\" class=\"ele-float-left\" src=\"../../images/list-icon-slvr.png\" onclick=\"SlideMenu()\" style=\"cursor:pointer;vertical-align: baseline !important; \"&gt;\n &lt;/div&gt;\n &lt;!--&lt;span class=\"home-slide-icon icon-list2 cPad-b-t-10 cDesktopHidden\" onclick=\"SlideMenu()\"&gt;&lt;/span&gt;--&gt;\n &lt;a class=\"left ele-margin-t-b-15 cMobileFloatNone\" style=\"text-decoration:none !important\" href=\"../../\"&gt;\n &lt;img alt=\"Phonebook\" class=\"\" width=\"205\" src=\"../../images/final-logo2s.png\"&gt;\n &lt;/a&gt;\n &lt;div class=\"cDesktopHidden cMobileShow\"&gt;\n &lt;img alt=\"Slider\" width=\"38\" height=\"26\" class=\"ele-float-left\" src=\"/images/magnify-glass-2.png\" onclick=\"enableMobileSearchOption() \" style=\"cursor:pointer;vertical-align: baseline !important; \"&gt;\n &lt;/div&gt;\n &lt;!--&lt;a href=\"../../default.aspx\"&gt;&lt;img height=\"60\" alt=\"Phonebook\" src=\"../images/Phonebook-Online-Logo-Big-new2.png\" /&gt;&lt;/a&gt;--&gt;\n &lt;!--&lt;h2 class=\"mColorWhite\"&gt;Your Online Search Engine&lt;/h2&gt;--&gt;\n &lt;/div&gt;\n &lt;div id=\"cHeader_sky_banner\" class=\"sky_banner\"&gt;&lt;embed src=\"http://www.phonebook.com.pk/images/advertisement/swf/79042_8_160614_61864_1.swf\" pluginspage=\"http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash\" width=\"700\" height=\"90\" quality=\"high\" value=\"autostart=true\" wmode=\"transparent\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;div class=\"wapper bg-h bg-fixed flow-visible m-on-mob-hide\" style=\"top: 0px;\"&gt;\n &lt;div class=\"header\"&gt;\n &lt;form method=\"POST\" action=\"../redirect.aspx?searchtype=kl\"&gt;\n &lt;input class=\"icon-search\" type=\"text\" name=\"keyword\" placeholder=\"What ? (Name or Keyword)\" autocomplete=\"off\" required=\"\"&gt;\n &lt;input class=\"icon-loc\" type=\"text\" name=\"location\" placeholder=\"Where ? (City or Area)\" autocomplete=\"off\"&gt;\n &lt;input class=\"submit\" type=\"submit\" value=\"Find\"&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n &lt;i class=\"after icon-circle-up\"&gt;&lt;/i&gt;\n&lt;/div&gt;\n &lt;!--Top Nav Bar End --&gt;\n &lt;div class=\"wapper\"&gt;\n &lt;div class=\"pagecontent search_width c-no-t-margin\"&gt;\n &lt;div class=\"cblock ele-margin-t-b-15 m-on-mob-hide\"&gt;&lt;a href=\"../../default.aspx\"&gt;Home&lt;/a&gt; &amp;gt; &lt;a href=\"../../dynamic/categories.aspx\"&gt;Search by category&lt;/a&gt; &amp;gt; &lt;a href=\"../../dynamic/categories.aspx?class_id=19\"&gt;Industrial supplies &amp;amp; services&lt;/a&gt; &amp;gt; &lt;a href=\"../../dynamic/categories.aspx?class_id=234\"&gt;Textiles&lt;/a&gt; &amp;gt; Yarn Wholesale &amp;amp; Manufacturers in Pakistan&lt;/div&gt;\n \n \n \n &lt;div id=\"cResultMainControl\"&gt;\n &lt;div class=\"result_hldr\" id=\"cResultContainer\"&gt;\n \n \n &lt;div class=\"cMobileHidden col-md-12 col-xs-12 text-center overflow-visible cheight-25 margin-t\" style=\"background-color: rgb(240, 240, 240);\"&gt;\n &lt;script async=\"\" src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"&gt;&lt;/script&gt;\n &lt;!-- New Line Link Ad --&gt;\n &lt;ins class=\"adsbygoogle\" style=\"display:inline-block;width:468px;height:15px;background-color: rgb(240, 240, 240);\" data-ad-client=\"ca-pub-6517686434458516\" data-ad-slot=\"4522680219\"&gt;&lt;/ins&gt;\n &lt;script&gt;\n (adsbygoogle = window.adsbygoogle || []).push({});\n &lt;/script&gt;\n &lt;/div&gt;\n &lt;div id=\"cAlpNav\" class=\"margin-t-10 cAlpNav m-on-mob-hide\"&gt;\n &lt;div class=\"text-center\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520\"&gt;all&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=a\"&gt;a&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=b\"&gt;b&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=c\"&gt;c&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=d\"&gt;d&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=e\"&gt;e&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=f\"&gt;f&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=g\"&gt;g&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=h\"&gt;h&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=i\"&gt;i&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=j\"&gt;j&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=k\"&gt;k&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=l\"&gt;l&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=m\"&gt;m&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=n\"&gt;n&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=o\"&gt;o&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=p\"&gt;p&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=q\"&gt;q&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=r\"&gt;r&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=s\"&gt;s&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=t\"&gt;t&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=u\"&gt;u&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=v\"&gt;v&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=w\"&gt;w&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=x\"&gt;x&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=y\"&gt;y&lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;alp=z\"&gt;z&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;\n &lt;div&gt;\n &lt;div id=\"cListingHldr\" class=\"listing\"&gt;\n \n&lt;div class=\"container\"&gt;\n &lt;div class=\"comp_info\"&gt;\n &lt;h2&gt;&lt;a href=\"../../company/77683-A-J-Apparels-Pvt-Ltd\"&gt;A &amp;amp; J Apparels (Pvt) Ltd.&lt;/a&gt;&lt;/h2&gt;\n &lt;!--&lt;img class=\"margin-t\" alt=\"Comapny Rating\" src=\"../../images/Stars&gt;.png\" /&gt;--&gt;\n &lt;i class=\"cfont-12 cnoPad left icon-zero-star\"&gt;&lt;/i&gt;\n \n &lt;span class=\"blue margin-t\"&gt;(No Review)&lt;/span&gt;\n \n &lt;span class=\"cfontBold margin-t cColor-Black cColor-SilverDark\"&gt;\n LA/6-A Block 22, F. B Area, Karachi\n &lt;/span&gt;\n \n &lt;div class=\"inline-block cMobile-Right\"&gt;\n &lt;ul class=\"margin-t cMobile-Text-Align-Right\"&gt;\n &lt;li&gt;\n &lt;a data-fancybox-type=\"iframe\" href=\"../../dynamic/emailtocustomer.aspx?Request_ID=8127&amp;amp;comp_name=A-J-Apparels-Pvt-Ltd&amp;amp;isAdvertizer=0\" class=\"other_links fancybox\"&gt;Email&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a title=\"Call Now\" href=\"tel:+92-21-36342521\" class=\"c_circle cMobileShow\"&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a class=\"other_links\" href=\"../../company/77683-A-J-Apparels-Pvt-Ltd\" title=\"Company Detail\"&gt;Detail&lt;/a&gt;\n &lt;/li&gt;\n \n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"comp_info contact_info\"&gt;\n &lt;strong&gt;&lt;a class=\"tel\" href=\"tel:+92-21-36342521\"&gt;+92-21-36342521&lt;/a&gt;&lt;/strong&gt;\n \n &lt;/div&gt;\n&lt;/div&gt;\n\n\n\n\n\n\n\n\n&lt;/div&gt;\n &lt;div id=\"cRecoredInfo\" class=\"listing dotted\"&gt;Displaying listings from 1 to 10 of 161&lt;/div&gt;\n &lt;div class=\"text-center m-pad-l-r-10\"&gt;\n &lt;div id=\"related-suggestions\" class=\"listing inline-block text-center cPad-b-t-10\"&gt;&lt;span class=\"left cfont-14\"&gt;&lt;b&gt;Related Searches:&lt;/b&gt;&lt;/span&gt; &lt;div class=\"newsssss left inline\" style=\"font-style: italic;font-weight:bold;\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=1030\" class=\"left ele-pad-r-l-20 text-underline cfont-14\"&gt;Importers&lt;/a&gt;&lt;/div&gt;&lt;div class=\"newsssss left inline\" style=\"font-style: italic;font-weight:bold;\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4499\" class=\"left ele-pad-r-l-20 text-underline cfont-14\"&gt;Textiles Wholesale &amp;amp; Manufacturers&lt;/a&gt;&lt;/div&gt;&lt;div class=\"newsssss left inline\" style=\"font-style: italic;font-weight:bold;\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=1029\" class=\"left ele-pad-r-l-20 text-underline cfont-14\"&gt;Exporters&lt;/a&gt;&lt;/div&gt;\n &lt;div class=\"text-left ele-margin-t-b-15 left inline\"&gt;&lt;b&gt;Need help with your search?&lt;/b&gt; Browse by:&lt;a class=\"text-left ele-pad-r-l-20 text-underline\" onclick=\"hide_show('#related-locations',this);$('#related-categories').addClass('hide');\" href=\"javascript:void(0)\"&gt;other locations &lt;img alt=\"\" class=\"margin-l\" width=\"18\" src=\"../../images/plus.png\"&gt;&lt;/a&gt;&lt;a class=\"text-left ele-pad-r-l-20 text-underline\" onclick=\"hide_show('#related-categories',this);$('#related-locations').addClass('hide');\" href=\"javascript:void(0)\"&gt;similar categories &lt;img alt=\"\" class=\"margin-l\" width=\"18\" src=\"../../images/plus.png\"&gt;&lt;/a&gt;&lt;/div&gt;&lt;ul id=\"related-locations\" class=\"col-xs-12 col-sm-12 sugesstion-box hide\"&gt;\n &lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=1\" class=\"left\"&gt;Karachi&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=2\" class=\"left\"&gt;Lahore&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=49\" class=\"left\"&gt;Faisalabad&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=77\" class=\"left\"&gt;Multan&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=81\" class=\"left\"&gt;Gujranwala&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=15\" class=\"left\"&gt;Hub&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=79\" class=\"left\"&gt;Rawalpindi&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=76\" class=\"left\"&gt;Hyderabad&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=62\" class=\"left\"&gt;Muzaffar Garh&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-3 col-sm-2\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;city_id=60\" class=\"left\"&gt;Layyah&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;\n &lt;ul id=\"related-categories\" class=\"col-xs-12 col-sm-12 sugesstion-box hide\"&gt;\n &lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4470\" class=\"left\"&gt;Knitted Fabrics&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4489\" class=\"left\"&gt;Synthetic &amp;amp; Blended Fabrics Wholesale &amp;amp; Manufacturers&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2391\" class=\"left\"&gt;Aprons Wholesale &amp;amp; Manufacturers&lt;/a&gt;&lt;/li&gt;&lt;li class=\"left cblock margin-l col-xs-4 col-sm-4 text-left\"&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=2109\" class=\"left\"&gt;Linens Wholesale &amp;amp; Manufacturers&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"text-center\"&gt;\n &lt;div id=\"cPagination\" class=\"listing\"&gt;\n &lt;img class=\"left\" alt=\"\" src=\"../../images/page-1.png\"&gt;\n &lt;a id=\"ctl39_cPageUrl\" class=\"pagi_anchor\"&gt;\n &lt;span id=\"ctl39_cAlp\"&gt;B&lt;/span&gt;\n &lt;span id=\"ctl39_cPageNo\"&gt;&lt;/span&gt;\n &lt;/a&gt;&lt;a href=\"search.aspx?searchtype=cat&amp;amp;class_id=4520&amp;amp;page=1\" id=\"ctl40_cPageUrl\" class=\"pagi_anchor\"&gt;\n &lt;span id=\"ctl40_cAlp\" style=\"color:red !important;;\"&gt;O&lt;/span&gt;\n &lt;span id=\"ctl40_cPageNo\" style=\"color:red !important;;\"&gt;1&lt;/span&gt;\n &lt;/a&gt;&lt;/div&gt;\n &lt;/div&gt;\n \n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n \n\n &lt;div class=\"srch_banner\"&gt; \n \n \n \n \n \n \n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;&lt;div style=\"height: 0px; visibility: hidden; font-weight: normal; text-align: center;\"&gt;&lt;iframe frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowtransparency=\"true\" scrolling=\"no\" width=\"100%\" name=\"{&amp;quot;name&amp;quot;:&amp;quot;master-2&amp;quot;,&amp;quot;slave-0-2&amp;quot;:{&amp;quot;container&amp;quot;:&amp;quot;adNewNTRSearchPagecontainer2&amp;quot;,&amp;quot;linkTarget&amp;quot;:&amp;quot;_top&amp;quot;,&amp;quot;lines&amp;quot;:3,&amp;quot;colorBackground&amp;quot;:&amp;quot;#e0e0e0&amp;quot;,&amp;quot;colorBorder&amp;quot;:&amp;quot;#0b0b0b&amp;quot;,&amp;quot;fontFamily&amp;quot;:&amp;quot;verdana&amp;quot;,&amp;quot;adIconLocation&amp;quot;:&amp;quot;ad-left&amp;quot;,&amp;quot;width&amp;quot;:&amp;quot;300px&amp;quot;,&amp;quot;type&amp;quot;:&amp;quot;ads&amp;quot;,&amp;quot;hl&amp;quot;:&amp;quot;en&amp;quot;,&amp;quot;columns&amp;quot;:1,&amp;quot;horizontalAlignment&amp;quot;:&amp;quot;left&amp;quot;,&amp;quot;resultsPageQueryParam&amp;quot;:&amp;quot;query&amp;quot;},&amp;quot;master-2&amp;quot;:{&amp;quot;linkTarget&amp;quot;:&amp;quot;_top&amp;quot;,&amp;quot;lines&amp;quot;:3,&amp;quot;colorBackground&amp;quot;:&amp;quot;#e0e0e0&amp;quot;,&amp;quot;colorBorder&amp;quot;:&amp;quot;#0b0b0b&amp;quot;,&amp;quot;fontFamily&amp;quot;:&amp;quot;verdana&amp;quot;,&amp;quot;adIconLocation&amp;quot;:&amp;quot;ad-left&amp;quot;,&amp;quot;width&amp;quot;:&amp;quot;300px&amp;quot;,&amp;quot;type&amp;quot;:&amp;quot;ads&amp;quot;,&amp;quot;hl&amp;quot;:&amp;quot;en&amp;quot;,&amp;quot;columns&amp;quot;:1,&amp;quot;horizontalAlignment&amp;quot;:&amp;quot;left&amp;quot;,&amp;quot;resultsPageQueryParam&amp;quot;:&amp;quot;query&amp;quot;}}\" id=\"master-2\" src=\"https://www.google.com/afs/ads?q=Yarn%20Wholesale%20%26%20Manufacturers&amp;amp;adpage=1&amp;amp;r=m&amp;amp;fexp=21404%2C7000107&amp;amp;client=pub-6517686434458516&amp;amp;channel=3589710218&amp;amp;hl=en&amp;amp;type=0&amp;amp;oe=UTF-8&amp;amp;ie=UTF-8&amp;amp;jsei=3&amp;amp;format=n2&amp;amp;ad=n2&amp;amp;nocache=3631469793737437&amp;amp;num=0&amp;amp;output=uds_ads_only&amp;amp;v=3&amp;amp;allwcallad=1&amp;amp;preload=true&amp;amp;adext=as1%2Csr1%2Cctc1&amp;amp;bsl=10&amp;amp;u_his=3&amp;amp;u_tz=300&amp;amp;dt=1469793737439&amp;amp;u_w=1366&amp;amp;u_h=768&amp;amp;biw=1349&amp;amp;bih=599&amp;amp;psw=1349&amp;amp;psh=1589&amp;amp;frm=0&amp;amp;uio=uv3vp1sl1sr1cc1-wi300ff1&amp;amp;jsv=12350&amp;amp;rurl=http%3A%2F%2Fwww.phonebook.com.pk%2Fdynamic%2Fsearch.aspx%3Fsearchtype%3Dcat%26class_id%3D4520#master-2\" style=\"visibility: hidden; height: 0px;\"&gt;&lt;/iframe&gt;&lt;/div&gt;\n \n&lt;div class=\"container-fluid bg-silver m-on-mob-hide\"&gt;\n &lt;div class=\"row cPad-b-t-10\" style=\"border-bottom:1px solid #ECECEC;\"&gt;\n &lt;!--\n &lt;div class=\"col-md-12 col-lg-12 col-xs-12\"&gt;\n &lt;img height=\"40\" alt=\"\" src=\"../images/Phonebook-Online-Logo-Big-new.png\" /&gt;\n &lt;/div&gt;\n --&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;div class=\"wapper pad-top-10 footerBg bg-white m-pad-zero\"&gt;\n &lt;div class=\"width footer m-on-mob-hide cMobileHiddenblock \"&gt;\n &lt;ul class=\"list-unstyled col-sm-4 m-on-mob-hide cMobileHidden\"&gt;\n &lt;li class=\"\"&gt;&lt;strong style=\"color:#37aef0;\"&gt;Popular Keywords :&lt;/strong&gt;&lt;/li&gt;\n &lt;li&gt;\n &lt;ul class=\"list-unstyled\"&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?searchtype=kl&amp;amp;k=restaurants&amp;amp;l=pakistan\"&gt;Restaurants&lt;/a&gt;,&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?searchtype=kl&amp;amp;k=pizza&amp;amp;l=pakistan\"&gt;Pizza&lt;/a&gt;,&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?searchtype=kl&amp;amp;k=hajj+%26+umrah&amp;amp;l=pakistan\"&gt;Hajj &amp;amp; Umrah&lt;/a&gt;,&lt;/li&gt;\n \n \n \n \n \n \n \n \n \n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li class=\"margin-t\"&gt;&lt;strong style=\"color:#37aef0;\"&gt;Popular Cities :&lt;/strong&gt;&lt;/li&gt;\n &lt;li&gt;\n &lt;ul class=\"list-unstyled\"&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/city_categories.aspx?city_id=1\"&gt;Karachi&lt;/a&gt;,&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/city_categories.aspx?city_id=2\"&gt;Lahore&lt;/a&gt;,&lt;/li&gt;\n \n \n \n \n \n \n \n \n \n &lt;li&gt;&lt;a href=\"../../dynamic/city_categories.aspx?city_id=75\"&gt;Sukkur&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;ul class=\"col-xs-6 col-sm-2 styled\"&gt;\n &lt;li class=\"\"&gt;&lt;strong style=\"color:#37aef0;\"&gt;ADVERTISE :&lt;/strong&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/advertisement-center/\"&gt;Advertise with us&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/free-basic-listing.aspx\"&gt;Get a Free Listings&lt;/a&gt;&lt;/li&gt;\n \n &lt;/ul&gt;\n &lt;ul class=\"col-xs-6 col-sm-2 styled\"&gt;\n &lt;li class=\"\"&gt;&lt;strong style=\"color:#37aef0;\"&gt;QUICK LINKS :&lt;/strong&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/categories.aspx\"&gt;Search by Category&lt;/a&gt;,&lt;/li&gt;\n \n \n &lt;li&gt;&lt;a href=\"javascript:void(0)\"&gt;Browse by Video&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;ul class=\"col-xs-6 col-sm-2 styled\"&gt;\n &lt;li class=\"\"&gt;&lt;strong style=\"color:#37aef0;\"&gt;ABOUT US:&lt;/strong&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../static/contact-us.aspx\"&gt;Contact Us&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"javscript:void(0)\"&gt;Report an Error&lt;/a&gt;&lt;/li&gt;\n \n \n \n \n &lt;/ul&gt;\n &lt;ul class=\"col-xs-6 col-sm-2 styled\"&gt;\n &lt;li class=\"\"&gt;&lt;strong style=\"color:#37aef0;\"&gt;PARTNERS:&lt;/strong&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"http://jang.com.pk/\"&gt;Jang Group of Newspapers&lt;/a&gt;&lt;/li&gt;\n \n \n &lt;li&gt;&lt;a href=\"http://www.ptcl.com.pk/\"&gt;PTCL - White Page Telephone Directory Data&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-12 m-footer-wapper m-hidden-on-desktop\"&gt;\n &lt;div class=\"col-xs-3\"&gt;\n &lt;a title=\"Home\" href=\"/\"&gt;&lt;img class=\"col-xs-12 cNoPad ele-pad-zero\" alt=\"Home\" src=\"../images/footer-icon-home.png\"&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-3\"&gt;\n &lt;a title=\"Free Basic Listing\" href=\"/dynamic/free-basic-listing.aspx\"&gt;&lt;img class=\"col-xs-12 cNoPad ele-pad-zero\" alt=\"Home\" src=\"../images/footer-icon-free-listing.png\"&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-3\"&gt;\n &lt;a title=\"Contact Us\" href=\"/static/contact-us.aspx\"&gt;&lt;img class=\"col-xs-12 cNoPad ele-pad-zero\" alt=\"Home\" src=\"../images/footer-icon-contact.png\"&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;div class=\"col-xs-3\"&gt;\n &lt;a title=\"Free Basic Listing\" href=\"/advertisement-center\"&gt;&lt;img class=\"col-xs-12 cNoPad ele-pad-zero\" alt=\"Home\" src=\"../images/footer-icon-advertisewithus.png\"&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n\n \n&lt;script&gt;\n (function (i, s, o, g, r, a, m) {\n i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {\n (i[r].q = i[r].q || []).push(arguments)\n }, i[r].l = 1 * new Date(); a = s.createElement(o),\n m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)\n })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');\n\n ga('create', 'UA-2028280-1', 'auto');\n ga('send', 'pageview');\n&lt;/script&gt;\n \n &lt;div class=\"modal\" id=\"cSlideMenu\" onclick=\"SlideMenu2()\"&gt;\n &lt;/div&gt;\n\n\n&lt;div class=\"slideMenu cfont-12 ie-ele-none\" id=\"defaultSliderMenu\" style=\"max-height: 599px; overflow: auto;\"&gt;\n &lt;ul&gt;\n &lt;!--\n &lt;li class=\"ele-pad-t-b-30\"&gt;&lt;/li&gt;\n --&gt;\n &lt;li&gt;\n &lt;a class=\"icon-circle-down\" href=\"javascript:void(0)\" onclick=\"showSubMenu(this,'.menuSearchType')\"&gt;Business search &lt;/a&gt;\n &lt;ul class=\"hide menuSearchType\"&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/categories.aspx\"&gt;Search by category&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/city_select.aspx\"&gt;Search by city&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../searchbyphone.aspx\"&gt;Search by phone&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../searchbyaddress.aspx\"&gt;Search by address&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../searchbybrand.aspx\"&gt;Search by brand&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a class=\"icon-circle-down\" href=\"javascript:void(0)\" onclick=\"showSubMenu(this,'.menuSearchFap')\"&gt;People search&lt;/a&gt;\n &lt;ul class=\"hide menuSearchFap\"&gt;\n &lt;li&gt;&lt;a href=\"../../findaperson/findaperson.aspx?type=name\"&gt;Search by name&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../findaperson/findaperson.aspx?type=number\"&gt;Search by number&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a class=\"icon-circle-down\" href=\"javascript:void(0)\" onclick=\"showSubMenu(this,'.menuGuides')\"&gt;Specialized Guides&lt;/a&gt;\n &lt;ul class=\"hide menuGuides\"&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?searchtype=cat&amp;amp;class_id=4710\"&gt;Development Sector &amp;amp; NGOs&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?searchtype=cat&amp;amp;class_id=863\"&gt;Associations &amp;amp; Trade Bodies&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?searchtype=cat&amp;amp;class_id=864\"&gt;Chambers of Commerce&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?SearchType=cat&amp;amp;class_id=1514\"&gt;Embassies &amp;amp; Foreign Missions&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/categories.aspx?class_Id=65\"&gt;Import &amp;amp; Export&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/search.aspx?SearchType=cat&amp;amp;class_id=1517\"&gt;Federal Government&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../dynamic/categories.aspx?class_id=4638\"&gt;Emergency &amp;amp; Complain&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"../../static/nwdcode.aspx\"&gt;NWD Codes&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/advertisement-center/\"&gt;Advertise with us&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"javascript:void(0)\"&gt;Help&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n&lt;div class=\"modal in\" id=\"cSlideMenu\" onclick=\"SlideMenu2()\" aria-hidden=\"false\" style=\"display:none; padding-right: 17px;\"&gt;\n&lt;/div&gt;\n\n \n \n&lt;script type=\"text/javascript\" src=\"../css_responsive/script/global_functions.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"../styles/scripts/fancybox/jquery.fancybox.js?v=2.1.5\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"../css_responsive/bootstrap-3.3.4-dist/js/bootstrap.js\"&gt;&lt;/script&gt;\n\n\n&lt;/body&gt;&lt;/html&gt;" soup = BeautifulSoup(html, "lxml") all = soup.find_all(href=True) for i in all: try: output = re.sub(r'(?is)(href="../../)([^.])', 'href="' + path.scheme + '://' + os.path.normpath(path.netloc) + '/'+r'\2', str(html)) except: output = i html = output for i in all: try: output = re.sub(r'(?is)(href="../)([^.])', 'href="' + path.scheme + '://' + os.path.normpath(path.netloc) + '/'+r'\2', str(html)) except: output = i html = output for i in all: try: output = re.sub(r'(?is)(href="/)([^./])', 'href="' + path.scheme + "://" + path.netloc + '/'+r'\2', str(html)) except: output = i html = output for i in all: try: output = re.sub(r'(?is)(href=")([^.|jav|ht|//|/|../|../../])', 'href="' + path.scheme + '://' + path.netloc + lpath+r'\2', str(html)) except: output = i html = output all = soup.find_all(src=True) for i in all: try: output = re.sub(r'(?is)(src="../)([^.])', 'src="' + path.scheme + '://' + os.path.normpath(path.netloc) + '/'+r'\2', str(html)) except: output = i html = output for i in all: try: output = re.sub(r'(?is)(src="/)([^./])', 'src="' + path.scheme + "://" + path.netloc + '/'+r'\2', str(html)) except: output = i html = output for i in all: try: output = re.sub(r'(?is)(src="../../)([^.])', 'src="' + path.scheme + '://' + os.path.normpath(path.netloc) + '/'+r'\2', str(html)) except: output = i html = output all = soup.find_all(action=True) for i in all: try: output = re.sub(r'(?is)(action="../)([^.])', 'action="' + path.scheme + '://' + os.path.normpath(path.netloc) + '/'+r'\2', str(html)) except: output = i html = output print (html) </code></pre>
0
2016-07-29T08:07:23Z
[ "python", "html", "beautifulsoup" ]
How can I speed up my program created in Jupyter Notebook?
38,637,263
<p>I have a python program which is created in a Jupter Notebook. Due to the datasize and the optimization algo I used, a 4-fold custom cross validation within some range takes about 30 minutes to finish.</p> <p>My computer's environment: CPU i5 3.3 GHz, 8 GB DDR3 RAM, SSD.</p> <p>I'm wondering </p> <ol> <li><p>If it is possible to deploy it to some server and may make the speed a little bit quicker? (The data file is only about 30MB, I think it is possible to both upload the data and the program). And this may also help others who want to use the program.</p></li> <li><p>Can I do anything to speed up the cross validation? It's kind a manual process. I use <code>sklearn.cross_validation.KFold</code> to extract the train and test set. Then I loop through each fold to build the model and test its result. I'm not sure if it possible to encapsulate my model building method and perform the cross validation in parrallel?</p></li> </ol>
0
2016-07-28T13:04:51Z
38,637,367
<p>1: There are a couple paid HPC servers such as Amazon, but this is off topic for SO.</p> <p>2: The iteration of the cross validation can be done in parallel.</p> <p>As the cross validations are not connected, i would suggest something like this:</p> <pre><code>import multiprocessing def validation_function(args): do_validation ... ... p = multiprocessing.Pool(processes=multiprocessing.cpu_count()) for _ in p.imap_unordered(validation_function, args): pass </code></pre>
0
2016-07-28T13:09:10Z
[ "python", "jupyter-notebook" ]
multiprocessing.Queue seems to go away? OS (pipe destruction) vs Python?
38,637,282
<p>I'm using multiprocessing.queues.JoinableQueue as follows:</p> <p>A very long-running thread (multiple days) polls an API for XML. The thread that does this simply parses the XML into objects and shoves these into the queue.</p> <p>The handling of each object takes significantly more time than parsing the XML and in no way depends on the thread reading from the API. As such this implementation of multiprocessing is reather simple.</p> <p>The code for creating and cleaning up processes is here:</p> <pre><code> def queueAdd(self, item): try: self.queue.put(item) except AssertionError: #queue has been closed, remake it (let the other GC) logger.warn('Queue closed early.') self.queue = BufferQueue(ctx=multiprocessing.get_context()) self.queue.put(item) except BrokenPipeError: #workaround for pipe issue logger.warn('Broken pipe, Forcing creation of new queue.') # all reading procesess should suicide and new ones spawned. self.queue = BufferQueue(ctx=multiprocessing.get_context()) # address = 'localhost' # if address in multiprocessing.managers.BaseProxy._address_to_local: # del BaseProxy._address_to_local[address][0].connection self.queue.put(item) except Exception as e: #general thread exception. logger.error('Buffer queue exception %s' % e) #TODO: continue trying/trap exceptions? raise # check for finished consumers and clean them up before we check to see # if we need to add additional consumers. for csmr in self.running: if not csmr.is_alive(): debug('Child dead, releasing.') self.running.remove(csmr) #see if we should start a consumer... # TODO: add min/max processes (default and override) if not self.running: debug('Spawning consumer.') new_consumer = self.consumer( queue=self.queue, results_queue=self.results_queue, response_error=self.response_error) new_consumer.start() self.running.append(new_consumer) </code></pre> <p>The consumer processes control loop is pretty simple as well:</p> <pre><code> def run(self): '''Consumes the queue in the framework, passing off each item to the ItemHandler method. ''' while True: try: item = self.queue.get(timeout=3) #the base class just logs this stuff rval = self.singleItemHandler(item) self.queue.task_done() if rval and self.results_queue: self.results_queue.put(rval) except queue.Empty: logging.debug('Queue timed out after 3 seconds.') break except EOFError: logging.info( '%s has finished consuming queue.' % (__class__.__name__)) break except Exception as e: #general thread exception. self.logger.error('Consumer exception %s' % e) #TODO: continue trying/trap exceptions? raise </code></pre> <p>After a while (about an hour of successful processing), I get a log message indicating that the consumer process has died due to timing out <code>DEBUG:root:Queue timed out after 3 seconds.</code>, but the queue is still open and apparently still being written to by the original thread. The thread doesn't seem to think that the consumer process has terminated (see the queueAdd method) and doesn't attempt to start a new one. The queue does not appear to be empty, simply reading from it appears to have timed out.</p> <p>I'm at a loss for why the manager thinks the child is still alive.</p> <p>Edit</p> <hr> <p>I have modified the original question due to a code change to how the BrokenPipeError is logged as well as to remove the broken connection cleanup. I consider that a separate issue.</p>
1
2016-07-28T13:05:35Z
38,796,547
<p>The issue was being caused by a subtle reality with multiprocessing.Queue. ANY process which called queue.put will be running a background thread that writes to the named pipe.</p> <p>In my particular case, while there isn't a significant amount of data being posted to the results queue (items that couldn't be handled for some reason) it was still enough to 'fill up' the pipe and cause the consumer to fail to exit even though it wasn't running. This in turn lead to the writing queue filling up slowly.</p> <p>The solution is that I modified my non-blocking call for the next iteration of the api calls to read all of the results available so far except on the last (blocking) call which ensures that all results are fetched.</p> <pre><code>def finish(self, block=True, **kwargs): ''' Notifies the buffer that we are done filling it. This command binds to any processes still running and lets them finish and then copies and flushes the managed results list. ''' # close the queue and wait until it is consumed if block: self.queue.close() self.queue.join_thread() # make sure the consumers are done consuming the queue for csmr in self.running: #get everything on the results queue right now. try: while csmr.is_alive(): self.results_list.append( self.results_queue.get(timeout=0.5)) self.results_queue.task_done() except queue.Empty: if csmr.is_alive(): logger.warn('Result queue empty but consumer alive.') logger.warn('joining %s.' % csmr.name) csmr.join() del self.running[:] if self.callback: return self.callback(self.results_list) else: #read results immediately available. try: while True: self.results_list.append(self.results_queue.get_nowait()) self.results_queue.task_done() except queue.Empty: #got everything on the queue so far pass return self.results_list </code></pre>
0
2016-08-05T19:28:33Z
[ "python", "linux", "multiprocessing" ]
cx_Freeze: shortcutDir gives error
38,637,337
<p>I'm creating a single file exe form my Python program. I'm using cx_Freeze. Everything works perfect except one little agnoying thing.</p> <p>When I install my program everything installs as it should do, including the shortcut on my desktop.</p> <p>BUT...When I want to start the program with the shortcut on the desktop I get the following error:</p> <p><a href="http://i.stack.imgur.com/jvDO6.png" rel="nofollow"><img src="http://i.stack.imgur.com/jvDO6.png" alt="Error"></a></p> <p>When I try to run my program from within my program folder than it works. When I manually create a shortcut to the desktop than it works aswell.</p> <p>Does anyone know why why the shortcut, which is installed at installation of my program doesn't work?</p> <blockquote> <p>My cx_Freeze setup.py</p> </blockquote> <pre><code>import cx_Freeze import sys executables = [cx_Freeze.Executable("Tennis_Calculator.py", base="Win32GUI", icon="tennis_ball.ico", shortcutName="TPC", shortcutDir="DesktopFolder")] build_exe_options = {"icon": "tennis_ball.ico","packages":["Tkinter", "csv", "ttk"], "include_files":["tennis_ball.ico", "testtennis.csv"]} build_msi_options = {"include_files":"testtennis.csv"} cx_Freeze.setup( name = "Tennis Probability Calculator", options = {"build_exe":build_exe_options, "build_msi":build_msi_options}, version = "1.0", author = "WS", executables = executables ) </code></pre>
0
2016-07-28T13:07:45Z
38,645,738
<p>After a long search I found a solution.</p> <p><a href="http://stackoverflow.com/questions/24195311/how-to-set-shortcut-working-directory-in-cx-freeze-msi-bundle">How to set shortcut working directory in cx_freeze msi bundle?</a></p> <p>I was able to fix the problem by making a small change to cx_Freeze/windist.py. In add_config(), line 61, I changed:</p> <pre><code>msilib.add_data(self.db, "Shortcut", [("S_APP_%s" % index, executable.shortcutDir, executable.shortcutName, "TARGETDIR", "[TARGETDIR]%s" % baseName, None, None, None, None, None, None, None)]) </code></pre> <p>to</p> <pre><code>msilib.add_data(self.db, "Shortcut", [("S_APP_%s" % index, executable.shortcutDir, executable.shortcutName, "TARGETDIR", "[TARGETDIR]%s" % baseName, None, None, None, None, None, None, "TARGETDIR")]) # &lt;--- Working directory. </code></pre> <p>Thanks everyone.</p>
0
2016-07-28T20:03:15Z
[ "python", "cx-freeze" ]
Why client socket connection is not closed after all data received from server?
38,637,365
<p>I'm learning socket programming in python, </p> <p><strong>Server Code:</strong> </p> <pre><code>import socket srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srvsock.bind(('', 23000)) srvsock.listen(5) while True: clisock, (rem_host, rem_port) = srvsock.accept() print "conection established with host %s and port %s" % (rem_host, rem_port) while True: strg = clisock.recv(20) if not strg: print 'conection closed' clisock.close() break clisock.send(strg) </code></pre> <p><strong>Client Code:</strong></p> <pre><code>import socket clisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clisock.connect(('', 23000)) clisock.send("Hello World rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr dsadsadsa tttttt\n") while True: data = clisock.recv(20) print type(data) if not data: clisock.close() break print data </code></pre> <p>I'm sending data stream from client to server and at the same time receiving data from server, after successful data transmission, the server not closing client connection. Did I miss any thing ? </p>
1
2016-07-28T13:09:05Z
38,637,900
<p>The issue is caused because the server keeps reading data from the client until it reads no data. This only happens when the connected client closes its connection. Until then, the server socket will block (i.e. temporarily suspect operations) until the client sends more data.</p> <p>Bottom line: either the client or the server has to indicate that it no longer intends to send data over the connection.</p> <p>You can fix the client by adding the line</p> <pre><code>clisock.shutdown(socket.SHUT_WR) </code></pre> <p>before the <code>for</code> loop in the client. This indicates that no more data will be sent.</p>
0
2016-07-28T13:29:10Z
[ "python", "sockets" ]
Why client socket connection is not closed after all data received from server?
38,637,365
<p>I'm learning socket programming in python, </p> <p><strong>Server Code:</strong> </p> <pre><code>import socket srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srvsock.bind(('', 23000)) srvsock.listen(5) while True: clisock, (rem_host, rem_port) = srvsock.accept() print "conection established with host %s and port %s" % (rem_host, rem_port) while True: strg = clisock.recv(20) if not strg: print 'conection closed' clisock.close() break clisock.send(strg) </code></pre> <p><strong>Client Code:</strong></p> <pre><code>import socket clisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clisock.connect(('', 23000)) clisock.send("Hello World rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr dsadsadsa tttttt\n") while True: data = clisock.recv(20) print type(data) if not data: clisock.close() break print data </code></pre> <p>I'm sending data stream from client to server and at the same time receiving data from server, after successful data transmission, the server not closing client connection. Did I miss any thing ? </p>
1
2016-07-28T13:09:05Z
38,638,251
<p>server code:</p> <pre><code>while True: clisock, (rem_host, rem_port) = srvsock.accept() print "conection established with host %s and port %s" % (rem_host, rem_port) while True: strg = clisock.recv(20) print '[message from client:] %s'%strg clisock.send(strg) print 'about to close with client' clisock.close() print 'connection closed with client' break </code></pre> <p>client code :</p> <pre><code>clisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clisock.connect(('', 23000)) clisock.send("Hello World rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr dsadsadsa tttttt\n") while True: data = clisock.recv(20) print '[Message from server :]%s'%data print 'about to close server connection' clisock.close() print 'server connection closed' break </code></pre> <p>This will work out in your case, holdenweb has proper a proper answer why your code is not behaving as expected in above code client only sends one message and closes the connection as well as server listens only for one message per client and closes connection to that client single client -- single connection ---- single message</p>
0
2016-07-28T13:42:54Z
[ "python", "sockets" ]
Map over a dict
38,637,415
<p>I'm trying to do this:</p> <pre><code>list(map(lambda x: x.name, my_dict)) </code></pre> <p>where <code>my_dict</code> is a dict of form <code>k, v</code> where <code>v</code> is an object and <code>v.name</code> is defined.</p> <p>The problem is it is using the key <code>k</code> for <code>x</code> where I really want to use the value <code>v</code>.</p> <p><strong>In other words:</strong> How do I map over the values of a dict?</p> <p>PS I want to avoid <code>my_dict[x]</code> as I will be using <code>concurrent.futures</code> and won't be passing the full dict into separate threads.</p>
2
2016-07-28T13:11:02Z
38,637,557
<p>You don't need to use <code>map()</code> and then convert the result to a list. Instead you can use simply use a list comprehension by looping over the dictionary values:</p> <pre><code>[v.name for v in my_dict.values()] </code></pre> <p>Or still if you are looking for a functional approach you can use <code>attrgetter</code> function from operator module :</p> <pre><code>from operator import attrgetter map(attrgetter('name'), my_dict.values()) </code></pre>
2
2016-07-28T13:17:14Z
[ "python", "python-3.x" ]
Map over a dict
38,637,415
<p>I'm trying to do this:</p> <pre><code>list(map(lambda x: x.name, my_dict)) </code></pre> <p>where <code>my_dict</code> is a dict of form <code>k, v</code> where <code>v</code> is an object and <code>v.name</code> is defined.</p> <p>The problem is it is using the key <code>k</code> for <code>x</code> where I really want to use the value <code>v</code>.</p> <p><strong>In other words:</strong> How do I map over the values of a dict?</p> <p>PS I want to avoid <code>my_dict[x]</code> as I will be using <code>concurrent.futures</code> and won't be passing the full dict into separate threads.</p>
2
2016-07-28T13:11:02Z
38,637,577
<p>To retrieve view of values, you may use <code>.values</code> method.</p> <pre><code>map(callable, my_dict.values()) </code></pre> <p>Obviously, <code>map</code> with trivial callables usually can be avoided in Python by using list or generator comprehensions.</p> <pre><code>[x.name for x in my_dict.values()] # creates list: non-lazy (x.name for x in my_dict.values()) # creates generator: lazy </code></pre>
3
2016-07-28T13:17:56Z
[ "python", "python-3.x" ]
extracting values in a specific column and processing other columns values in pandas
38,637,420
<p>The following is a simplified blob of my dataframe. I want to process</p> <p><a href="https://gist.github.com/ecenm/97248a1d1f6f301d662c6f238b6168df#file-first-csv" rel="nofollow">first.csv</a></p> <pre class="lang-none prettyprint-override"><code>No.,Time,Source,Destination,Protocol,Length,Info,src_dst_pair 325778,112.305107,02:e0,Broadcast,ARP,64,Who has 253.244.230.77? Tell 253.244.230.67,"('02:e0', 'Broadcast')" 801130,261.868118,02:e0,Broadcast,ARP,64,Who has 253.244.230.156? Tell 253.244.230.67,"('02:e0', 'Broadcast')" 700094,222.055094,02:e0,Broadcast,ARP,60,Who has 253.244.230.77? Tell 253.244.230.156,"('02:e0', 'Broadcast')" 766543,247.796156,100.118.138.150,41.177.26.176,TCP,66,32222 &gt; http [SYN] Seq=0,"('100.118.138.150', '41.177.26.176')" 767405,248.073313,100.118.138.150,41.177.26.176,TCP,64,32222 &gt; http [ACK] Seq=1,"('100.118.138.150', '41.177.26.176')" 767466,248.083268,100.118.138.150,41.177.26.176,HTTP,380,Continuation [Packet capture],"('100.118.138.150', '41.177.26.176')" 891394,294.989813,105.144.38.121,41.177.26.15,TCP,66,48852 &gt; http [SYN] Seq=0 Win=65535 Len=0 MSS=1460 SACK_PERM=1,"('105.144.38.121', '41.177.26.15')" 892285,295.320654,105.144.38.121,41.177.26.15,TCP,64,48852 &gt; http [ACK] Seq=1 Ack=1 Win=65535 Len=0,"('105.144.38.121', '41.177.26.15')" 892287,295.321003,105.144.38.121,41.177.26.15,HTTP,350,Continuation or non-HTTP traffic[Packet size limited during capture],"('105.144.38.121', '41.177.26.15')" 893306,295.652079,105.144.38.121,41.177.26.15,TCP,64,48852 &gt; http [ACK] Seq=293 Ack=609 Win=64928 Len=0,"('105.144.38.121', '41.177.26.15')" 893307,295.652233,105.144.38.121,41.177.26.15,TCP,64,"48852 &gt; http [FIN, ACK] Seq=293 Ack=609 Win=64928 Len=0","('105.144.38.121', '41.177.26.15')" 885501,294.070377,105.144.38.139,41.177.26.15,TCP,66,48810 &gt; http [SYN] Seq=0 Win=65535 Len=0 MSS=1460 SACK_PERM=1,"('105.144.38.139', '41.177.26.15')" 887786,294.402349,105.144.38.139,41.177.26.15,TCP,64,48810 &gt; http [ACK] Seq=1 Ack=1 Win=65535 Len=0,"('105.144.38.139', '41.177.26.15')" 887788,294.402642,105.144.38.139,41.177.26.15,HTTP,371,Continuation or non-HTTP traffic[Packet size limited during capture],"('105.144.38.139', '41.177.26.15')" 890133,294.732297,105.144.38.139,41.177.26.15,TCP,64,"48810 &gt; http [FIN, ACK] Seq=314 Ack=629 Win=64907 Len=0","('105.144.38.139', '41.177.26.15')" 890154,294.733413,105.144.38.139,41.177.26.15,TCP,64,48810 &gt; http [ACK] Seq=315 Ack=630 Win=64907 Len=0,"('105.144.38.139', '41.177.26.15')" 902758,297.792645,105.144.38.164,41.177.26.15,TCP,66,49005 &gt; http [SYN] Seq=0 Win=65535 Len=0 MSS=1460 SACK_PERM=1,"('105.144.38.164', '41.177.26.15')" 903926,298.123157,105.144.38.164,41.177.26.15,TCP,64,49005 &gt; http [ACK] Seq=1 Ack=1 Win=65535 Len=0,"('105.144.38.164', '41.177.26.15')" 903932,298.123369,105.144.38.164,41.177.26.15,HTTP,350,Continuation or non-HTTP traffic[Packet size limited during capture],"('105.144.38.164', '41.177.26.15')" 905269,298.455368,105.144.38.164,41.177.26.15,TCP,64,49005 &gt; http [ACK] Seq=293 Ack=609 Win=64928 Len=0,"('105.144.38.164', '41.177.26.15')" 905273,298.455557,105.144.38.164,41.177.26.15,TCP,64,"49005 &gt; http [FIN, ACK] Seq=293 Ack=609 Win=64928 Len=0","('105.144.38.164', '41.177.26.15')" 906162,298.714281,105.144.38.204,41.177.26.15,TCP,66,49050 &gt; http [SYN] Seq=0 Win=65535 Len=0 MSS=1460 SACK_PERM=1,"('105.144.38.204', '41.177.26.15')" 907292,299.025951,105.144.38.204,41.177.26.15,TCP,64,49050 &gt; http [ACK] Seq=1 Ack=1 Win=65535 Len=0,"('105.144.38.204', '41.177.26.15')" 907294,299.026985,105.144.38.204,41.177.26.15,HTTP,354,Continuation or non-HTTP traffic[Packet size limited during capture],"('105.144.38.204', '41.177.26.15')" 907811,299.362918,105.144.38.204,41.177.26.15,TCP,64,49050 &gt; http [ACK] Seq=297 Ack=613 Win=64924 Len=0,"('105.144.38.204', '41.177.26.15')" 907812,299.362951,105.144.38.204,41.177.26.15,TCP,64,"49050 &gt; http [FIN, ACK] Seq=297 Ack=613 Win=64924 Len=0","('105.144.38.204', '41.177.26.15')" </code></pre> <p>How can I do the following in pandas? For each unique <code>df.src_dst_pair</code> (last element in each row):</p> <ol> <li><p>Check if <code>df.Info</code> has <code>[SYN]</code>. If not, skip the row.</p></li> <li><p>If <code>df.Info</code> has <code>[SYN]</code>, store the <code>df.Time</code> (indicates start time) </p></li> <li><p>Start accumulating the <code>df.Length</code> from <code>[SYN]</code> till we find <code>[FIN, ACK]</code> </p></li> <li><p>Once we find the <code>[FIN, ACK]</code> in <code>df.info</code>, store the <code>df.Time</code> (indicates stop time). If no <code>[FIN, ACK]</code> is found in <code>df.Info</code> for a <code>df.src_dst_pair</code>, then skip the <code>df.src_dst_pair</code>.</p></li> <li><p>Finally, summarize the result.</p></li> </ol> <pre class="lang-none prettyprint-override"><code>df.src_dst_pair: flow number, (accumulated) df.Length, df.Time(stop)-df.Time(start) </code></pre> <p><strong>Expected output for first.csv</strong></p> <pre class="lang-none prettyprint-override"><code>('105.144.38.121', '41.177.26.15') : flow 1, 1118, 0.66242 ('105.144.38.139', '41.177.26.15') : flow 1, 565, 0.028527 ('105.144.38.139', '41.177.26.15') : flow 2, 608, 0.662912 ('105.144.38.204', '41.177.26.15') : flow 1, 612, 0.64867 </code></pre> <p><strong>My approach:</strong></p> <pre><code>import pandas import numpy data = pandas.read_csv('first.csv') print data uniq_src_dst_pair = numpy.unique(data.src_dst_pair.ravel()) print uniq_src_dst_pair print len(uniq_src_dst_pair) # for now only able to sort data based on src_dst_pair, need flow info. result = data.groupby('src_dst_pair').Length.sum() print result </code></pre>
0
2016-07-28T13:11:13Z
38,643,363
<pre><code>import pandas as pd def extract_flows(g): # Find the location of SYN packets is_syn = g['Info'].fillna('').str.contains('\[SYN\]') syn = g[is_syn].index.values # Find the location of the FIN-ACK packets is_finack = g['Info'].fillna('').str.contains('\[FIN, ACK\]') finack = g[is_finack].index.values # Loop over SYN packets runs = [] for num, start in enumerate(syn, start=1): try: # Find the first FIN-ACK packet after each SYN packet # If none, raises IndexError stop = finack[finack &gt; start][0] runs.append([# The flow number counter num, # The time difference between the packets g.loc[stop, 'Time'] - g.loc[start, 'Time'], # The accumulated length g.loc[start:stop, 'Length'].sum()]) except IndexError: break # The output must be a DataFrame output = (pd.DataFrame(runs, columns=['Flow number', 'Time', 'Length']) .set_index('Flow number')) return output df = pd.read_csv('first.csv', usecols = ['src_dst_pair', 'Info', 'Time', 'Length']) result = df.groupby('src_dst_pair').apply(extract_flows) print(result) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code> Time Length src_dst_pair Flow number ('105.144.38.121', '41.177.26.15') 1 0.662420 608.0 ('105.144.38.139', '41.177.26.15') 1 0.661920 565.0 2 0.662912 608.0 ('105.144.38.204', '41.177.26.15') 1 0.648670 612.0 </code></pre> <p><em>N.B.</em>: the sample data in the OP does not coincide with that in the linked <code>first.csv</code>. Some of the numbers in the above output coincide with the OP's desired output for processing of <code>first.csv</code> &mdash; yet others differ, and I think mine are the correct ones. </p>
1
2016-07-28T17:46:00Z
[ "python", "csv", "pandas" ]
How to execute multiple update queries once in pymongo?
38,637,480
<p>I have more than 100000 update queries need to be execute, <code>db.collection_name.update(upsert=True)</code> can only execute one query statement,it is too slow if I execute all queries one by one.</p> <p>Is there any way to collect multiple queries into a list then execute once in pymongo?</p> <p>I tried use <a href="http://api.mongodb.com/python/current/examples/bulk.html" rel="nofollow">bulk</a>, and it doesn't save any time, also not a transaction operation :(</p> <p>Here is my code snippet:</p> <pre><code>bulk = self._db.initialize_unordered_bulk_op() for user_id, result in results.items(): time_stamp = time.strftime('%Y-%m-%d:%H:%M:%S') history = { 'create_at': time_stamp, 'results': result } bulk.find({'user_id': user_id}).update( {'$set': {'update_at': time_stamp}} ) bulk.find({'user_id': user_id}).update( {'$addToSet': {'history': history}} ) bulk.execute() </code></pre> <p>it is almost the same speed as following update statement:</p> <pre><code>self._db.update( {'user_id': user_id}, {'$set': {'update_at':time.strftime('%Y-%m-%d:%H:%M:%S')}}, upsert=True ) self._db.update( {'user_id': user_id}, {'$addToSet': {'history': history}}, upsert=True ) </code></pre>
0
2016-07-28T13:13:53Z
38,637,753
<p>You could introduce a counter variable that ensures the updates are sent in batches because write commands can accept no more than 1000 operations so there's need to group operations to have at most 1000 operations and re-intialise the bulk operation when the loop hits the 1000 iteration. Also, DRY (Don't Repeat Yourself): merge the update statements <code>$set</code> and <code>$addToSet</code> into one update document. Your final update script should perform much better:</p> <pre><code>bulk = self._db.initialize_unordered_bulk_op() counter = 0; for user_id, result in results.items(): time_stamp = time.strftime('%Y-%m-%d:%H:%M:%S') history = { 'create_at': time_stamp, 'results': result } bulk.find({'user_id': user_id}).update({ '$set': { 'update_at': time_stamp }, '$addToSet': { 'history': history } }) counter++ if (counter % 1000 == 0): bulk.execute() bulk = self._db.initialize_unordered_bulk_op() if (counter % 1000 != 0): bulk.execute() </code></pre>
0
2016-07-28T13:24:37Z
[ "python", "mongodb", "pymongo" ]
join file binary with text to create POST request body - python
38,637,543
<p>I'm trying to upload file to Google Drive using their API.</p> <p>According to their specification, the body of the POST request should look like this:</p> <pre><code>--foo_bar_baz Content-Type: application/json; charset=UTF-8 { "name": "My File" } --foo_bar_baz Content-Type: image/jpeg JPEG data --foo_bar_baz-- </code></pre> <p>Assuming I have a path to the <em>JPEG file</em>, how to construct the request's body (<em>"load the file plus prepend and append the text to it"</em>)?</p> <p>Thank you.</p> <p>PS: Please don't suggest Google Client Library. It's about creating the request's body:)</p>
0
2016-07-28T13:16:40Z
38,655,900
<p>As discussed in <a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">Advanced Usage</a>, </p> <blockquote> <p>Requests supports streaming uploads, which allow you to send large streams or files without reading them into memory. To stream and upload, simply provide a file-like object for your body:</p> </blockquote> <pre><code>with open('massive-body', 'rb') as f: requests.post('http://some.url/streamed', data=f) </code></pre> <p>However, please note that it is strongly recommended that you open files in binary mode. This is because Requests may attempt to provide the Content-Length header for you, and if it does this value will be set to the number of bytes in the file. <strong>Errors may occur if you open the file in text mode.</strong></p> <p>This <a href="http://docs.python-requests.org/en/master/user/quickstart/" rel="nofollow">Quickstart</a> will be helpful too.</p>
0
2016-07-29T09:58:35Z
[ "python", "google-drive-sdk", "python-requests" ]
django-haystack with elastic search not building index for newly add index model
38,637,635
<p>I'm using Haystack 2.3.1 and trying to figure out multiple indexes.</p> <p>I've got elasticsearch cores set up and defined each in HAYSTACK_CONNECTIONS, and then I've created three SearchIndexes in search_indexes.py.</p> <p>When I run the command manage.py rebuild_index, I see this warning.</p> <p>Thanks for any tips and let me know if I'm missing anything. </p> <p>setting.py:</p> <p>```</p> <pre><code>HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'default', 'TIMEOUT': 60 * 5, 'INCLUDE_SPELLING': True, 'SILENTLY_FAIL': True, 'EXCLUDED_INDEXES': ['dmmactress.search_indexes.ActressInfoIndex'], }, 'autocomplete': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'autocomplete', 'TIMEOUT': 60 * 5, 'INCLUDE_SPELLING': True, 'SILENTLY_FAIL': True, 'EXCLUDED_INDEXES': ['dmmactress.search_indexes.EnActress'], }, 'autocomplete2': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'autocomplete2', 'TIMEOUT': 60 * 5, 'INCLUDE_SPELLING': True, 'SILENTLY_FAIL': True, 'EXCLUDED_INDEXES': ['dmmactress.search_indexes.EnMovielist'], }, } HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' </code></pre> <p>```</p> <p>search_indexes.py</p> <p>```</p> <pre><code>class ActressInfoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') birth = indexes.CharField(model_attr='birth') starsign = indexes.CharField(model_attr='starsign') bloodtype = indexes.CharField(model_attr='bloodtype') boobs = indexes.CharField(model_attr='boobs') home = indexes.CharField(model_attr='home') hobby = indexes.CharField(model_attr='hobby') image_paths = indexes.CharField(model_attr='image_paths') def get_model(self): return ActressInfo def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() class EnActress(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') image_paths = indexes.CharField(model_attr='image_paths') def get_model(self): return EnActress def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() class EnMovielist(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) Content_ID = indexes.CharField(model_attr='Content_ID') release_date = indexes.CharField(model_attr='release_date') running_time = indexes.CharField(model_attr='running_time') Actress = indexes.CharField(model_attr='Actress') Series = indexes.CharField(model_attr='Series') Studio = indexes.CharField(model_attr='Studio') Director = indexes.CharField(model_attr='Director') Label = indexes.CharField(model_attr='Label') image_paths = indexes.CharField(model_attr='image_paths') def get_model(self): return EnMovielist def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() </code></pre> <p>```</p> <p>_text.txt</p> <p>```</p> <pre><code>{{ object.name}} {{ object.image_paths }} {{ object.birth }} {{ object.starsign }} {{ object.bloodtype }} {{ object.boobs }} {{ object.home }} {{ object.hobby }} {{ object.EnMovielist.Content_ID }} {{ object.EnMovielist.image_paths }} {{ object.EnMovielist.release_date }} {{ object.EnMovielist.running_time }} {{ object.EnMovielist.Actress }} {{ object.EnMovielist.Series }} {{ object.EnMovielist.Studio }} {{ object.EnMovielist.Director }} {{ object.EnMovielist.Label }} {{ object.EnActress.name}} {{ object.EnActress.image_paths }} </code></pre> <p>```</p> <p>..after running</p> <p><code> Indexing 9464 actress infos GET /autocomplete/_mapping [status:404 request:0.001s] Indexing 9464 actress infos GET /autocomplete2/_mapping [status:404 request:0.003s] </code></p>
0
2016-07-28T13:20:17Z
38,656,368
<p>Make sure that which version of <code>elasticsearch</code> you are using? If you are using <code>django-haystack</code> then your <code>elasticsearch</code> should be less than 2.00.</p>
0
2016-07-29T10:19:34Z
[ "python", "django", "elasticsearch" ]
pyimage2 does not exist error when I try to insert an image to window
38,637,637
<p>I am trying to insert an image to window but I get an error.</p> <pre><code>Traceback (most recent call last): File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__ return self.func(*args) File "C:\Users\Afro\Desktop\h.py", line 151, in start pic_lab = Label(wind,image=pik) File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2605, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2138, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "pyimage2" doesn't exist </code></pre> <p>Here's my code</p> <pre><code>wind = Tk() name = money.jpg' pik = ImageTk.PhotoImage(Image.open(name)) pic_lab = Label(wind,image=pik) pic_lab.grid() </code></pre> <p>What do I need to do?</p>
0
2016-07-28T13:20:24Z
38,644,109
<p>The string 'money.jpg' that is assigned to the variable name is missing a single quotation mark on the left.</p>
1
2016-07-28T18:26:20Z
[ "python", "python-3.x", "tkinter", "python-imaging-library" ]
Using a list of tuples on a function which take tuples
38,637,638
<p>I want to use a function which takes tuples as an argument, however I have a list of tuples and whenever I try feeding the list of tuples to the function it returns </p> <pre><code> s = s.join(x) TypeError: sequence item 0: expected str instance, tuple found </code></pre> <p>However with just one tuple on its own without a list around it, the function will work as expected. </p> <p>Is there a way in which I can feed a list of tuples like this:</p> <pre><code>[('abcd','1234','xyz'),('e.t.c', 'e.t.c', 'test')] </code></pre> <p>to a function which takes single tuples on their own? Thanks :)</p> <p>EDIT - This is the function I am feeding the list of tuples to: </p> <pre><code>def strFormat(x): #Convert to string s=' ' s = s.join(x) print(s) #Split string into different parts payR, dep, sal, *other, surn = s.split() other = " ".join(other) #Print formatting! print ("{:5}, {:5} {:&gt;10} {:10} £{:10}".format(surn , other, payR, dep, sal)) </code></pre> <p>When putting a single tuple to this function it returns the print formatted string as expected. When putting a list of tuples to this function it does not work and returns an error. How do I make it so a list of tuples like the one above will work on the above function?</p>
-1
2016-07-28T13:20:26Z
38,637,720
<p>If you want to join the tuples separately you can use a list comprehension:</p> <pre><code>[delimiter.join(x) for x in list_of_tup] # delimiter should be a string </code></pre> <p>Otherwise you need to unpack the tuples then join them all. Which for that aim you can use a nested list comprehension or <code>itertools.chain</code>:</p> <pre><code>delimiter.join([item for tup in list_of_tup for item in tup]) </code></pre>
0
2016-07-28T13:23:23Z
[ "python" ]
Python passing arguments - a confused beginner
38,637,687
<p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = int(raw_input('Enter: ')) test(y) print 'Outside the function', y </code></pre> <blockquote> <p>Enter: 6 </p> <p>Inside the function 36</p> <p>Outside the function 6</p> </blockquote> <p>However, when the code is as below:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = test(6) print 'Outside the function', y </code></pre> <blockquote> <p>Inside the function 36 </p> <p>Outside the function 36</p> </blockquote> <p>Why does the first code snippet provide 36, 6 and <strong>not</strong> 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.</p> <p><em>For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this</em></p> <p>Many thanks for your time, any help is greatly appreciated.</p>
0
2016-07-28T13:21:54Z
38,637,795
<p>Because you changed the value of y on the second example by setting y = test(6). Set y = test(y) on the first and you will get the same result.</p>
0
2016-07-28T13:25:59Z
[ "python", "return", "return-value" ]
Python passing arguments - a confused beginner
38,637,687
<p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = int(raw_input('Enter: ')) test(y) print 'Outside the function', y </code></pre> <blockquote> <p>Enter: 6 </p> <p>Inside the function 36</p> <p>Outside the function 6</p> </blockquote> <p>However, when the code is as below:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = test(6) print 'Outside the function', y </code></pre> <blockquote> <p>Inside the function 36 </p> <p>Outside the function 36</p> </blockquote> <p>Why does the first code snippet provide 36, 6 and <strong>not</strong> 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.</p> <p><em>For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this</em></p> <p>Many thanks for your time, any help is greatly appreciated.</p>
0
2016-07-28T13:21:54Z
38,637,796
<p>The only difference between the two snippets is that in the second one you reassign <code>y</code> to to the result of calling the function. That is all you need to do.</p>
0
2016-07-28T13:26:01Z
[ "python", "return", "return-value" ]
Python passing arguments - a confused beginner
38,637,687
<p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = int(raw_input('Enter: ')) test(y) print 'Outside the function', y </code></pre> <blockquote> <p>Enter: 6 </p> <p>Inside the function 36</p> <p>Outside the function 6</p> </blockquote> <p>However, when the code is as below:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = test(6) print 'Outside the function', y </code></pre> <blockquote> <p>Inside the function 36 </p> <p>Outside the function 36</p> </blockquote> <p>Why does the first code snippet provide 36, 6 and <strong>not</strong> 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.</p> <p><em>For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this</em></p> <p>Many thanks for your time, any help is greatly appreciated.</p>
0
2016-07-28T13:21:54Z
38,637,857
<p>In the first code, you have a global variable named  <code>y</code>, which you assign the value 6 to. When going into the function, you create a local variable, also called <code>y</code>, which you assign the value 6*6=36 to. When you leave the function, you return this value, but do not use it. Then, you print the global <code>y</code>. </p> <p>In the second code, you assign the returned value (local <code>y</code> = 36) to your global value <code>y</code>, thus making the two printed values to be the same.</p>
0
2016-07-28T13:27:39Z
[ "python", "return", "return-value" ]
Python passing arguments - a confused beginner
38,637,687
<p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = int(raw_input('Enter: ')) test(y) print 'Outside the function', y </code></pre> <blockquote> <p>Enter: 6 </p> <p>Inside the function 36</p> <p>Outside the function 6</p> </blockquote> <p>However, when the code is as below:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = test(6) print 'Outside the function', y </code></pre> <blockquote> <p>Inside the function 36 </p> <p>Outside the function 36</p> </blockquote> <p>Why does the first code snippet provide 36, 6 and <strong>not</strong> 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.</p> <p><em>For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this</em></p> <p>Many thanks for your time, any help is greatly appreciated.</p>
0
2016-07-28T13:21:54Z
38,637,894
<blockquote> <p>Why does the first code snippet provide 36, 6 and not 36, 36 as in the second case?</p> </blockquote> <p>Because you defined an entirely new y variable whose value is 36, meanwhile the value outside the function is 6.</p> <p>In the second case, you still have two y variables, but the one towards the bottom (almost said first one, because it technically is executed first) is the return value of the method</p>
0
2016-07-28T13:28:59Z
[ "python", "return", "return-value" ]
Python passing arguments - a confused beginner
38,637,687
<p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = int(raw_input('Enter: ')) test(y) print 'Outside the function', y </code></pre> <blockquote> <p>Enter: 6 </p> <p>Inside the function 36</p> <p>Outside the function 6</p> </blockquote> <p>However, when the code is as below:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = test(6) print 'Outside the function', y </code></pre> <blockquote> <p>Inside the function 36 </p> <p>Outside the function 36</p> </blockquote> <p>Why does the first code snippet provide 36, 6 and <strong>not</strong> 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.</p> <p><em>For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this</em></p> <p>Many thanks for your time, any help is greatly appreciated.</p>
0
2016-07-28T13:21:54Z
38,637,911
<p>You don't assign the result of <code>test(y)</code> the variable y in your code</p> <pre><code>y=int(raw_input('Enter: ')) # y= 6 # here you need to assign y= test(y) test(y) # test result is 36, but not saved to y print 'Outside the function', y # print 6 </code></pre>
0
2016-07-28T13:29:30Z
[ "python", "return", "return-value" ]
Python passing arguments - a confused beginner
38,637,687
<p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = int(raw_input('Enter: ')) test(y) print 'Outside the function', y </code></pre> <blockquote> <p>Enter: 6 </p> <p>Inside the function 36</p> <p>Outside the function 6</p> </blockquote> <p>However, when the code is as below:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = test(6) print 'Outside the function', y </code></pre> <blockquote> <p>Inside the function 36 </p> <p>Outside the function 36</p> </blockquote> <p>Why does the first code snippet provide 36, 6 and <strong>not</strong> 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.</p> <p><em>For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this</em></p> <p>Many thanks for your time, any help is greatly appreciated.</p>
0
2016-07-28T13:21:54Z
38,638,015
<p><strong>case #1 explained</strong></p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y; # returning 36 y=int(raw_input('Enter: ')) # here y is 6 as you read from user test(y) # you are passing 6 and which computes y to be 36, though test is returning 36, but it is not stored in any variable (including y). (not re-assigned, so outside the definition/fucntion, y is still 6) print 'Outside the function', y # so it is still 6 </code></pre> <p><strong>Case #2 explained</strong></p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y; # returning 36 y=test(6) # here you received and stored it in y print 'Outside the function', y # now y is 36 </code></pre>
1
2016-07-28T13:33:06Z
[ "python", "return", "return-value" ]
Python passing arguments - a confused beginner
38,637,687
<p>I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = int(raw_input('Enter: ')) test(y) print 'Outside the function', y </code></pre> <blockquote> <p>Enter: 6 </p> <p>Inside the function 36</p> <p>Outside the function 6</p> </blockquote> <p>However, when the code is as below:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y y = test(6) print 'Outside the function', y </code></pre> <blockquote> <p>Inside the function 36 </p> <p>Outside the function 36</p> </blockquote> <p>Why does the first code snippet provide 36, 6 and <strong>not</strong> 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.</p> <p><em>For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this</em></p> <p>Many thanks for your time, any help is greatly appreciated.</p>
0
2016-07-28T13:21:54Z
38,638,563
<p>There are two reasons the output is not the same: - the scopes are different, in your first example, the y you assign in the function is <em>not</em> the same the y outside of it, even if they have the same name. To (over)simplify, you can think that, when you start a new function, there is a brand new memory space created and, inside of it, there is nothing already present (except the modules names imported, the argument to the function, ...), so, even if you do an assignation to y inside the function, it is a brand new y, and, its life stops when the function is over. - in the second example, you take to output of your function and put it in y, in the first example, the output is lost since not used.</p> <p>To illustrate my first point:</p> <pre><code>#!/usr/bin/python def test(arg1): y = arg1 * arg1 print 'Inside the function', y return y; test(3) print y </code></pre> <p>This will raise NameError, because, outside the function, y does not exists.</p> <p>I invite you to read and understand this very simple explanation <a href="http://gettingstartedwithpython.blogspot.be/2012/05/variable-scope.html" rel="nofollow">Getting Started with Python - Variable scope</a></p>
0
2016-07-28T13:54:41Z
[ "python", "return", "return-value" ]
Python Regex to find image source
38,637,734
<p>I am new to Python and I am trying to get <strong>alt</strong> and <strong>images source</strong> from a website, but I am facing problem with the quote <code>'</code> and <code>"</code></p> <pre><code>import requests,urllib,urllib2,re rule = re.compile(r'^[^*$&lt;,&gt;?!\']*$') r = requests.get('http://www.hotstar.com/channels/star-plus') match = re.compile('&lt;img alt="(.*?)" ng-mouseleave="mouseLeaveCard()" ng-mouseenter="mouseEnterCard()" ng-click="mouseEnterCard(true)" ng-class="{\'dull-img\': isThumbnailTitleVisible || isRegionalLanguageVisible}" class="show-card imgtag card-minheight-hc ng-scope ng-isolate-scope" placeholder-img="{\'realUrl\' : \'(.*?)\', \'placeholderUrl\' : \'./img/placeholder/hs.jpg\'}" ng-if="record.urlPictures" src="(.*?)" style="display: block;"&gt;',re.DOTALL).findall(r.content) for name,img,image in match: </code></pre> <p>I can only use the standard Python library.</p> <p>I've read about defining rule so I did from this: <a href="http://stackoverflow.com/questions/17486765/regex-apostrophe-how-to-match">Regex Apostrophe how to match?</a></p> <p>Honestly, I don't know how to use it.</p> <p>Thanks in advance</p>
-3
2016-07-28T13:23:48Z
38,638,055
<p>Use a parser instead:</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get('http://www.hotstar.com/channels/star-plus') soup = BeautifulSoup(r.text, "lxml") imgs = soup.findAll('img') for img in imgs: print(img["alt"]) </code></pre>
0
2016-07-28T13:34:47Z
[ "python", "regex" ]
Python Regex to find image source
38,637,734
<p>I am new to Python and I am trying to get <strong>alt</strong> and <strong>images source</strong> from a website, but I am facing problem with the quote <code>'</code> and <code>"</code></p> <pre><code>import requests,urllib,urllib2,re rule = re.compile(r'^[^*$&lt;,&gt;?!\']*$') r = requests.get('http://www.hotstar.com/channels/star-plus') match = re.compile('&lt;img alt="(.*?)" ng-mouseleave="mouseLeaveCard()" ng-mouseenter="mouseEnterCard()" ng-click="mouseEnterCard(true)" ng-class="{\'dull-img\': isThumbnailTitleVisible || isRegionalLanguageVisible}" class="show-card imgtag card-minheight-hc ng-scope ng-isolate-scope" placeholder-img="{\'realUrl\' : \'(.*?)\', \'placeholderUrl\' : \'./img/placeholder/hs.jpg\'}" ng-if="record.urlPictures" src="(.*?)" style="display: block;"&gt;',re.DOTALL).findall(r.content) for name,img,image in match: </code></pre> <p>I can only use the standard Python library.</p> <p>I've read about defining rule so I did from this: <a href="http://stackoverflow.com/questions/17486765/regex-apostrophe-how-to-match">Regex Apostrophe how to match?</a></p> <p>Honestly, I don't know how to use it.</p> <p>Thanks in advance</p>
-3
2016-07-28T13:23:48Z
38,638,284
<p>I took a quick look at this problem and I tried to look in to and I found a few different ways to go about it from looking at the links below. It looks like something like this has happened to other people. I took a quick glance at it, and thought maybe these might help. Try looking at a few of the pages below:</p> <p>Possibly similar posts:</p> <ul> <li><a href="http://stackoverflow.com/questions/17486765/regex-apostrophe-how-to-match">Regex Apostrophe how to match?</a></li> <li><a href="http://stackoverflow.com/questions/11696745/beautifulsoup-extract-img-alt-data">BeautifulSoup: Extract img alt data</a> </li> <li><a href="http://stackoverflow.com/questions/22710315/regex-for-search-and-get-the-src-of-a-image">Regex for search and get the src of a image</a></li> </ul> <p>Then you could also try looking at <a href="https://docs.python.org/2/library/re.html" rel="nofollow">Python's Regular Expression Documentation</a>.</p>
0
2016-07-28T13:44:05Z
[ "python", "regex" ]
BeautifulSoap to get first value using string/text
38,637,792
<p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautifulsoup</a> is handy for html parsing in python, but I meet problem to have clean code to get the value directly using <code>string</code> or <code>text</code></p> <pre><code>from bs4 import BeautifulSoup tr =""" &lt;table&gt; &lt;tr&gt;&lt;td&gt;text1&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;text2&lt;div&gt;abc&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; """ table = BeautifulSoup(tr,"html.parser") for row in table.findAll("tr"): td = row.findAll("td") print td[0].text print td[0].string </code></pre> <p>result:</p> <pre><code>text1 text1 text2abc None </code></pre> <p>How can I get the result for</p> <pre><code>text1 text2 </code></pre> <p>I want to skip the extra inner tag</p> <p><code>beautifulsoup4-4.5.0</code> is used with <code>python 2.7</code></p>
1
2016-07-28T13:25:55Z
38,638,078
<p>You could try this:</p> <pre><code>for row in table.findAll("tr"): td = row.findAll("td") t = td[0] print t.contents[0] </code></pre> <p>But that will only work if you are always looking for the text <em>before</em> the div tag</p>
1
2016-07-28T13:35:38Z
[ "python", "beautifulsoup", "html-parsing" ]
BeautifulSoap to get first value using string/text
38,637,792
<p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautifulsoup</a> is handy for html parsing in python, but I meet problem to have clean code to get the value directly using <code>string</code> or <code>text</code></p> <pre><code>from bs4 import BeautifulSoup tr =""" &lt;table&gt; &lt;tr&gt;&lt;td&gt;text1&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;text2&lt;div&gt;abc&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; """ table = BeautifulSoup(tr,"html.parser") for row in table.findAll("tr"): td = row.findAll("td") print td[0].text print td[0].string </code></pre> <p>result:</p> <pre><code>text1 text1 text2abc None </code></pre> <p>How can I get the result for</p> <pre><code>text1 text2 </code></pre> <p>I want to skip the extra inner tag</p> <p><code>beautifulsoup4-4.5.0</code> is used with <code>python 2.7</code></p>
1
2016-07-28T13:25:55Z
38,638,729
<p>You could simply use the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find" rel="nofollow"><code>.find()</code></a> function by setting the <code>text</code> and <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-recursive-argument" rel="nofollow"><code>recursive</code></a> argument.</p> <pre><code>for row in table.findAll("tr"): td1 = row.td.find(text=True, recursive=False) print str(td1) </code></pre> <p>You'll get your output as:</p> <pre><code>text1 text2 </code></pre> <p>This will work regardless of the position of the <code>div</code> tag. See the example below.</p> <pre><code>&gt;&gt;&gt; tr =""" &lt;table&gt; &lt;tr&gt;&lt;td&gt;text1&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;text2&lt;div&gt;abc&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;div&gt;abc&lt;/div&gt;text3&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; """ &gt;&gt;&gt; table = BeautifulSoup(tr,"html.parser") &gt;&gt;&gt; for row in table.findAll("tr"): td1 = row.td.find(text=True, recursive=False) print str(td1) text1 text2 text3 </code></pre>
2
2016-07-28T14:01:24Z
[ "python", "beautifulsoup", "html-parsing" ]
BeautifulSoup4 fails to parse multiple tables
38,637,870
<p>I'd like to systematically scrape the privacy breach data found <a href="https://www.privacyrights.org/data-breach/new?title=" rel="nofollow">here</a> which is directly embedded in the HTML of the page. I've found various links on StackOverflow about <a href="http://stackoverflow.com/questions/37021747/missing-html-in-response-using-python-requests-and-beautifulsoup4">missing HTML</a> and <a href="http://stackoverflow.com/questions/34291519/cant-scrape-a-specific-table-using-beautifulsoup4-python-3">not being able to scrape a table using BS4</a>. Both of these threads seem very similar to the issue that I'm having, however i'm having a difficult time reconciling the differences.</p> <p><strong>Here's my problem:</strong> When I pull the HTML using either Requests or urllib (python 3.6) the second table does not appear in the soup. The second link above details that this can occur if the table/data is added in after the page loads using javascript. However when I examine the page source the data is all there, so that doesn't seem to be the issue. A snippet of my code is below.</p> <pre><code>url = 'https://www.privacyrights.org/data-breach/new?title=&amp;page=1' r = requests.get(url, verify=False) soupy = BeautifulSoup(r.content, 'html5lib') print(len(soupy.find_all('table'))) # only finds 1 table, there should be 2 </code></pre> <p>This code snippet fails to find the table with the actual data in it. I've tried lmxl, html5lib, and html.parse parsers. I've tried urllib and Requests packages to pull down the page.</p> <p>Why can't requests + BS4 find the table that I'm looking for?</p>
0
2016-07-28T13:28:01Z
38,638,148
<p>Looking at the HTML delivered from the URL it appears that there only IS one table in it, which is precisely why Beautiful Soup can't find two!</p>
0
2016-07-28T13:38:26Z
[ "python", "html", "web-scraping", "beautifulsoup", "python-requests" ]
Conversion from U3 dtype to ascii
38,638,013
<p>I am reading data from a .mat file. The data is in form on numpy array.</p> <pre><code>[array([u'ABT'], dtype='&lt;U3')] </code></pre> <p>This is one element of the array. I want to get only the value 'ABT' from the array. Unicode normalize and Encode to ascii functions do not work.</p>
1
2016-07-28T13:32:59Z
38,641,632
<p><code>encode</code> is a string method, so can't work directly on an array of strings. But there are several ways of applying it to each string</p> <p>Here I'm working Py3, so the default is unicode.</p> <pre><code>In [179]: A=np.array(['one','two']) In [180]: A Out[180]: array(['one', 'two'], dtype='&lt;U3') </code></pre> <p>plain iteration:</p> <pre><code>In [181]: np.array([s.encode() for s in A]) Out[181]: array([b'one', b'two'], dtype='|S3') </code></pre> <p><code>np.char</code> has functions that apply string methods to each element of an array:</p> <pre><code>In [182]: np.char.encode(A) Out[182]: array([b'one', b'two'], dtype='|S3') </code></pre> <p>but it looks like this is one of the conversions that <code>astype</code> can handle:</p> <pre><code>In [183]: A.astype('&lt;S3') Out[183]: array([b'one', b'two'], dtype='|S3') </code></pre> <p>And inspired by a recent question about <code>np.chararray</code>: <a href="http://stackoverflow.com/questions/38621820/what-happened-to-numpy-chararray">What happened to numpy.chararray</a></p> <pre><code>In [191]: Ac=np.char.array(A) In [192]: Ac Out[192]: chararray(['one', 'two'], dtype='&lt;U3') In [193]: Ac.encode() Out[193]: array([b'one', b'two'], dtype='|S3') </code></pre>
0
2016-07-28T16:11:50Z
[ "python", "numpy", "unicode", "ascii" ]
format Date in pandas style render
38,638,025
<p>I have a pandas dataframe with three columns of which the first is the Date. To produce a html output I use this: </p> <pre><code>html_string = df.style.format({'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render() </code></pre> <p>how is it possible to specifiy the format of the Date as well...something like:</p> <pre><code>html_string = df.style.format({'Date': "%Y.%m",'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render() </code></pre>
2
2016-07-28T13:33:43Z
38,638,369
<p>You can do:</p> <pre><code>html_string = df.style.format({'Date': "{:%Y.%m}", 'second': "{:0,.0f}", 'third': "{:0,.0f}"}).set_table_styles(styles).render() </code></pre>
1
2016-07-28T13:47:19Z
[ "python", "pandas" ]
format Date in pandas style render
38,638,025
<p>I have a pandas dataframe with three columns of which the first is the Date. To produce a html output I use this: </p> <pre><code>html_string = df.style.format({'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render() </code></pre> <p>how is it possible to specifiy the format of the Date as well...something like:</p> <pre><code>html_string = df.style.format({'Date': "%Y.%m",'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render() </code></pre>
2
2016-07-28T13:33:43Z
38,638,417
<p>For me works:</p> <pre><code>html_string = df.style.format({'first': lambda x: "{}".format(x.strftime('%Y.%m')) , 'second': "{:0,.0f}", 'third': "{:0,.0f}"}).set_table_styles('styles').render() print (html_string) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({ 'first':['2015-01-05','2015-01-06','2015-01-07'], 'second':[4,2.1,5.9], 'third':[8,5.1,7.7]}) df['first'] = pd.to_datetime(df['first'] ) print (df) first second third 0 2015-01-05 4.0 8.0 1 2015-01-06 2.1 5.1 2 2015-01-07 5.9 7.7 </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4f" None&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="blank"&gt; &lt;th class="col_heading level0 col0"&gt;first &lt;th class="col_heading level0 col1"&gt;second &lt;th class="col_heading level0 col2"&gt;third &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4f" class="row_heading level2 row0"&gt; 0 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow0_col0" class="data row0 col0"&gt; 2015.01 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow0_col1" class="data row0 col1"&gt; 4 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow0_col2" class="data row0 col2"&gt; 8 &lt;/tr&gt; &lt;tr&gt; &lt;th id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4f" class="row_heading level2 row1"&gt; 1 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow1_col0" class="data row1 col0"&gt; 2015.01 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow1_col1" class="data row1 col1"&gt; 2 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow1_col2" class="data row1 col2"&gt; 5 &lt;/tr&gt; &lt;tr&gt; &lt;th id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4f" class="row_heading level2 row2"&gt; 2 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow2_col0" class="data row2 col0"&gt; 2015.01 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow2_col1" class="data row2 col1"&gt; 6 &lt;td id="T_a301a12e_54ca_11e6_9a6f_acb57da49b4frow2_col2" class="data row2 col2"&gt; 8 &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
1
2016-07-28T13:49:04Z
[ "python", "pandas" ]
format Date in pandas style render
38,638,025
<p>I have a pandas dataframe with three columns of which the first is the Date. To produce a html output I use this: </p> <pre><code>html_string = df.style.format({'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render() </code></pre> <p>how is it possible to specifiy the format of the Date as well...something like:</p> <pre><code>html_string = df.style.format({'Date': "%Y.%m",'second': "{:0,.0f}",third: "{:0,.0f}"}).set_table_styles(styles).render() </code></pre>
2
2016-07-28T13:33:43Z
38,638,708
<p>Actually it takes a string as argument...so this should work:</p> <pre><code>html_string = df.style.format({'Date': "{:%Y.%m}",'second': "{:0,.0f}",'third': "{:0,.0f}"}).set_table_styles(styles).render() </code></pre> <p>thanks though</p>
0
2016-07-28T14:00:41Z
[ "python", "pandas" ]
How do I multiply a map of a variable in Python?
38,638,054
<p>Here's my code:</p> <pre><code>elif cmd == "pay for dog": name = input("Dog name? ") for d in dogs: if d["name"] == name: print(d["name"] + " owes $" + d["days"]) </code></pre> <p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, how do I multiply d["days"] by 30?</p>
-2
2016-07-28T13:34:41Z
38,638,198
<p>You can use casting. Assuming <code>d["days"]</code> is a number, <code>print("$"+str(d["days"]*30))</code> will show you the amount to pay.</p>
0
2016-07-28T13:40:35Z
[ "python", "maps" ]
How do I multiply a map of a variable in Python?
38,638,054
<p>Here's my code:</p> <pre><code>elif cmd == "pay for dog": name = input("Dog name? ") for d in dogs: if d["name"] == name: print(d["name"] + " owes $" + d["days"]) </code></pre> <p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, how do I multiply d["days"] by 30?</p>
-2
2016-07-28T13:34:41Z
38,638,217
<p>If I unterstand you correctly, you want </p> <pre><code>print("%s owes $%.2f" % (d["name"], (30 * float(d["days"])))) </code></pre>
0
2016-07-28T13:41:15Z
[ "python", "maps" ]
How do I multiply a map of a variable in Python?
38,638,054
<p>Here's my code:</p> <pre><code>elif cmd == "pay for dog": name = input("Dog name? ") for d in dogs: if d["name"] == name: print(d["name"] + " owes $" + d["days"]) </code></pre> <p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, how do I multiply d["days"] by 30?</p>
-2
2016-07-28T13:34:41Z
38,638,682
<p>I think this would do the needful</p> <pre><code>for d in dogs: if d['name'] == name: print(d['name']+ " owes $" +str(int(d['day']) * 30)) </code></pre>
0
2016-07-28T14:00:04Z
[ "python", "maps" ]
How do I multiply a map of a variable in Python?
38,638,054
<p>Here's my code:</p> <pre><code>elif cmd == "pay for dog": name = input("Dog name? ") for d in dogs: if d["name"] == name: print(d["name"] + " owes $" + d["days"]) </code></pre> <p>How do I multiply d["days"] so that the person has to pay $30 each day? What I really mean is, how do I multiply d["days"] by 30?</p>
-2
2016-07-28T13:34:41Z
38,638,771
<p>As I see, <code>d["days"]</code> is string.</p> <p>Try this:</p> <pre><code>print(d["name"] + " owes $" + str(30 * int(d["days"]))) </code></pre> <p>or this:</p> <pre><code>print("%s owes $%d" % (d["name"], (30 * int(d["days"])))) </code></pre>
1
2016-07-28T14:03:16Z
[ "python", "maps" ]
over-plot dataframes with seaborn
38,638,107
<p>I have a few dataframes to plot, do I need to aggregate them before initializing something like JointGrid or can I access the axis ala matplotlib's ax.plot() style?</p>
-1
2016-07-28T13:36:40Z
38,638,336
<p>The interest of using Seaborn is that the axes generated are data-aware, i.e. it inspects the full dataset, and creates Facets and plot properties that are linked to the properties of your data. </p> <p>You could technically access each subplot and plot your individual dataframes in each of them, but you would lose the main interests of Seaborn : abilities to have common x and y axes across Facets, edit the legends and colors, etc. So I'd recommend concatenation of your Dataframes in a new one. </p> <p>Edit: The number of Facets created also depends on your data, so definitely aggregate them together. For instance, if your df1 has only two levels for the variable "Country", and you ask Seaborn to generate a FacetGrid with the argument column="Country", then you will only get two columns, which might be a issue if you have a third level of "Country" in your second DataFrame df2. </p>
1
2016-07-28T13:46:11Z
[ "python", "pandas", "matplotlib", "seaborn" ]
How to avoid printing unnecessary newline in python2?
38,638,109
<p>Here iam writing a code snippet <a href="http://ideone.com/cM10zZ" rel="nofollow">Code here</a>which takes some input and for each test case a particular operation has to be performed.Iam done with the job but here the actual output does not produce any newlines in between the test cases ,but my code is either putting newline or completly removing it.How to fix.</p> <h2>Actual output:</h2> <pre><code>y po i ntc </code></pre> <h2>My Output:</h2> <pre><code>y po i ntc </code></pre> <h2>Code:</h2> <pre><code># your code goes here import sys a = int(raw_input()) for _ in range(0 , a): str = raw_input() #print len(str) # print str[0] # sys.stdout.write(str[0]) for i in range( 0 , len(str)/2): # if( i % 2 == 1): if(i == 0): sys.stdout.write(str[i]) elif(i % 2 == 0 and i != 0): sys.stdout.write(str[i]) print('\n') </code></pre> <p>If i take away the last line print('\n'), it gives undesired output like</p> <pre><code>ypointc </code></pre>
-1
2016-07-28T13:36:47Z
38,638,316
<p>To be able to use the print function in a Python 2.x program, insert at the beginning of your module file this:</p> <pre><code>from __future__ import print_function </code></pre> <p>This "Python 3 updated" <code>print</code> to becomes a function, and it works much better that way.</p> <p>For the print function, just add a keyword <code>end</code> parameter to print, to indicate the string that will be printed at the end of the text:</p> <pre><code>print("my text here: ", variable1, variable2, end="") </code></pre> <p>With this import, even in Python 2, <code>print</code> becomes an ordinary function, and will require parentheses to work - but you can specificate not only the <code>end</code> string but also the separator between strings (parameter <code>sep</code>), and the file to print to (defaults to sys.stdout) (parameter <code>file</code>)(There is aloso the <code>flush</code> parameter indicating the file should be flushed after the printing. </p> <p>Also, in Python 2, you can simply put a comma (<code>,</code>) at the end of the print statement to switch the <code>end</code> to a space (<code></code>) instead of a newline. The use of print_functions os preferred, though. </p>
1
2016-07-28T13:45:17Z
[ "python", "python-2.7", "format", "newline" ]
How to avoid printing unnecessary newline in python2?
38,638,109
<p>Here iam writing a code snippet <a href="http://ideone.com/cM10zZ" rel="nofollow">Code here</a>which takes some input and for each test case a particular operation has to be performed.Iam done with the job but here the actual output does not produce any newlines in between the test cases ,but my code is either putting newline or completly removing it.How to fix.</p> <h2>Actual output:</h2> <pre><code>y po i ntc </code></pre> <h2>My Output:</h2> <pre><code>y po i ntc </code></pre> <h2>Code:</h2> <pre><code># your code goes here import sys a = int(raw_input()) for _ in range(0 , a): str = raw_input() #print len(str) # print str[0] # sys.stdout.write(str[0]) for i in range( 0 , len(str)/2): # if( i % 2 == 1): if(i == 0): sys.stdout.write(str[i]) elif(i % 2 == 0 and i != 0): sys.stdout.write(str[i]) print('\n') </code></pre> <p>If i take away the last line print('\n'), it gives undesired output like</p> <pre><code>ypointc </code></pre>
-1
2016-07-28T13:36:47Z
38,640,527
<p>Py2:</p> <pre><code>print '\n', </code></pre> <p>Py3:</p> <pre><code>print("\n", end="") </code></pre> <p>That's all.</p>
0
2016-07-28T15:20:03Z
[ "python", "python-2.7", "format", "newline" ]
How to avoid printing unnecessary newline in python2?
38,638,109
<p>Here iam writing a code snippet <a href="http://ideone.com/cM10zZ" rel="nofollow">Code here</a>which takes some input and for each test case a particular operation has to be performed.Iam done with the job but here the actual output does not produce any newlines in between the test cases ,but my code is either putting newline or completly removing it.How to fix.</p> <h2>Actual output:</h2> <pre><code>y po i ntc </code></pre> <h2>My Output:</h2> <pre><code>y po i ntc </code></pre> <h2>Code:</h2> <pre><code># your code goes here import sys a = int(raw_input()) for _ in range(0 , a): str = raw_input() #print len(str) # print str[0] # sys.stdout.write(str[0]) for i in range( 0 , len(str)/2): # if( i % 2 == 1): if(i == 0): sys.stdout.write(str[i]) elif(i % 2 == 0 and i != 0): sys.stdout.write(str[i]) print('\n') </code></pre> <p>If i take away the last line print('\n'), it gives undesired output like</p> <pre><code>ypointc </code></pre>
-1
2016-07-28T13:36:47Z
38,640,675
<p><code>print</code> will append <code>\n</code> automatically, so <code>print('\n')</code> will give two new lines. We just need print a blank string <code>print ''</code> to replace <code>print('\n')</code></p>
0
2016-07-28T15:26:47Z
[ "python", "python-2.7", "format", "newline" ]
How works is and id in python using integers above preallocated -5, 255 range
38,638,180
<p>Running interpretator</p> <pre><code>&gt;&gt;&gt; x = 5000 &gt;&gt;&gt; y = 5000 &gt;&gt;&gt; print(x is y) &gt;&gt;&gt; False </code></pre> <p>running the same in code using <code>python test.py</code> returns <code>True</code></p> <p>The heck?</p>
0
2016-07-28T13:39:40Z
38,638,392
<p>The <code>is</code> operator only returns <code>True</code> when the two operands reference the exact same object. Whether the interpreter chooses to create new values or re-use existing ones is an implementation detail. CPython (the most commonly used implementation) is clearly quite happy having several different integer objects that will compare equal, but not identical.</p> <p>Similarly there are no guarantees that the interpreter's behaviour will be the same as far as memory allocation and value creation are concerned. When running interactively quite a lot happens between the execution of successive statements. Running non-interactively none of that stuff (bind value of the expression to the <code>_</code> variable, print out the value followed by a prompt, etc.) needs to happen, and so it's easier for the interpreter to re-use a just-created value.</p>
0
2016-07-28T13:48:07Z
[ "python" ]
How works is and id in python using integers above preallocated -5, 255 range
38,638,180
<p>Running interpretator</p> <pre><code>&gt;&gt;&gt; x = 5000 &gt;&gt;&gt; y = 5000 &gt;&gt;&gt; print(x is y) &gt;&gt;&gt; False </code></pre> <p>running the same in code using <code>python test.py</code> returns <code>True</code></p> <p>The heck?</p>
0
2016-07-28T13:39:40Z
38,638,402
<p>Python allocates some numbers at start.</p> <pre><code>for x,y in zip(range(256,258),range(256,258)): print(x is y) x=y=5000 print(x is y) </code></pre> <p>This will print on my machine:</p> <pre><code>True False True </code></pre> <p>The first print is True because it was in the allocated range and both x and y refer to the same number. The False indicates that both x and y will create an integer object and these won't be the same. The last one is True because I specifically told Python to make x and y the same object. If you want to check equality, use <code>==</code> instead of <code>is</code>.</p>
0
2016-07-28T13:48:28Z
[ "python" ]
add one column (subtraction) to a dataframe with python
38,638,199
<p>I try to add one column in a dataframe df2 which contains the value 0 <code>if(df2['P_ACT_KW'] - df2['P_SOUSCR']) &lt; 0 else df2['P_ACT_KW']- df2['P_SOUSCR']</code>.</p> <pre><code>if (df2['P_ACT_KW'] - df2['P_SOUSCR']) &lt;0: df2['depassement']=0 else: df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSCR']) </code></pre> <p>I got this error message : </p> <blockquote> <p>ValueError Traceback (most recent call last) in () ----> 1 if (df2['P_ACT_KW'] - df2['P_SOUSCR']) &lt;0: 2 df2['depassement']=0 3 else: 4 df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSCR'])</p> <p>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py in <strong>nonzero</strong>(self) 890 raise ValueError("The truth value of a {0} is ambiguous. " 891 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." --> 892 .format(self.<strong>class</strong>.<strong>name</strong>)) 893 894 <strong>bool</strong> = <strong>nonzero</strong></p> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>Any idea please?</p> <p>Thank you</p>
1
2016-07-28T13:40:40Z
38,638,308
<p>You need to do:</p> <pre><code>df2['depassement'] = np.where((df2['P_ACT_KW'] - df2['P_SOUSCR']) &lt; 0), 0, df2['P_ACT_KW'] - df2['P_SOUSCR']) </code></pre> <p><code>if</code> doesn't understand how to compare array like structures hence the error, here we can use <code>np.where</code> to compare all rows to produce a mask and where the condition is true set to <code>0</code> else perform the subtraction</p>
0
2016-07-28T13:44:52Z
[ "python", "pandas", "dataframe", "calculated-columns" ]
add one column (subtraction) to a dataframe with python
38,638,199
<p>I try to add one column in a dataframe df2 which contains the value 0 <code>if(df2['P_ACT_KW'] - df2['P_SOUSCR']) &lt; 0 else df2['P_ACT_KW']- df2['P_SOUSCR']</code>.</p> <pre><code>if (df2['P_ACT_KW'] - df2['P_SOUSCR']) &lt;0: df2['depassement']=0 else: df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSCR']) </code></pre> <p>I got this error message : </p> <blockquote> <p>ValueError Traceback (most recent call last) in () ----> 1 if (df2['P_ACT_KW'] - df2['P_SOUSCR']) &lt;0: 2 df2['depassement']=0 3 else: 4 df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSCR'])</p> <p>C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py in <strong>nonzero</strong>(self) 890 raise ValueError("The truth value of a {0} is ambiguous. " 891 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." --> 892 .format(self.<strong>class</strong>.<strong>name</strong>)) 893 894 <strong>bool</strong> = <strong>nonzero</strong></p> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>Any idea please?</p> <p>Thank you</p>
1
2016-07-28T13:40:40Z
38,638,579
<p>IIUC:</p> <pre><code>df2['depassement'] = df2['P_ACT_KW'] - df2['P_SOUSCR'] df2[df2['depassement'] &lt; 0, 'depassement'] = 0 </code></pre> <p>This should also work:</p> <pre><code>df2['depassement'] = df2.P_ACT_KW.sub(df2.P_SOUSCR).apply(lambda x: max(x, 0)) </code></pre>
1
2016-07-28T13:55:35Z
[ "python", "pandas", "dataframe", "calculated-columns" ]
How to get full text even after clicking on link to expand text using selenium?
38,638,252
<p>I am trying to scrape reviews from tripadvisor website. Reviews which have longer text are shown partially with 'More' link. I have used selenium to hit 'More' link and it's working but I am again getting half reviews in my final output file. </p> <p>I figured out that full reviews are stored in different class but how can I access different class? </p> <p>Please see a part of my code below: </p> <pre><code>driver.get(full_url) driver.find_element_by_css_selector("span.moreLink").click() r = requests.get(full_url) soup = BeautifulSoup(r.content, "lxml") #soup = BeautifulSoup(source, 'html.parser') page_count = int(soup.select('.pagination a')[-1].text.strip()) page_results = soup.find_all("p", {"class" : "partial_entry"}) </code></pre>
-1
2016-07-28T13:42:56Z
38,638,427
<p>When you do <code>requests.get(full_url).content</code> you are getting the raw markup of the page. This has nothing to do with the state the <code>driver</code> is in (notice how the <code>get</code> call is neither passed the <code>driver</code> nor run <em>on</em> the <code>driver</code>). It's in a very real sense like opening a web site in Firefox and then running <code>curl</code> to get the content - the two have no idea about each other.</p> <p>What you need to do is ask <strong><code>driver</code></strong> what the markup is currently like, for example using <code>driver.find_element_by_css_selector("span").text</code>.</p>
0
2016-07-28T13:49:36Z
[ "python", "selenium", "web-scraping" ]
Python: process flow avoiding nested IF statements
38,638,292
<p>I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:</p> <pre><code>def run(self): status = False if step_1(): if step_2(): if step_3(): etc... [several nested IFs] status = True else: self.logger.error('Error in step 3') else: self.logger.error('Error in step 2') else: self.logger.error('Error in step 1') return status </code></pre> <p>Is there a more elegant way (a design pattern?) to avoid these nested IF statements?</p> <p>Thanks a lot,</p>
1
2016-07-28T13:44:15Z
38,638,440
<p>You would place your steps in a list:</p> <pre><code>my_plan = (step1, step2, step3, ..., stepN) </code></pre> <p>And then execute them in a loop:</p> <pre><code>for step in my_plan: if not step(): print 'Error in %s' % step.__name__ status = False break else: status = True </code></pre>
8
2016-07-28T13:49:58Z
[ "python", "python-2.7", "design-patterns" ]
Python: process flow avoiding nested IF statements
38,638,292
<p>I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:</p> <pre><code>def run(self): status = False if step_1(): if step_2(): if step_3(): etc... [several nested IFs] status = True else: self.logger.error('Error in step 3') else: self.logger.error('Error in step 2') else: self.logger.error('Error in step 1') return status </code></pre> <p>Is there a more elegant way (a design pattern?) to avoid these nested IF statements?</p> <p>Thanks a lot,</p>
1
2016-07-28T13:44:15Z
38,639,306
<p>Think of it as failing returning False instead of passing returning True.</p> <pre><code>def run(self): if not step_1(): self.logger.error('Error in step 1') return False if not step_2(): self.logger.error('Error in step 2') return False if not step_3(): self.logger.error('Error in step 3') return False return True </code></pre>
-2
2016-07-28T14:27:36Z
[ "python", "python-2.7", "design-patterns" ]
trying to log in and scrape a website through asp.net
38,638,319
<p>I have wrote a program with the aim of logging into one of my companies websites and then scraping data with aim of making data collection quicker. this is using requests and beautiful soup.</p> <p>I can get it to print out the html code for a page but I cant get it to log in past the aspx and then print the html on the page after.</p> <p>below is the code im using and my headers and params. any help would be appreciated</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import requests from bs4 import BeautifulSoup URL="http://mycompanywebsiteloginpage.co.uk/Login.aspx" headers={"User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0 Iceweasel/44.0.2"} username="myusername" password="mypassword" s=requests.Session() s.headers.update(headers) r=s.get(URL) soup=BeautifulSoup(r.content) VIEWSTATE=soup.find(id="__VIEWSTATE")['value'] EVENTVALIDATION=soup.find(id="__EVENTVALIDATION")['value'] EVENTTARGET=soup.find(id="__EVENTTARGET")['value'] EVENTARGUEMENT=soup.find(id="__EVENTARGUMENT")['value'] login_data={"__VIEWSTATE":VIEWSTATE, "ctl00$ContentPlaceHolder1$_tbEngineerUsername":username, "ctl00$ContentPlaceHolder1$_tbEngineerPassword":password, "ctl00$ContentPlaceHolder1$_tbSiteOwnerEmail":"", "ctl00$ContentPlaceHolder1$_tbSiteOwnerPassword":"", "ctl00$ContentPlaceHolder1$tbAdminName":username, "ctl00$ContentPlaceHolder1$tbAdminPassword":password, "__EVENTVALIDATION":EVENTVALIDATION, "__EVENTTARGET":EVENTTARGET, "--EVENTARGUEMENT":EVENTARGUEMENT} r = s.post(URL, data=login_data) r = requests.get("http://mycompanywebsitespageafterthelogin.co.uk/Secure/") print (r.url) print (r.text)</code></pre> </div> </div> </p> <p>FROM DATA</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>__VIEWSTATE:"DAwNEAIAAA4BBQAOAQ0QAgAADgEFAw4BDRACDwEBBm9ubG9hZAFkU2hvd1BhbmVsKCdjdGwwMF9Db250ZW50UGxhY2VIb2xkZXIxX19wbkFkbWluaXN0cmF0b3JzJywgZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ2FkbWluTG9naW5MaW5rJykpOwAOAQUBDgENEAIAAA4DBQEFBwULDgMNEAIMDwEBDUFsdGVybmF0ZVRleHQBDldEU0kgRGFzaGJvYXJkAAAAAA0QAgAADgIFAAUBDgINEAIPAQEEVGV4dAEEV0RTSQAAAA0QAgwPAQEHVmlzaWJsZQgAAAAADRACDwECBAABBFdEU2kAAAAAAABCX8QugS7ztoUJMfDmZ0s20ZNQfQ==" ctl00$ContentPlaceHolder1$_tbEngineerUsername:"myusername" ctl00$ContentPlaceHolder1$_tbEngineerPassword:"mypassword" ctl00$ContentPlaceHolder1$_tbSiteOwnerEmail:"" ctl00$ContentPlaceHolder1$_tbSiteOwnerPassword:"" ctl00$ContentPlaceHolder1$tbAdminName:"myusername" ctl00$ContentPlaceHolder1$tbAdminPassword:"mypassword" __EVENTVALIDATION:"HQABAAAA/////wEAAAAAAAAADwEAAAAKAAAACBzHEFXh+HCtf3vdl8crWr6QZnmaeK7pMzThEoU2hwqJxnlkQDX2XLkLAOuKEnW/qBMtNK2cdpQgNxoGtq65" __EVENTTARGET:"ctl00$ContentPlaceHolder1$_btAdminLogin" __EVENTARGUMENT:""</code></pre> </div> </div> </p> <p>REQUEST COOKIES</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>ASP.NET_SessionId:"11513CDDE31AF267CCD87BAB"</code></pre> </div> </div> </p> <p>RESPONSE HEADERS</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Cache-Control:"private" Connection:"Keep-Alive" Content-Length:"123" Content-Type:"text/html; charset=utf-8" Date:"Thu, 28 Jul 2016 13:37:45 GMT" Keep-Alive:"timeout=15, max=91" Location:"/Secure/" Server:"Apache/2.2.14 (Ubuntu)" x-aspnet-version:"2.0.50727"</code></pre> </div> </div> </p> <p>REQUEST HEADERS</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Host:"mycompanywebsite.co.uk" User-Agent:"Mozilla/5.0 (X11; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0 Iceweasel/44.0.2" Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" Accept-Language:"en-US,en;q=0.5" Accept-Encoding:"gzip, deflate" Referer:"http://mycompanywebsiteloginpage/Login.aspx" Cookie:"ASP.NET_SessionId=F11CB47B137ADB66D2274758" Connection:"keep-alive"</code></pre> </div> </div> </p>
-3
2016-07-28T13:45:23Z
38,638,503
<p>change the line </p> <pre><code>r = requests.get("http://mycompanywebsitespageafterthelogin.co.uk/Secure/") </code></pre> <p>to use your session object</p> <pre><code>r = s.get("http://mycompanywebsitespageafterthelogin.co.uk/Secure/") </code></pre>
1
2016-07-28T13:52:07Z
[ "python", "asp.net", "web-scraping", "beautifulsoup", "python-requests" ]
How do i write a mock configuration file in the setUp for my unittesting?
38,638,322
<p>I am trying to make my setUp-method create a mock configuration file, write a bunch of mock variables to it, and then use this file to instantiate the class (called Producer) i am running my tests on. </p> <pre><code>path_to_file =("/path/to/unit.Config") unitTest = open (path_to_file, 'w') unitTest.write("a string containing mock variables") prod = Producer("unit.Config") </code></pre> <p>The tests work if i manually create a file and fill it with data prior to running the tests, but doing it in setUp causes my program to crash ("Producer instance has no attribute 'LOGGER'). If i remove the 3 first lines of code the tests will run fine - so writing to the config file works.</p>
0
2016-07-28T13:45:32Z
38,638,600
<p>Perhaps if you closed the file before trying to read the configuration from it you might get better results.</p>
0
2016-07-28T13:56:16Z
[ "python", "unit-testing" ]
How do i write a mock configuration file in the setUp for my unittesting?
38,638,322
<p>I am trying to make my setUp-method create a mock configuration file, write a bunch of mock variables to it, and then use this file to instantiate the class (called Producer) i am running my tests on. </p> <pre><code>path_to_file =("/path/to/unit.Config") unitTest = open (path_to_file, 'w') unitTest.write("a string containing mock variables") prod = Producer("unit.Config") </code></pre> <p>The tests work if i manually create a file and fill it with data prior to running the tests, but doing it in setUp causes my program to crash ("Producer instance has no attribute 'LOGGER'). If i remove the 3 first lines of code the tests will run fine - so writing to the config file works.</p>
0
2016-07-28T13:45:32Z
38,638,640
<p>To guarantee that the content that you write to a file is actually available to any process reading the file you need to <code>close</code> the file handle after writing to it. The easiest way to remember to do this is to use a <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">context manager</a>:</p> <pre><code>with open(path_to_file, 'w') as file_pointer: file_pointer.write("content") # Outside the `with` the file content is available </code></pre>
1
2016-07-28T13:58:13Z
[ "python", "unit-testing" ]
Python - CodeAcademy Madlibs Exercise
38,638,429
<p>This code is for Code Academy's Madlibs exercise, which is supposed to take a number of inputs from the user and then print a very funny output.</p> <p>There is a story already provided in the site and I have not modified it.</p> <p>When I run the script, I am getting the following error:</p> <p>...........................................................................</p> <p>Traceback (most recent call l ast):<br> File "Madlibs.py", line 30, in <br> print "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." %(a1, name, v1, a2,n1, n2, Animal, Food, v2, n3,Fruit, a3, name, v3, Number,name, Superhero, Superhero, name, Country, name, Dessert,name, Year, n4) </p> <p>TypeError: not all arguments converted during string formatting<br> ...........................................................................</p> <p>The output also prints the "print" !!!</p> <p>Please note that in the story, there are some places where we have '%ss' instead of '%s'. Codeacademy wants the users to use '%ss' (I believe so)</p> <p>Also, I tried replacing the '%ss' with '%s' - I got the same error.</p> <p>Replaced all the '%s' and '%ss' with '%r' and '%rr' and got the same error.</p> <p>Replaced '%rr' with '%r' throughout and got the same error.</p> <p>One more thing I must mention, the code asks the user for all of the raw_input correctly, but fails to replace those in the story and prints the story with just %s or %r along with the error message.</p> <p>Can someone kindly help me out here. My code seems fine to me and I don't understand what's going on with the error message.</p> <p>Following is the code (Please bear with me for this repetitive piece)</p> <pre><code># This is a story for Mad Libs !!! print "Mad Lib is staritng now." name = raw_input ("What's your name ?") a1 = raw_input ("How are you feeling today ?") a2 = raw_input ("How is ther weather?") a3 = raw_input("Would you like your coffee hot or cold?") v1 = raw_input ("Would you rather jump, run or walk ?") v2 = raw_input ("Would you rather sing, dance or act ?") v3 = raw_input ("Would you rather eat, sleep or watch ?") n1 = raw_input ("In which city do you live ?") n2 = raw_input ("What is your favourite pet ?") n3 = raw_input ("Would you like to go to a mountain or a beach ?") n4 = raw_input ("DO you wnat to buy a dress or a shoe? ") Animal = raw_input ("Which animal do you like the most ?") Food = raw_input ("Enter your favourite food") Fruit = raw_input ("What's your favourite fruit ?") Number = raw_input ("Tell me a number: ") Superhero = raw_input ("Tell me the name of one Superhero") Country = raw_input ("Which country would you like to visit on your next vacation ?") Dessert = raw_input ("Which is your favourite dessert ?") Year = raw_input ("Which year were you born ?") print "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." %(a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, name, v3, Number, name, Superhero, Superhero, name, Country, name, Dessert, name, Year, n4) </code></pre>
1
2016-07-28T13:49:38Z
38,638,632
<p>You have many more arguments in your tuple (the (a1,name......) argument) than you have %s in your string. Make sure that each argument matches up with exactly 1 %s for the string formatting to work.</p>
0
2016-07-28T13:57:55Z
[ "python", "raw-input" ]
Python - CodeAcademy Madlibs Exercise
38,638,429
<p>This code is for Code Academy's Madlibs exercise, which is supposed to take a number of inputs from the user and then print a very funny output.</p> <p>There is a story already provided in the site and I have not modified it.</p> <p>When I run the script, I am getting the following error:</p> <p>...........................................................................</p> <p>Traceback (most recent call l ast):<br> File "Madlibs.py", line 30, in <br> print "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." %(a1, name, v1, a2,n1, n2, Animal, Food, v2, n3,Fruit, a3, name, v3, Number,name, Superhero, Superhero, name, Country, name, Dessert,name, Year, n4) </p> <p>TypeError: not all arguments converted during string formatting<br> ...........................................................................</p> <p>The output also prints the "print" !!!</p> <p>Please note that in the story, there are some places where we have '%ss' instead of '%s'. Codeacademy wants the users to use '%ss' (I believe so)</p> <p>Also, I tried replacing the '%ss' with '%s' - I got the same error.</p> <p>Replaced all the '%s' and '%ss' with '%r' and '%rr' and got the same error.</p> <p>Replaced '%rr' with '%r' throughout and got the same error.</p> <p>One more thing I must mention, the code asks the user for all of the raw_input correctly, but fails to replace those in the story and prints the story with just %s or %r along with the error message.</p> <p>Can someone kindly help me out here. My code seems fine to me and I don't understand what's going on with the error message.</p> <p>Following is the code (Please bear with me for this repetitive piece)</p> <pre><code># This is a story for Mad Libs !!! print "Mad Lib is staritng now." name = raw_input ("What's your name ?") a1 = raw_input ("How are you feeling today ?") a2 = raw_input ("How is ther weather?") a3 = raw_input("Would you like your coffee hot or cold?") v1 = raw_input ("Would you rather jump, run or walk ?") v2 = raw_input ("Would you rather sing, dance or act ?") v3 = raw_input ("Would you rather eat, sleep or watch ?") n1 = raw_input ("In which city do you live ?") n2 = raw_input ("What is your favourite pet ?") n3 = raw_input ("Would you like to go to a mountain or a beach ?") n4 = raw_input ("DO you wnat to buy a dress or a shoe? ") Animal = raw_input ("Which animal do you like the most ?") Food = raw_input ("Enter your favourite food") Fruit = raw_input ("What's your favourite fruit ?") Number = raw_input ("Tell me a number: ") Superhero = raw_input ("Tell me the name of one Superhero") Country = raw_input ("Which country would you like to visit on your next vacation ?") Dessert = raw_input ("Which is your favourite dessert ?") Year = raw_input ("Which year were you born ?") print "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." %(a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, name, v3, Number, name, Superhero, Superhero, name, Country, name, Dessert, name, Year, n4) </code></pre>
1
2016-07-28T13:49:38Z
38,638,655
<p>This <a href="https://discuss.codecademy.com/t/codeacademy-python-4-11-madlibs/39512/10" rel="nofollow">link</a> provides a solution. Read toward the bottom. It seems that you need to replace all the _ with %s. </p> <p>So for example instead of</p> <pre><code>print "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." %(a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, name, v3, Number, name, Superhero, Superhero, name, Country, name, Dessert, name, Year, n4) </code></pre> <p>It should be</p> <pre><code>print "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %s protesting to keep %s in stores. The crowd began to %s to the rythym of the %s, which made all of the %s very %s. %s tried to %s into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping %s into a puddle of %s. %s then fell asleep and woke up in the year %s, in a world where %s ruled the world." %(a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, name, v3, Number, name, Superhero, Superhero, name, Country, name, Dessert, name, Year, n4) </code></pre>
0
2016-07-28T13:58:40Z
[ "python", "raw-input" ]
pip freeze not showing packages
38,638,487
<p>For example if after installing Tornado with pip like this:</p> <pre><code>pip install tornado Collecting tornado ... Successfully installed backports-abc certifi singledispatch six tornado </code></pre> <p><code>pip freeze</code> doesn't return tornado package in list, it just shows:</p> <pre><code>PyMySQL==0.7.2 </code></pre> <p>also when I run <code>easy_install</code> it returns:</p> <pre><code>error: bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /lib/python2.7/site-packages/ and your PYTHONPATH environment variable currently contains: '' </code></pre> <p>What is going wrong?</p>
1
2016-07-28T13:51:27Z
38,640,526
<ol> <li><p>I suppose reinstalling pip may help you:</p> <pre><code>pip install --upgrade pip </code></pre></li> <li><p>To fix easy_install problem add <code>/lib/python2.7/site-packages/</code> to your PYTHONPATH:</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/lib/python2.7/site-packages/ </code></pre></li> </ol> <p><strong>Good Luck !</strong> </p>
0
2016-07-28T15:19:58Z
[ "python", "pip" ]
Beautiful Soup Tree Backward Navigation
38,638,519
<p><a href="http://i.stack.imgur.com/cKR4l.jpg" rel="nofollow">Shell screen shot</a></p> <p>Hello:</p> <p>I am a Python neophyte so apologies in advance if this question is too easy. I’ve been searching like crazy for an answer but cannot seem to find an example that is applicable to my case.</p> <p>In Python 3 running Beautiful Soup, I am trying set my html tree reference as a specific href and then scrape the 6 preceding numerical values from the url below.</p> <pre><code>url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm' </code></pre> <p>My reason for starting from the <code>href</code> tag is that it is the only reference in the html which stays the same and is not repeated again.</p> <p>In my example, I would like to start at the <code>href</code> tag: </p> <pre><code>href="./hist/LeafHandler.ashx?n=PET&amp;amp;s=W_EPOOXE_YIR_NUS_MBBLD&amp;amp;f=W" </code></pre> <p>Then scape the individual contents from the six <code>"td=class"</code> tags preceding that tag:</p> <pre><code>936, 934, 919,957, 951, 928. </code></pre> <p>Thanks in advance for any help.</p>
1
2016-07-28T13:52:41Z
38,641,174
<p>The format of the file is a number of tables, the one you are interested in being the second. Since you know the value of the <code>href</code> attribute you want to match on, one way to access the parts you need would be to iterate over the table rows, first of all checking in the <code>href</code> value is the one you want.</p>
0
2016-07-28T15:49:26Z
[ "python", "html", "beautifulsoup" ]
Beautiful Soup Tree Backward Navigation
38,638,519
<p><a href="http://i.stack.imgur.com/cKR4l.jpg" rel="nofollow">Shell screen shot</a></p> <p>Hello:</p> <p>I am a Python neophyte so apologies in advance if this question is too easy. I’ve been searching like crazy for an answer but cannot seem to find an example that is applicable to my case.</p> <p>In Python 3 running Beautiful Soup, I am trying set my html tree reference as a specific href and then scrape the 6 preceding numerical values from the url below.</p> <pre><code>url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm' </code></pre> <p>My reason for starting from the <code>href</code> tag is that it is the only reference in the html which stays the same and is not repeated again.</p> <p>In my example, I would like to start at the <code>href</code> tag: </p> <pre><code>href="./hist/LeafHandler.ashx?n=PET&amp;amp;s=W_EPOOXE_YIR_NUS_MBBLD&amp;amp;f=W" </code></pre> <p>Then scape the individual contents from the six <code>"td=class"</code> tags preceding that tag:</p> <pre><code>936, 934, 919,957, 951, 928. </code></pre> <p>Thanks in advance for any help.</p>
1
2016-07-28T13:52:41Z
38,644,885
<p>First select the anchor using the <em>href</em>, then find the six previous td's:</p> <pre><code>from bs4 import BeautifulSoup import requests url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm' soup = BeautifulSoup(requests.get(url).content,"html.parser") anchor = soup.select_one("a[href=./hist/LeafHandler.ashx?n=PET&amp;s=W_EPOOXE_YIR_NUS_MBBLD&amp;f=W]") data = [td.text for td in anchor.find_all_previous("td","DataB", limit=6)] </code></pre> <p>If we run the code, you can see we get text from the previous six td's:</p> <pre><code>In [1]: from bs4 import BeautifulSoup ...: import requests ...: url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm' ...: soup = BeautifulSoup(requests.get(url).content,"html.parser") ...: anchor = soup.select_one("a[href=./hist/LeafHandler.ashx?n=PET&amp;s=W_EPOOX ...: E_YIR_NUS_MBBLD&amp;f=W]") ...: data = [td.text for td in anchor.find_all_previous("td","DataB", limit=6 ...: )] ...: In [2]: data Out[2]: ['934', '919', '957', '951', '928', '139'] </code></pre> <p>That does not quite get there as there as there are two different classes for the td's <em>Current2</em> and <em>DataB</em> sdo we can use the parent of the anchor which will be a td itself:</p> <pre><code>In [5]: from bs4 import BeautifulSoup ...: import requests ...: url = 'http://www.eia.gov/dnav/pet/pet_sum_sndw_dcus_nus_w.htm' ...: soup = BeautifulSoup(requests.get(url).content,"html.parser") ...: anchor_td = soup.find("a", href="./hist/LeafHandler.ashx?n=PET&amp;s=W_EPOOXE_Y ...: IR_NUS_MBBLD&amp;f=W").parent ...: data = [td.text for td in anchor_td.find_all_previous("td", limit=6)] ...: In [6]: data Out[6]: ['936', '934', '919', '957', '951', '928'] </code></pre> <p>Now we get exactly what we want.</p> <p>Lastly we could get the <em>grandparent</em> of the <em>anchor</em> i.e the main <em>td</em> then use a select using the the both the class names in our <em>select</em>:</p> <pre><code>href = "./hist/LeafHandler.ashx?n=PET&amp;s=W_EPOOXE_YIR_NUS_MBBLD&amp;f=W" grandparent = soup.find("a", href=href).parent.parent data = [td.text for td in grandparent.select("td.Current2,td.DataB")] </code></pre> <p>Again data gives us the same output.</p>
0
2016-07-28T19:11:34Z
[ "python", "html", "beautifulsoup" ]
unable to import win32com.client
38,638,552
<p>I am trying to import win32com.client library gives me the following error:</p> <pre><code>&gt;&gt;&gt; import win32com.client Traceback (most recent call last): File "&lt;pyshell#57&gt;", line 1, in &lt;module&gt; import win32com.client File "C:\Python27\lib\site-packages\win32com\__init__.py", line 5, in &lt;module&gt; import win32api, sys, os ImportError: No module named win32api &gt;&gt;&gt; </code></pre> <p>Basically i am trying to send email using win32com.client . Kindly help.</p>
0
2016-07-28T13:54:16Z
38,638,742
<p>Did you install the <a href="http://python.net/crew/skippy/win32/Downloads.html" rel="nofollow">Win32 Extensions for Python</a>? Make sure you pick the correct installer for your system and version of Python otherwise it may not work correctly.</p>
0
2016-07-28T14:01:53Z
[ "python", "python-2.7", "winapi" ]
filtering dataframe on multiple conditions
38,638,565
<pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'], 'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV', 'CRV'], 'amount': [5, 5, 8, 6, 1, 5, 10, 6, 12, 11], 'id': [10, 10, 11, 11, 11, 10, 10, 11, 11, 10]} stores = pd.DataFrame(data, columns=['retailer_name', 'store_number', 'year', 'amount', 'id']) stores.set_index(['retailer_name', 'store_number', 'year'], inplace=True) stores_grouped = stores.groupby(level=[0, 1, 2]) </code></pre> <p>That looks like:</p> <pre><code> amount id retailer_name store_number year Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 CRV 1946 11:24:19 8 11 1948 11:25:19 6 11 11:25:19 1 11 Walmart 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1948 11:23:19 6 11 1949 11:23:19 12 11 1947 11:23:19 11 10 </code></pre> <p>I manage to filter on: <code>stores_grouped.filter(lambda x: (len(x) == 1))</code></p> <p>But when I want to filter on two conditions:</p> <p>That my group has length one and id column is equals 10. Any idea ho do so ?</p>
5
2016-07-28T13:54:49Z
38,638,624
<p>Actually as <code>filter</code> expects a scalar <code>bool</code> you can just add the condition in the <code>lambda</code> like a normal <code>if</code> style statement:</p> <pre><code>In [180]: stores_grouped.filter(lambda x: (len(x) == 1 and x['id'] == 10)) ​ Out[180]: amount id retailer_name store_number year Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1947 11:23:19 11 10 </code></pre>
3
2016-07-28T13:57:21Z
[ "python", "pandas", "dataframe" ]
filtering dataframe on multiple conditions
38,638,565
<pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'], 'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV', 'CRV'], 'amount': [5, 5, 8, 6, 1, 5, 10, 6, 12, 11], 'id': [10, 10, 11, 11, 11, 10, 10, 11, 11, 10]} stores = pd.DataFrame(data, columns=['retailer_name', 'store_number', 'year', 'amount', 'id']) stores.set_index(['retailer_name', 'store_number', 'year'], inplace=True) stores_grouped = stores.groupby(level=[0, 1, 2]) </code></pre> <p>That looks like:</p> <pre><code> amount id retailer_name store_number year Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 CRV 1946 11:24:19 8 11 1948 11:25:19 6 11 11:25:19 1 11 Walmart 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1948 11:23:19 6 11 1949 11:23:19 12 11 1947 11:23:19 11 10 </code></pre> <p>I manage to filter on: <code>stores_grouped.filter(lambda x: (len(x) == 1))</code></p> <p>But when I want to filter on two conditions:</p> <p>That my group has length one and id column is equals 10. Any idea ho do so ?</p>
5
2016-07-28T13:54:49Z
38,638,626
<p>i'd do it this way:</p> <pre><code>In [348]: stores_grouped.filter(lambda x: (len(x) == 1)).query('id == 10') Out[348]: amount id retailer_name store_number year Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1947 11:23:19 11 10 </code></pre>
1
2016-07-28T13:57:34Z
[ "python", "pandas", "dataframe" ]
filtering dataframe on multiple conditions
38,638,565
<pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'], 'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV', 'CRV'], 'amount': [5, 5, 8, 6, 1, 5, 10, 6, 12, 11], 'id': [10, 10, 11, 11, 11, 10, 10, 11, 11, 10]} stores = pd.DataFrame(data, columns=['retailer_name', 'store_number', 'year', 'amount', 'id']) stores.set_index(['retailer_name', 'store_number', 'year'], inplace=True) stores_grouped = stores.groupby(level=[0, 1, 2]) </code></pre> <p>That looks like:</p> <pre><code> amount id retailer_name store_number year Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 CRV 1946 11:24:19 8 11 1948 11:25:19 6 11 11:25:19 1 11 Walmart 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1948 11:23:19 6 11 1949 11:23:19 12 11 1947 11:23:19 11 10 </code></pre> <p>I manage to filter on: <code>stores_grouped.filter(lambda x: (len(x) == 1))</code></p> <p>But when I want to filter on two conditions:</p> <p>That my group has length one and id column is equals 10. Any idea ho do so ?</p>
5
2016-07-28T13:54:49Z
38,638,630
<p>You can use:</p> <pre><code>print (stores_grouped.filter(lambda x: (len(x) == 1) &amp; (x.id == 10).all())) amount id retailer_name store_number year Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1947 11:23:19 11 10 </code></pre>
3
2016-07-28T13:57:54Z
[ "python", "pandas", "dataframe" ]
filtering dataframe on multiple conditions
38,638,565
<pre><code>data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'], 'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV', 'CRV'], 'amount': [5, 5, 8, 6, 1, 5, 10, 6, 12, 11], 'id': [10, 10, 11, 11, 11, 10, 10, 11, 11, 10]} stores = pd.DataFrame(data, columns=['retailer_name', 'store_number', 'year', 'amount', 'id']) stores.set_index(['retailer_name', 'store_number', 'year'], inplace=True) stores_grouped = stores.groupby(level=[0, 1, 2]) </code></pre> <p>That looks like:</p> <pre><code> amount id retailer_name store_number year Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 CRV 1946 11:24:19 8 11 1948 11:25:19 6 11 11:25:19 1 11 Walmart 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1948 11:23:19 6 11 1949 11:23:19 12 11 1947 11:23:19 11 10 </code></pre> <p>I manage to filter on: <code>stores_grouped.filter(lambda x: (len(x) == 1))</code></p> <p>But when I want to filter on two conditions:</p> <p>That my group has length one and id column is equals 10. Any idea ho do so ?</p>
5
2016-07-28T13:54:49Z
38,638,932
<p>Thinking outside the box, use <code>drop_duplicates</code> with <code>keep=False</code>:</p> <pre><code>df.drop_duplicates(subset=['retailer_name', 'store_number', 'year'], keep=False) \ .query('id == 10') </code></pre> <p><a href="http://i.stack.imgur.com/6hBn5.png" rel="nofollow"><img src="http://i.stack.imgur.com/6hBn5.png" alt="enter image description here"></a></p> <hr> <h3>Timing</h3> <p><a href="http://i.stack.imgur.com/Jrxgw.png" rel="nofollow"><img src="http://i.stack.imgur.com/Jrxgw.png" alt="enter image description here"></a></p>
2
2016-07-28T14:10:30Z
[ "python", "pandas", "dataframe" ]
Python - Parameter checking with Exception Raising
38,638,642
<p>I am attempting to write exception raising code blocks into my Python code in order to ensure that the parameters passed to the function meet appropriate conditions (i.e. making parameters mandatory, type-checking parameters, establishing boundary values for parameters, etc...). I understand satisfactorily how to <a href="http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python">manually raise exceptions</a> as well as <a href="http://stackoverflow.com/questions/4428250/handling-exceptions-in-python">handling them</a>.</p> <pre><code>from numbers import Number def foo(self, param1 = None, param2 = 0.0, param3 = 1.0): if (param1 == None): raise ValueError('This parameter is mandatory') elif (not isinstance(param2, Number)): raise ValueError('This parameter must be a valid Numerical value') elif (param3 &lt;= 0.0): raise ValueError('This parameter must be a Positive Number') ... </code></pre> <p>This is an acceptable (tried and true) way of parameter checking in Python, but I have to wonder: Since Python does not have a way of writing Switch-cases besides if-then-else statements, is there a more efficient or proper way to perform this task? Or is implementing long stretches of if-then-else statements my only option?</p>
5
2016-07-28T13:58:18Z
38,639,156
<p>You could create a decorator function and pass the expected types and (optional) ranges as parameters. Something like this:</p> <pre><code>def typecheck(types, ranges=None): def __f(f): def _f(*args, **kwargs): for a, t in zip(args, types): if not isinstance(a, t): raise ValueError("Expected %s got %r" % (t, a)) for a, r in zip(args, ranges or []): if r and not r[0] &lt;= a &lt;= r[1]: raise ValueError("Should be in range %r: %r" % (r, a)) return f(*args, **kwargs) return _f return __f </code></pre> <p>Instead of <code>if ...: raise</code> you could also invert the conditions and use <code>assert</code>, but as <a href="http://stackoverflow.com/questions/38638642/python-parameter-checking-with-exception-raising/38639156#comment64661781_38638642">noted in comments</a> those might not always be executed. You could also extend this to allow e.g. open ranges (like <code>(0., None)</code>) or to accept arbitrary (<code>lambda</code>) functions for more specific checks.</p> <p>Example:</p> <pre><code>@typecheck(types=[int, float, str], ranges=[None, (0.0, 1.0), ("a", "f")]) def foo(x, y, z): print("called foo with ", x, y, z) foo(10, .5, "b") # called foo with 10 0.5 b foo([1,2,3], .5, "b") # ValueError: Expected &lt;class 'int'&gt;, got [1, 2, 3] foo(1, 2.,"e") # ValueError: Should be in range (0.0, 1.0): 2.0 </code></pre>
2
2016-07-28T14:19:43Z
[ "python", "if-statement", "exception", "typechecking" ]
Python - Parameter checking with Exception Raising
38,638,642
<p>I am attempting to write exception raising code blocks into my Python code in order to ensure that the parameters passed to the function meet appropriate conditions (i.e. making parameters mandatory, type-checking parameters, establishing boundary values for parameters, etc...). I understand satisfactorily how to <a href="http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python">manually raise exceptions</a> as well as <a href="http://stackoverflow.com/questions/4428250/handling-exceptions-in-python">handling them</a>.</p> <pre><code>from numbers import Number def foo(self, param1 = None, param2 = 0.0, param3 = 1.0): if (param1 == None): raise ValueError('This parameter is mandatory') elif (not isinstance(param2, Number)): raise ValueError('This parameter must be a valid Numerical value') elif (param3 &lt;= 0.0): raise ValueError('This parameter must be a Positive Number') ... </code></pre> <p>This is an acceptable (tried and true) way of parameter checking in Python, but I have to wonder: Since Python does not have a way of writing Switch-cases besides if-then-else statements, is there a more efficient or proper way to perform this task? Or is implementing long stretches of if-then-else statements my only option?</p>
5
2016-07-28T13:58:18Z
38,639,246
<p>I think you can use decorator to check the parameters.</p> <pre><code>def parameterChecker(input,output): ... def wrapper(f): ... assert len(input) == f.func_code.co_argcount ... def newfun(*args, **kwds): ... for (a, t) in zip(args, input): ... assert isinstance(a, t), "arg {} need to match {}".format(a,t) ... res = f(*args, **kwds) ... if not isinstance(res,collections.Iterable): ... res = [res] ... for (r, t) in zip(res, output): ... assert isinstance(r, t), "output {} need to match {}".format(r,t) ... return f(*args, **kwds) ... newfun.func_name = f.func_name ... return newfun ... return wrapper example: @parameterChecker((int,int),(int,)) ... def func(arg1, arg2): ... return '1' func(1,2) AssertionError: output 1 need to match &lt;type 'int'&gt; func(1,'e') AssertionError: arg e need to match &lt;type 'int'&gt; </code></pre>
1
2016-07-28T14:24:35Z
[ "python", "if-statement", "exception", "typechecking" ]
How to mock object attributes and complex fields and methods?
38,638,744
<p>I have a following function which needs to be unit tested.</p> <pre><code>def read_all_fields(all_fields_sheet): entries = [] for row_index in xrange(2, all_fields_sheet.nrows): d = {'size' : all_fields_sheet.cell(row_index,0).value,\ 'type' : all_fields_sheet.cell(row_index,1).value,\ 'hotslide' : all_fields_sheet.cell(row_index,3).value} entries.append((all_fields_sheet.cell(row_index,2).value,d)) return entries </code></pre> <p>Now, my all_fields_sheet is a sheet returned by xlrd module(Used to read Excel file).</p> <p>So, basically I need to mock for following attributes nrows cell</p> <p>How should I go abput it?</p>
0
2016-07-28T14:02:02Z
38,639,015
<p>Just mock the calls and attributes directly on a mock object; adjust to cover your test needs:</p> <pre><code>mock_sheet = MagicMock() mock_sheet.nrows = 3 # loop once cells = [ MagicMock(value=42), # row_index, 0 MagicMock(value='foo'), # row_index, 1 MagicMock(value='bar'), # row_index, 3 MagicMock(value='spam'), # row_index, 2 ] mock_sheet.cell.side_effect = cells </code></pre> <p>By assigning a list to <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect" rel="nofollow"><code>Mock.side_effect</code></a> you can control, in order, what calls to <code>.cell()</code> return.</p> <p>Afterwards, you can test if the right calls have been made with the various assertion methods. You could use the <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.call" rel="nofollow"><code>mock.call()</code> object</a> to give precise expectations:</p> <pre><code>result = read_all_fields(mock_sheet) self.assertEqual( result, [('spam', {'size': 42, 'type': 'foo', 'hotslide': 'bar'})] ) self.assertEqual( mock_sheet.cell.call_args_list, [call(2, 0), call(2, 1), call(2, 3), call(2, 2)]) </code></pre> <p>I used <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args_list" rel="nofollow"><code>Mock.call_args_list</code></a> here to match an exact number of calls, directly to <code>mock_sheet.cell</code> alone.</p> <p>Demo, assuming that your <code>read_all_fields()</code> function is already defined:</p> <pre><code>&gt;&gt;&gt; from unittest.mock import MagicMock, call &gt;&gt;&gt; mock_sheet = MagicMock() &gt;&gt;&gt; mock_sheet.nrows = 3 # loop once &gt;&gt;&gt; cells = [ ... MagicMock(value=42), # row_index, 0 ... MagicMock(value='foo'), # row_index, 1 ... MagicMock(value='bar'), # row_index, 3 ... MagicMock(value='spam'), # row_index, 2 ... ] &gt;&gt;&gt; mock_sheet.cell.side_effect = cells &gt;&gt;&gt; result = read_all_fields(mock_sheet) &gt;&gt;&gt; result == [('spam', {'size': 42, 'type': 'foo', 'hotslide': 'bar'})] True &gt;&gt;&gt; mock_sheet.cell.call_args_list == [call(2, 0), call(2, 1), call(2, 3), call(2, 2)] True </code></pre> <p>Alternatively, you could create a function for the <code>mock_sheet.cell.side_effect</code> attribute, to return values from a 'sheet' you set up up front:</p> <pre><code>cells = [[42, 'foo', 'spam', 'bar']] # 1 row def mock_cells(row, cell): return MagicMock(value=cells[row - 2][cell]) mock_sheet.cell.side_effect = mock_cells </code></pre> <p>When <code>side_effect</code> is a function, it is called whenever <code>mock_sheet.cell()</code> is called, with the same arguments.</p>
1
2016-07-28T14:13:58Z
[ "python", "python-2.7", "unit-testing", "mocking" ]
python console closes before it starts
38,639,095
<p>I am learning Python and came across this problem. I know that i can put "input()" at the bottom of the program, but the problem is that it IS there, but console terminates nevertheless. It seems like the programm never starts at all. I am using the 3.5 version of Python.</p>
-3
2016-07-28T14:16:53Z
38,639,192
<p>Open a terminal, navigate to the directory of your file, and type <code>python myfile.py</code>. If you just double click the file in your system explorer it will run and close when it finishes, which is often too fast to see what's going on.</p>
-1
2016-07-28T14:21:30Z
[ "python", "console" ]
python console closes before it starts
38,639,095
<p>I am learning Python and came across this problem. I know that i can put "input()" at the bottom of the program, but the problem is that it IS there, but console terminates nevertheless. It seems like the programm never starts at all. I am using the 3.5 version of Python.</p>
-3
2016-07-28T14:16:53Z
38,639,194
<p>I think you are starting the programme by clicking on it don't do that to run your programme follow following steps</p> <p>1.open command prompt 2. go to the path where you have your python programme 3. use command for python for eg: python programme.py in linux 4. if it says python command not recognised probably because the path to python executable is not present in system path add it to environment variable and that should work fine</p>
-1
2016-07-28T14:21:35Z
[ "python", "console" ]
How to validate data based on conditions
38,639,175
<pre><code>a = int(input("Enter mark of BIOLOGY: ")) b = int(input("Enter mark of CHEMISTRY: ")) c = int(input("Enter mark of PHYSICS: ")) sum = a + b + c x = sum y = 3 avg = x / y print("Total marks = ", sum) print("Average marks = ", avg) </code></pre> <p>I want to limit the user's input so it only accepts integers from 0 to 90.</p>
-1
2016-07-28T14:20:35Z
38,639,296
<p>If you are wanting to limit the sum variable, at the end of your code you could simply put an if statement checking that the variable is within the boundary..</p> <pre><code>if sum &gt; 90: sum = 90 elif sum &lt; 0: sum = 0 </code></pre>
0
2016-07-28T14:27:17Z
[ "python", "python-2.7", "python-3.x" ]
How to validate data based on conditions
38,639,175
<pre><code>a = int(input("Enter mark of BIOLOGY: ")) b = int(input("Enter mark of CHEMISTRY: ")) c = int(input("Enter mark of PHYSICS: ")) sum = a + b + c x = sum y = 3 avg = x / y print("Total marks = ", sum) print("Average marks = ", avg) </code></pre> <p>I want to limit the user's input so it only accepts integers from 0 to 90.</p>
-1
2016-07-28T14:20:35Z
38,639,300
<p>To limit the user's input to 0 to 90, you will need to repeatedly ask the user to re-input the data until it meets the 0 to 90 criteria. You can do that by implementing a <code>while</code> loop and then <code>break</code> if the criteria is met. Here's the code:</p> <pre><code># Data validation for the variable "a" while True: a = int(input("Enter mark of BIOLOGY: ")) if 0 &lt;= a &lt;= 90: break else: print("The mark is not between 0 and 90. Please enter a new mark.") </code></pre> <p>Hope this helped.</p>
1
2016-07-28T14:27:19Z
[ "python", "python-2.7", "python-3.x" ]
How to validate data based on conditions
38,639,175
<pre><code>a = int(input("Enter mark of BIOLOGY: ")) b = int(input("Enter mark of CHEMISTRY: ")) c = int(input("Enter mark of PHYSICS: ")) sum = a + b + c x = sum y = 3 avg = x / y print("Total marks = ", sum) print("Average marks = ", avg) </code></pre> <p>I want to limit the user's input so it only accepts integers from 0 to 90.</p>
-1
2016-07-28T14:20:35Z
38,639,426
<p>The following code will ensure that the user inputs the number in the specified range:</p> <pre><code>while True: a = int(input("enter mark of BIOLOGY = ")) if 0 &lt;= a &lt;= 90: break else: print("Invalid mark. Please try again.") while True: b = int(input("enter mark of CHEMISTRY = ")) if 0 &lt;= b &lt;= 90: break else: print("Invalid mark. Please try again.") while True: c = int(input("enter mark of PHYSICS = ")) if 0 &lt;= c &lt;= 90: break else: print("Invalid mark. Please try again.") sum = a + b + c x = sum y = 3 avg = x / y print("total marks = ", sum) print("average marks = ", avg) </code></pre> <p>This will ensure the variables <code>a</code>, <code>b</code>, and <code>c</code> are between 0-90.</p>
0
2016-07-28T14:33:52Z
[ "python", "python-2.7", "python-3.x" ]
Python : IndexError: list index out of range
38,639,217
<p>I'm relatively new to python. I was getting this error when I tried implementing the following code. I don't understand the error. </p> <pre><code>def coinChange(S,m,n): dp = [[0 for x in range(m)] for x in range(n+1)] for i in range(m): dp[0][i] = 1 for i in range(1,n+1): for j in range(m): if i &gt;= S[j]: dp[i][j] = dp[i-1][j] + dp[i][i-S[j]] else: dp[i][j] = dp[i-1][j] return dp[i][j] S = [1,3,5] m = len(S) n = 11 print(coinChange(S,m,n)) This is the error I'm getting: Traceback (most recent call last): File "C:\Users\SaiV\CoinChange.py", line 24, in &lt;module&gt; print(coinChange(S,m,n)) File "C:\Users\SaiV\CoinChange.py", line 13, in coinChange dp[i][j] = dp[i-1][j] + dp[i][i-S[j]] IndexError: list index out of range </code></pre>
-7
2016-07-28T14:22:44Z
38,639,283
<p>The error means you have tried to retrieve the value of an index in a list (as in <code>my_list[index]</code>) which <strong>does not exist.</strong> This is assumed to be a fatal error by sensible languages, and as such the program terminates immediately. Read the rest of the exception message to get a better idea of where the issue is.</p>
0
2016-07-28T14:26:38Z
[ "python" ]
How to read files in the directory using glob pattern in python?
38,639,254
<p>I want read files in one directory. </p> <p><strong>Directory contains :</strong> </p> <pre><code>ABC1.csv ABC1_1.csv ABC1_2.csv ABC11.csv ABC11_1.csv ABC11_3.csv ABC11_2.csv ABC13_4.csv ABC13_1.csv ABC17_6.csv ABC17_2.csv ABC17_4.csv ABC17_8.csv </code></pre> <p>While running script I want to give command line argument for reading specific files depend on some conditions :</p> <ol> <li>If user give only ABC error message.</li> <li>If user give ABC1 then it must read ABC1.csv, ABC1_1.csv and ABC1_2.csv only.</li> <li>If user give ABC11 then it must read ABC11.csv,ABC11_1.csv,ABC11_2.csv,ABC11_3.csv only.</li> <li>If user give ABC13 it must read ABC13_1.csv,ABC13_4.csv only.</li> <li>If user give ABC17 then it must read ABC17_2.csv,ABC17_4.csv,ABC17_6.csv,ABC17_8.csv only.</li> </ol> <p>For this stuff I'm created a script but I'm facing issue.</p> <p><strong>Program-</strong></p> <pre><code>from glob import glob import os import sys file_pattern = '' files_list = list() arguments = {'ABC', 'PQR', 'XYZ'} if len(sys.argv[1:2]) is 1: file_pattern = str(sys.argv[1:2]) else: print 'run as &lt;python test.py ABC&gt;' sys.exit(1) if file_pattern in arguments: print '&lt;Provide Name with some Number&gt;' sys.exit(1) file_pattern = file_pattern.replace('[','').replace(']','').replace('\'','') if file_pattern.startswith('ABC',0,3): files_list = glob(os.path.join('&lt;directory name&gt;', str(file_pattern)+'_*.csv')) else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name&gt;' sys.exit(1) if files_list: for a_file in sorted(files_list): print a_file #process file else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name&gt;' sys.exit(1) </code></pre> <p>This code is working fine but it doesn't satisfy my 2nd condition. when user is giving ABC1 as a argument i.e. python test.py ABC1 , it will return files ABC1_1.csv, ABC1_2.csv but not returning ABC1.csv file.</p> <p>How I can satisfy this 2nd condition also without losing any other condition?</p>
0
2016-07-28T14:25:11Z
38,640,450
<p>I have a solution. It's not perfect, depends if you have other files in the folder:</p> <pre><code>file_pattern = 'ABC1' files_list = glob(os.path.join('&lt;directory name&gt;', str(file_pattern)+'[!0-9]*')) # output: ABC1.csv, ABC1_1.csv, ABC1_2.csv file_pattern = 'ABC11' files_list = glob(os.path.join('&lt;directory name&gt;', str(file_pattern)+'[!0-9]*')) # output: ['.\\ABC11.csv', '.\\ABC11_1.csv', '.\\ABC11_2.csv', '.\\ABC11_3.csv'] </code></pre> <p>I had the same problem as Jesper. The issue is that although * will match any character, it needs <em>a</em> character!</p> <p>By selecting any file that doesn't have a digit after the file pattern, we avoid the 1-11 issue.</p>
0
2016-07-28T15:17:10Z
[ "python", "file", "directory", "glob" ]
How to read files in the directory using glob pattern in python?
38,639,254
<p>I want read files in one directory. </p> <p><strong>Directory contains :</strong> </p> <pre><code>ABC1.csv ABC1_1.csv ABC1_2.csv ABC11.csv ABC11_1.csv ABC11_3.csv ABC11_2.csv ABC13_4.csv ABC13_1.csv ABC17_6.csv ABC17_2.csv ABC17_4.csv ABC17_8.csv </code></pre> <p>While running script I want to give command line argument for reading specific files depend on some conditions :</p> <ol> <li>If user give only ABC error message.</li> <li>If user give ABC1 then it must read ABC1.csv, ABC1_1.csv and ABC1_2.csv only.</li> <li>If user give ABC11 then it must read ABC11.csv,ABC11_1.csv,ABC11_2.csv,ABC11_3.csv only.</li> <li>If user give ABC13 it must read ABC13_1.csv,ABC13_4.csv only.</li> <li>If user give ABC17 then it must read ABC17_2.csv,ABC17_4.csv,ABC17_6.csv,ABC17_8.csv only.</li> </ol> <p>For this stuff I'm created a script but I'm facing issue.</p> <p><strong>Program-</strong></p> <pre><code>from glob import glob import os import sys file_pattern = '' files_list = list() arguments = {'ABC', 'PQR', 'XYZ'} if len(sys.argv[1:2]) is 1: file_pattern = str(sys.argv[1:2]) else: print 'run as &lt;python test.py ABC&gt;' sys.exit(1) if file_pattern in arguments: print '&lt;Provide Name with some Number&gt;' sys.exit(1) file_pattern = file_pattern.replace('[','').replace(']','').replace('\'','') if file_pattern.startswith('ABC',0,3): files_list = glob(os.path.join('&lt;directory name&gt;', str(file_pattern)+'_*.csv')) else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name&gt;' sys.exit(1) if files_list: for a_file in sorted(files_list): print a_file #process file else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name&gt;' sys.exit(1) </code></pre> <p>This code is working fine but it doesn't satisfy my 2nd condition. when user is giving ABC1 as a argument i.e. python test.py ABC1 , it will return files ABC1_1.csv, ABC1_2.csv but not returning ABC1.csv file.</p> <p>How I can satisfy this 2nd condition also without losing any other condition?</p>
0
2016-07-28T14:25:11Z
38,651,789
<p>I tried with different Scenarios,and finally got exact solution which satisfies all my conditions. First I'm checking for user input file is available or not in the specified directory, If it is available then globing all files with same file with (_) all at the end appending match file to same list. </p> <p>If user input if not file is not available in the specified directory then I'm checking for the files with (_) symbol then globing all files into list. At the end iterating through list and got final result.</p> <p><strong>Program-</strong> </p> <pre><code>from glob import glob import os import sys file_pattern = '' files_list = list() arguments = {'ABC', 'PQR', 'XYZ'} #checking for user provided argument or not if len(sys.argv[1:2]) is 1: file_pattern = str(sys.argv[1:2]) else: print 'run as &lt; python test.py &lt;LineName&gt; &gt;' sys.exit(1) #replace all unnecessary stuff with ('') file_pattern = file_pattern.replace('[','').replace(']','').replace('\'','') #checking for line number is provided or not if file_pattern in arguments: print '&lt;Provide LineName with some Number&gt;' sys.exit(1) flag = True #list of all files containing specified directory files = os.listdir('&lt;directory name&gt;') for file_name in files: if str(file_name) == str(file_pattern)+'.csv': files_list = glob(os.path.join('&lt;directory name&gt;', str(file_pattern)+'_*.csv')) #appending match file also to resultant list files_list.append('&lt;directory name&gt;'+file_name) flag = False #if specified file is not present in dir check for filename with (_) if flag: files_list = glob(os.path.join('&lt;directory name&gt;', str(file_pattern)+'_*.csv')) #checking for list contains items or not if files_list: for a_file in sorted(files_list): print a_file else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name1&gt;' sys.exit(1) </code></pre> <p>Consider directory contains ABC1.csv, ABC1_1.csv, ABC1_2.csv, ABC11.csv, ABC11_1.csv, ABC11_3.csv, ABC11_2.csv files.</p> <p><strong>Output Scenario :</strong> </p> <pre><code>#if input is ABC1 .\\ABC1.csv .\\ABC1_1.csv .\\ABC1_2.csv #if input is ABC11 .\\ABC11.csv .\\ABC11_1.csv .\\ABC11_2.csv .\\ABC11_3.csv </code></pre>
1
2016-07-29T06:19:58Z
[ "python", "file", "directory", "glob" ]
How to read files in the directory using glob pattern in python?
38,639,254
<p>I want read files in one directory. </p> <p><strong>Directory contains :</strong> </p> <pre><code>ABC1.csv ABC1_1.csv ABC1_2.csv ABC11.csv ABC11_1.csv ABC11_3.csv ABC11_2.csv ABC13_4.csv ABC13_1.csv ABC17_6.csv ABC17_2.csv ABC17_4.csv ABC17_8.csv </code></pre> <p>While running script I want to give command line argument for reading specific files depend on some conditions :</p> <ol> <li>If user give only ABC error message.</li> <li>If user give ABC1 then it must read ABC1.csv, ABC1_1.csv and ABC1_2.csv only.</li> <li>If user give ABC11 then it must read ABC11.csv,ABC11_1.csv,ABC11_2.csv,ABC11_3.csv only.</li> <li>If user give ABC13 it must read ABC13_1.csv,ABC13_4.csv only.</li> <li>If user give ABC17 then it must read ABC17_2.csv,ABC17_4.csv,ABC17_6.csv,ABC17_8.csv only.</li> </ol> <p>For this stuff I'm created a script but I'm facing issue.</p> <p><strong>Program-</strong></p> <pre><code>from glob import glob import os import sys file_pattern = '' files_list = list() arguments = {'ABC', 'PQR', 'XYZ'} if len(sys.argv[1:2]) is 1: file_pattern = str(sys.argv[1:2]) else: print 'run as &lt;python test.py ABC&gt;' sys.exit(1) if file_pattern in arguments: print '&lt;Provide Name with some Number&gt;' sys.exit(1) file_pattern = file_pattern.replace('[','').replace(']','').replace('\'','') if file_pattern.startswith('ABC',0,3): files_list = glob(os.path.join('&lt;directory name&gt;', str(file_pattern)+'_*.csv')) else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name&gt;' sys.exit(1) if files_list: for a_file in sorted(files_list): print a_file #process file else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name&gt;' sys.exit(1) </code></pre> <p>This code is working fine but it doesn't satisfy my 2nd condition. when user is giving ABC1 as a argument i.e. python test.py ABC1 , it will return files ABC1_1.csv, ABC1_2.csv but not returning ABC1.csv file.</p> <p>How I can satisfy this 2nd condition also without losing any other condition?</p>
0
2016-07-28T14:25:11Z
38,651,863
<p>You might want to add a simple check for the additional "special" case, something like this:</p> <pre><code>if file_pattern.startswith('ABC',0,3): csv_path = os.path.join('.', str(file_pattern)) files_list = glob(csv_path + '_*.csv') # Just check the special case that's not included in the glob above csv_path = csv_path + '.csv' if os.path.isfile(csv_path): files_list.append(csv_path) else: print 'No Such File --&gt; ' + str(file_pattern)+ '\t &lt;Provide appropriate Name&gt;' sys.exit(1) </code></pre>
0
2016-07-29T06:25:00Z
[ "python", "file", "directory", "glob" ]
How can I stop my program from generating the same key?
38,639,395
<p>I writing a password generator and I ran into this annoying issue, and it is the repeating a a number or letter on the same line. The user gives the program a format on how they want their password to be generated ex "C@@d%%%" where @ is only letters and where % is only numbers, and the user also inputs the numbers and letters to generate the password, then the program is suppose to print out something like cold123, but instead it prints out cood111 or clld111, I will post a snippet of my code below, but please don't bad mouth it, I'm fairly new to python, self-taught and just about couple of months into the python experience. </p> <pre><code>class G() . . . # self.forms is the format the user input they can input things such as C@@d%%% # where @ is only letters and where % is only numbers # self.Bank is a list where generated things go AlphaB = [] #list Of All Of The Positions That have The @ sign in The self.forms NumB = [] #list of All of the positions that have a % sign for char in self.forms: if char == '@': EOL=(self.Position) # Positions End Of Line Loc = self.forms[EOL] # Letter AlphaB.append(EOL) if char == '%': EOL=(self.Position) Loc = self.forms[EOL] NumB.append(EOL) self.Position+=1 # Move right a position for pos in AlphaB: for letter in self.alphas: #letters in The User Inputs GenPass=(self.forms.replace(self.forms[pos],letter)) #Not Fully Formatted yet, because Only The letter been formatted if GenPass.find('%'): for Pos in NumB: for number in self.ints: GenPass=(GenPass.replace(GenPass[Pos],number)) if GenPass not in self.Bank: #Cood111 print (GenPass) self.Bank.append(GenPass) else: if GenPass not in self.Bank: print (GenPass) self.Bank.append(GenPass) </code></pre>
1
2016-07-28T14:32:19Z
38,639,640
<p><code>GenPass.replace(GenPass[Pos],number)</code> will replace <em>every</em> occurrence of the character at <code>GenPass[Pos]</code> with the value of <code>number</code>. You need to make sure you replace one character at a time.</p>
0
2016-07-28T14:42:05Z
[ "python", "passwords", "generator" ]