title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python Flask wt forms ventilator check if password is matching database
39,506,137
<p>I am trying to create a from where before updating records the user must type in their password for validation.</p> <p>I was thinking of useing something like this.</p> <pre><code>class AccountSettingsForm(Form): password_proof= TextField("Password:",[validators.EqualTo(current_user.password, message='Passwords Invlaid')]) </code></pre> <p>But i get this error<br> AttributeError: 'NoneType' object has no attribute 'password'</p>
-1
2016-09-15T08:13:51Z
39,506,421
<p>You need to create a validator method with the syntax <code>validate_{field_name}</code>. Also, as you are using other data (the user instance, which contains their password), you need to initialize the form with that user instance.</p> <p>Something like this should work for your example:</p> <pre><code>from wtforms import ValidationError class AccountSettingsForm(Form): password_proof= TextField("Password:") def __init__(self, user, *args, **kwargs): super(AccountSettingsForm, self).__init__(*args, **kwargs) self.user = user def validate_password_proof(self, field): if field.data != self.user.password: raise ValidationError('Wrong password.') </code></pre> <p>Then, when initializing the form, you need to do it like this:</p> <pre><code>form = AccountSettingsForm(current_user) </code></pre> <p>On an unrelated side note, you should encrypt your users' passwords if you are not doing so.</p>
1
2016-09-15T08:29:51Z
[ "python", "flask", "flask-sqlalchemy", "flask-wtforms", "flask-security" ]
pandas drop_duplicates using comparison function
39,506,438
<p>Is it somehow possible to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a> with a comparison operator which compares two objects in a particular column in order to identify duplicates? If not, what is the alternative?</p> <p>Here is an example where it could be used:</p> <p>I have a pandas DataFrame which has lists as values in a particular column and I would like to have duplicates removed based on column <code>A</code></p> <pre><code>import pandas as pd df = pd.DataFrame( {'A': [[1,2],[2,3],[1,2]]} ) print df </code></pre> <p>giving me</p> <pre><code> A 0 [1, 2] 1 [2, 3] 2 [1, 2] </code></pre> <p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a></p> <pre><code>df.drop_duplicates( 'A' ) </code></pre> <p>gives me a <code>TypeError</code></p> <pre><code>[...] TypeError: type object argument after * must be a sequence, not itertools.imap </code></pre> <p>However, my desired result is</p> <pre><code> A 0 [1, 2] 1 [2, 3] </code></pre> <p>My comparison function would be here:</p> <pre><code>def cmp(x,y): return x==y </code></pre> <p>But in principle it could be something else, e.g.,</p> <pre><code>def cmp(x,y): return x==y and len(x)&gt;1 </code></pre> <p>How can I remove duplicates based on the comparison function in a efficient way?</p> <p>Even more, what could I do if I had more columns to compare using a different comparison function, respectively?</p>
3
2016-09-15T08:31:04Z
39,506,753
<p><strong><em>Option 1</em></strong></p> <pre><code>df[~pd.DataFrame(df.A.values.tolist()).duplicated()] </code></pre> <p><a href="http://i.stack.imgur.com/pQ4BD.png" rel="nofollow"><img src="http://i.stack.imgur.com/pQ4BD.png" alt="enter image description here"></a></p> <p><strong><em>Option 2</em></strong></p> <pre><code>df[~df.A.apply(pd.Series).duplicated()] </code></pre>
3
2016-09-15T08:49:26Z
[ "python", "pandas" ]
pandas drop_duplicates using comparison function
39,506,438
<p>Is it somehow possible to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a> with a comparison operator which compares two objects in a particular column in order to identify duplicates? If not, what is the alternative?</p> <p>Here is an example where it could be used:</p> <p>I have a pandas DataFrame which has lists as values in a particular column and I would like to have duplicates removed based on column <code>A</code></p> <pre><code>import pandas as pd df = pd.DataFrame( {'A': [[1,2],[2,3],[1,2]]} ) print df </code></pre> <p>giving me</p> <pre><code> A 0 [1, 2] 1 [2, 3] 2 [1, 2] </code></pre> <p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a></p> <pre><code>df.drop_duplicates( 'A' ) </code></pre> <p>gives me a <code>TypeError</code></p> <pre><code>[...] TypeError: type object argument after * must be a sequence, not itertools.imap </code></pre> <p>However, my desired result is</p> <pre><code> A 0 [1, 2] 1 [2, 3] </code></pre> <p>My comparison function would be here:</p> <pre><code>def cmp(x,y): return x==y </code></pre> <p>But in principle it could be something else, e.g.,</p> <pre><code>def cmp(x,y): return x==y and len(x)&gt;1 </code></pre> <p>How can I remove duplicates based on the comparison function in a efficient way?</p> <p>Even more, what could I do if I had more columns to compare using a different comparison function, respectively?</p>
3
2016-09-15T08:31:04Z
39,506,999
<p>IIUC, your question is how to use an <em>arbitrary</em> function to determine what is a duplicate. To emphasize this, let's say that two lists are duplicates if the sum of the first item, plus the square of the second item, is the same in each case</p> <pre><code>In [59]: In [118]: df = pd.DataFrame( {'A': [[1,2],[4,1],[2,3]]} ) </code></pre> <p>(Note that the first and second lists are equivalent, although not same.)</p> <p>Python typically <a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">prefers key functions to comparison functions</a>, so here we need a function to say what is the key of a list; in this case, it is <code>lambda l: l[0] + l[1]**2</code>.</p> <p>We can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>groupby</code> + <code>first</code></a> to group by the values of the key function, then take the first of each group:</p> <pre><code>In [119]: df.groupby(df.A.apply(lambda l: l[0] + l[1]**2)).first() Out[119]: A A 5 [1, 2] 11 [2, 3] </code></pre> <hr> <p><strong>Edit</strong></p> <p>Following further edits in the question, here are a few more examples using</p> <pre><code>df = pd.DataFrame( {'A': [[1,2],[2,3],[1,2], [1], [1], [2]]} ) </code></pre> <p>Then for</p> <pre><code>def cmp(x,y): return x==y </code></pre> <p>this could be</p> <pre><code>In [158]: df.groupby(df.A.apply(tuple)).first() Out[158]: A A (1,) [1] (1, 2) [1, 2] (2,) [2] (2, 3) [2, 3] </code></pre> <p>for</p> <pre><code>def cmp(x,y): return x==y and len(x)&gt;1 </code></pre> <p>this could be </p> <pre><code>In [184]: class Key(object): .....: def __init__(self): .....: self._c = 0 .....: def __call__(self, l): .....: if len(l) &lt; 2: .....: self._c += 1 .....: return self._c .....: return tuple(l) .....: In [187]: df.groupby(df.A.apply(Key())).first() Out[187]: A A 1 [1] 2 [1] 3 [2] (1, 2) [1, 2] (2, 3) [2, 3] </code></pre> <p>Alternatively, this could also be done much more succinctly via</p> <pre><code>In [190]: df.groupby(df.A.apply(lambda l: np.random.rand() if len(l) &lt; 2 else tuple(l))).first() Out[190]: A A 0.112012068449 [2] 0.822889598152 [1] 0.842630848774 [1] (1, 2) [1, 2] (2, 3) [2, 3] </code></pre> <p>but some people don't like these Monte-Carlo things.</p>
3
2016-09-15T09:01:47Z
[ "python", "pandas" ]
pandas drop_duplicates using comparison function
39,506,438
<p>Is it somehow possible to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a> with a comparison operator which compares two objects in a particular column in order to identify duplicates? If not, what is the alternative?</p> <p>Here is an example where it could be used:</p> <p>I have a pandas DataFrame which has lists as values in a particular column and I would like to have duplicates removed based on column <code>A</code></p> <pre><code>import pandas as pd df = pd.DataFrame( {'A': [[1,2],[2,3],[1,2]]} ) print df </code></pre> <p>giving me</p> <pre><code> A 0 [1, 2] 1 [2, 3] 2 [1, 2] </code></pre> <p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a></p> <pre><code>df.drop_duplicates( 'A' ) </code></pre> <p>gives me a <code>TypeError</code></p> <pre><code>[...] TypeError: type object argument after * must be a sequence, not itertools.imap </code></pre> <p>However, my desired result is</p> <pre><code> A 0 [1, 2] 1 [2, 3] </code></pre> <p>My comparison function would be here:</p> <pre><code>def cmp(x,y): return x==y </code></pre> <p>But in principle it could be something else, e.g.,</p> <pre><code>def cmp(x,y): return x==y and len(x)&gt;1 </code></pre> <p>How can I remove duplicates based on the comparison function in a efficient way?</p> <p>Even more, what could I do if I had more columns to compare using a different comparison function, respectively?</p>
3
2016-09-15T08:31:04Z
39,507,103
<p><code>Lists</code> are unhashable in nature. Try converting them to hashable types such as <code>tuples</code> and then you can continue to use <code>drop_duplicates</code>:</p> <pre><code>df['A'] = df['A'].map(tuple) df.drop_duplicates('A').applymap(list) </code></pre> <p><a href="http://i.stack.imgur.com/Ge4NF.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ge4NF.png" alt="Image"></a></p> <hr> <p>One way of implementing it using a function would be based on computing <code>value_counts</code> of the series object, as duplicated values get aggregated and we are interested in only the <code>index</code> part (which by the way is unique) and not the actual count part.</p> <pre><code>def series_dups(col_name): ser = df[col_name].map(tuple).value_counts(sort=False) return (pd.Series(data=ser.index.values, name=col_name)).map(list) series_dups('A') 0 [1, 2] 1 [2, 3] Name: A, dtype: object </code></pre> <hr> <p>If you do not want to convert the values to <code>tuple</code> but rather process the values as they are, you could do:</p> <p><strong>Toy data:</strong></p> <pre><code>df = pd.DataFrame({'A': [[1,2], [2,3], [1,2], [3,4]], 'B': [[10,11,12], [11,12], [11,12,13], [10,11,12]]}) df </code></pre> <p><a href="http://i.stack.imgur.com/Al7FS.png" rel="nofollow"><img src="http://i.stack.imgur.com/Al7FS.png" alt="Image"></a></p> <pre><code>def series_dups_hashable(frame, col_names): for col in col_names: ser, indx = np.unique(frame[col].values, return_index=True) frame[col] = pd.Series(data=ser, index=indx, name=col) return frame.dropna(how='all') series_dups_hashable(df, ['A', 'B']) # Apply to subset/all columns you want to check </code></pre> <p><a href="http://i.stack.imgur.com/MTzqn.png" rel="nofollow"><img src="http://i.stack.imgur.com/MTzqn.png" alt="Image"></a></p>
3
2016-09-15T09:06:42Z
[ "python", "pandas" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!") print("You've just gone bananas!") </code></pre> <p>For functions with one input i use:</p> <pre><code>def test_some_function(self): codefile.input = lambda x: 'u' codefile.some_function() . . . . </code></pre> <p>And then:</p> <pre><code>def teardown_method(self, method): codefile.input = input </code></pre> <p>To revert inputs back.</p> <p>But here it won't work. Help!</p>
2
2016-09-15T08:39:18Z
39,507,214
<p>What you want is to simulate the user inputs.</p> <p>You have to use a <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow"><strong>unittest.mock</strong></a> and patch the <code>input</code> function.</p> <p>See the <a href="https://docs.python.org/3/library/unittest.mock.html#quick-guide" rel="nofollow">Quick Guide</a>.</p>
0
2016-09-15T09:13:08Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!") print("You've just gone bananas!") </code></pre> <p>For functions with one input i use:</p> <pre><code>def test_some_function(self): codefile.input = lambda x: 'u' codefile.some_function() . . . . </code></pre> <p>And then:</p> <pre><code>def teardown_method(self, method): codefile.input = input </code></pre> <p>To revert inputs back.</p> <p>But here it won't work. Help!</p>
2
2016-09-15T08:39:18Z
39,507,282
<p>Here is my solution:</p> <pre><code>class SimulatedInput: def __init__(self,*args): self.args = iter(args) def __call__(self,x): try: return next(self.args) except StopIteration: raise Exception("No more input") </code></pre> <p>Then you could use it like you did before:</p> <pre><code>def test_some_function(self): codefile.input = SimulatedInput("u","v") codefile.some_function() . . . . </code></pre>
0
2016-09-15T09:16:53Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!") print("You've just gone bananas!") </code></pre> <p>For functions with one input i use:</p> <pre><code>def test_some_function(self): codefile.input = lambda x: 'u' codefile.some_function() . . . . </code></pre> <p>And then:</p> <pre><code>def teardown_method(self, method): codefile.input = input </code></pre> <p>To revert inputs back.</p> <p>But here it won't work. Help!</p>
2
2016-09-15T08:39:18Z
39,507,428
<p>A minimalistic example with no dependencies. Play with it to extend it as you wish:</p> <pre><code>import sys import io def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!") print("You've just gone bananas!") def wrapper(): lines = ["go", "bananas"] def fake_input(*args, **kwargs): return lines.pop(0) global input real_input = input input = fake_input two_answers() input = real_input wrapper() </code></pre>
-1
2016-09-15T09:23:15Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!") print("You've just gone bananas!") </code></pre> <p>For functions with one input i use:</p> <pre><code>def test_some_function(self): codefile.input = lambda x: 'u' codefile.some_function() . . . . </code></pre> <p>And then:</p> <pre><code>def teardown_method(self, method): codefile.input = input </code></pre> <p>To revert inputs back.</p> <p>But here it won't work. Help!</p>
2
2016-09-15T08:39:18Z
39,537,628
<p>I would wrap the input in to a function.</p> <pre><code>def input_wrap(prompt): return input(prompt) </code></pre> <p>Then you can inject it.</p> <pre><code>def two_answers(input_func): if input_func('...') != 'go': return two_answers(input_func) ... </code></pre> <p>Now when you want to test it you can inject a fake or a mock:</p> <pre><code>def test_two_answers(self): fake_input = mock.MagicMock() fake_input.side_effect = ['go', 'foo', 'bananas'] two_answers(fake_input) # no assertion for needed since there's no return value </code></pre> <p>Later in the code that executes two_answers you call it like this:</p> <pre><code>two_answers(input_wrap) </code></pre>
0
2016-09-16T18:05:11Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to get match result by given range using regular expression?
39,506,578
<p>I'm stucking with my code to get all return match by given range. My data sample is:</p> <pre><code> comment 0 [intj74, you're, whipping, people, is, a, grea... 1 [home, near, kcil2, meniaga, who, intj47, a, l... 2 [thematic, budget, kasi, smooth, sweep] 3 [budget, 2, intj69, most, people, think, of, e... </code></pre> <p>I want to get the result as: (where the given range is intj1 to intj75)</p> <pre><code> comment 0 [intj74] 1 [intj47] 2 [nan] 3 [intj69] </code></pre> <p>My code is:</p> <pre><code>df.comment = df.comment.apply(lambda x: [t for t in x if t=='intj74']) df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]] </code></pre> <p>I'm not sure how to use regular expression to find the range for t=='range'. Or any other idea to do this?</p> <p>Thanks in advance,</p> <p>Pandas Python Newbie</p>
1
2016-09-15T08:39:36Z
39,506,752
<p>you could replace <code>[t for t in x if t=='intj74']</code> with, e.g.,</p> <pre><code>[t for t in x if re.match('intj[0-9]+$', t)] </code></pre> <p>or even</p> <pre><code>[t for t in x if re.match('intj[0-9]+$', t)] or [np.nan] </code></pre> <p>which would also handle the case if there are no matches (so that one wouldn't need to check for that explicitly using <code>df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]]</code>) The "trick" here is that an empty list evaluates to <code>False</code> so that the <code>or</code> in that case returns its right operand.</p>
1
2016-09-15T08:49:26Z
[ "python", "pandas" ]
How to get match result by given range using regular expression?
39,506,578
<p>I'm stucking with my code to get all return match by given range. My data sample is:</p> <pre><code> comment 0 [intj74, you're, whipping, people, is, a, grea... 1 [home, near, kcil2, meniaga, who, intj47, a, l... 2 [thematic, budget, kasi, smooth, sweep] 3 [budget, 2, intj69, most, people, think, of, e... </code></pre> <p>I want to get the result as: (where the given range is intj1 to intj75)</p> <pre><code> comment 0 [intj74] 1 [intj47] 2 [nan] 3 [intj69] </code></pre> <p>My code is:</p> <pre><code>df.comment = df.comment.apply(lambda x: [t for t in x if t=='intj74']) df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]] </code></pre> <p>I'm not sure how to use regular expression to find the range for t=='range'. Or any other idea to do this?</p> <p>Thanks in advance,</p> <p>Pandas Python Newbie</p>
1
2016-09-15T08:39:36Z
39,506,867
<p>I am new to <code>pandas</code> as well. You might have initialized your DataFrame differently. Anyway, this is what I have:</p> <pre><code>import pandas as pd data = { 'comment': [ "intj74, you're, whipping, people, is, a", "home, near, kcil2, meniaga, who, intj47, a", "thematic, budget, kasi, smooth, sweep", "budget, 2, intj69, most, people, think, of" ] } print(df.comment.str.extract(r'(intj\d+)')) </code></pre>
0
2016-09-15T08:55:00Z
[ "python", "pandas" ]
Django 1.10 full text search by UUIDField returns DataError
39,506,717
<p>I have the following model:</p> <pre><code>class Show(models.Model): cid = models.UUIDField( default=uuid.uuid4, editable=False, verbose_name="Content ID", help_text="Unique Identifier" ) title_short = models.CharField( max_length=60, blank=True, verbose_name="Short Title", help_text="Short title (60 chars)" ) </code></pre> <p>I'm using the below snippet</p> <pre><code>from django.contrib.postgres.search import SearchVector Entry.objects.annotate( search=SearchVector('cid'), ).filter(search='wateva') </code></pre> <p>Returns:</p> <pre><code>DataError at /meta/shows/ invalid input syntax for uuid: "" LINE 1: ...unt", to_tsvector(COALESCE("entities_show"."cid", '')) AS "s... </code></pre> <p>I tried with PostgreSQL 9.3.14 and PostgreSQL 9.5.3, Python 3.4.3</p> <p>Has anyone encountered this issue ?</p>
0
2016-09-15T08:47:29Z
39,507,224
<p>You may want to file a bug-report.</p> <p>The Django code creates a COALESCE() statement, assuming that the final fallback value of an empty string (<code>''</code>) is acceptable for fields given. I don't see a way to specify the fallback value through the official API, and since UUID fields are translated to Postgres Native <a href="https://www.postgresql.org/docs/9.4/static/datatype-uuid.html" rel="nofollow">UUID</a> fields, the empty string is an invalid value for that field.</p> <p>If you decide to file a report, please add a comment here with the ticket ID, I might pitch in fixing it as I have a vested interest in this feature.</p>
0
2016-09-15T09:13:30Z
[ "python", "django", "postgresql", "full-text-search", "uuid" ]
See stacktrace of hanging Python in futex(..., FUTEX_WAIT_BITSET_PRIVATE|...)
39,506,737
<p>A Python process hangs in futex():</p> <pre><code>root@pc:~# strace -p 9042 strace: Process 9042 attached futex(0x1e61900, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 0, NULL, ffffffff </code></pre> <p>I want to see the stacktrace if the hanging process.</p> <p>Unfortunately ctrl-c does not work :-(</p> <p>How can I see the stacktrace if Python hangs like this?</p>
3
2016-09-15T08:48:22Z
39,507,648
<ol> <li>install the gdb python extensions if needed for your system (see <a href="https://wiki.python.org/moin/DebuggingWithGdb" rel="nofollow">here</a> for example, or look at your distro documentation)</li> <li>attach gdb to your hung process</li> <li><p>run</p> <pre><code>(gdb) py-bt </code></pre> <p>instead of regular <code>bt</code> to get the Python backtrace</p></li> </ol>
3
2016-09-15T09:32:45Z
[ "python", "debugging", "hang", "futex" ]
PyQt display 1 widget in 2 layouts?
39,506,856
<p>I'd like to add QLineEdit/checkbox/button in 2 layouts. So no matter which one I press in which ever window they both do the same thing, update each other as I type and so on.</p> <p>Is it possible or do I need to create second set of controls and then signal link each other?</p> <p>Regards Dariusz</p>
1
2016-09-15T08:54:37Z
39,506,951
<p>A widget can only exist in one place at a time. You will need to link the two unfortunately. Do yourself a favor and do it properly via a model.</p> <p>If it were possible for a widget to exist in multiple places, this would lead to a whole lot of problems: cyclic trees, multiple parents, etc.</p>
1
2016-09-15T08:59:14Z
[ "python", "pyqt", "pyqt4" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacement from this list M samples.</p></li> <li><p>If M &lt;= N, then simply use Numpy's random.choice without replacement. </p></li> <li><p>If M > N, then the samples must consist X times all the N numbers in the list, where X is the number of times N fully divides M, i.e. X = floor(M/N) and then sample additional M-(X*N) remainder samples from the list without replacement. </p></li> </ul> <p>For example, let my list be the following: </p> <blockquote> <p>L = [1, 2, 3, 4, 5]</p> </blockquote> <p>and I need to sample 8 samples. Then firstly, I sample the full list once and additional 3 elements randomly without replacement, e.g. my samples could then be: </p> <blockquote> <p>Sampled_list = [1, 2, 3, 4, 5, 3, 5, 1]</p> </blockquote> <p>How can I implement such a code as efficiently as possible in terms of computation time in Python? Can this be done without for-loops? </p> <p>At the moment I'm implementing this using for-loops but this is too inefficient for my purposes. I have also tried Numpy's random.choice without replacement but then I need to have M &lt;= N. </p> <p>Thank you for any help! </p>
2
2016-09-15T09:07:18Z
39,507,484
<p>I would just wrap numpy's <code>random.choice()</code> like so:</p> <pre><code>L = [1, 2, 3, 4, 5] def wrap_choice(list_to_sample, no_samples): list_size = len(list_to_sample) takes = no_samples // list_size samples = list_to_sample * (no_samples // list_size) + list(np.random.choice(list_to_sample, no_samples - takes * list_size)) return samples print(wrap_choice(L, 2)) # [5, 1] print(wrap_choice(L, 13)) # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3, 3, 1] </code></pre> <p>Edit: There is no need to check for the length. The algorithm you have for when the requests are more than the list's length also works when this is not the case.</p>
2
2016-09-15T09:25:56Z
[ "python", "numpy", "sampling" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacement from this list M samples.</p></li> <li><p>If M &lt;= N, then simply use Numpy's random.choice without replacement. </p></li> <li><p>If M > N, then the samples must consist X times all the N numbers in the list, where X is the number of times N fully divides M, i.e. X = floor(M/N) and then sample additional M-(X*N) remainder samples from the list without replacement. </p></li> </ul> <p>For example, let my list be the following: </p> <blockquote> <p>L = [1, 2, 3, 4, 5]</p> </blockquote> <p>and I need to sample 8 samples. Then firstly, I sample the full list once and additional 3 elements randomly without replacement, e.g. my samples could then be: </p> <blockquote> <p>Sampled_list = [1, 2, 3, 4, 5, 3, 5, 1]</p> </blockquote> <p>How can I implement such a code as efficiently as possible in terms of computation time in Python? Can this be done without for-loops? </p> <p>At the moment I'm implementing this using for-loops but this is too inefficient for my purposes. I have also tried Numpy's random.choice without replacement but then I need to have M &lt;= N. </p> <p>Thank you for any help! </p>
2
2016-09-15T09:07:18Z
39,507,620
<p>You can <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>concatenate</code></a> the results of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>repeat</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html#numpy.random.choice" rel="nofollow"><code>random.choice</code></a>:</p> <pre><code>np.concatenate((np.repeat(L, M // len(L)), np.random.choice(L, M - M // len(L)))) </code></pre> <p>First, the sequence is repeated as often as necessary, then a choice is made for the remaining number needed; finally, the two arrays are concatenated.</p> <p>Note that you can easily determine whether <code>choice</code> works with replacement or without, using the <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow"><code>replace</code> parameter</a>:</p> <blockquote> <p><strong>replace</strong> : boolean, optional -- Whether the sample is with or without replacement</p> </blockquote>
3
2016-09-15T09:31:38Z
[ "python", "numpy", "sampling" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacement from this list M samples.</p></li> <li><p>If M &lt;= N, then simply use Numpy's random.choice without replacement. </p></li> <li><p>If M > N, then the samples must consist X times all the N numbers in the list, where X is the number of times N fully divides M, i.e. X = floor(M/N) and then sample additional M-(X*N) remainder samples from the list without replacement. </p></li> </ul> <p>For example, let my list be the following: </p> <blockquote> <p>L = [1, 2, 3, 4, 5]</p> </blockquote> <p>and I need to sample 8 samples. Then firstly, I sample the full list once and additional 3 elements randomly without replacement, e.g. my samples could then be: </p> <blockquote> <p>Sampled_list = [1, 2, 3, 4, 5, 3, 5, 1]</p> </blockquote> <p>How can I implement such a code as efficiently as possible in terms of computation time in Python? Can this be done without for-loops? </p> <p>At the moment I'm implementing this using for-loops but this is too inefficient for my purposes. I have also tried Numpy's random.choice without replacement but then I need to have M &lt;= N. </p> <p>Thank you for any help! </p>
2
2016-09-15T09:07:18Z
39,507,782
<p>Here is what might be a solution for the <strong>case where 0 &lt; M-N &lt; max(L)</strong> :</p> <pre><code>import numpy as np from numpy.random import random l = np.array([1, 2, 3, 4, 5]) rand = [ i for i in l[np.argsort(np.amax(l))[:M-N]] ] new_l = np.concatenate(l,rand) </code></pre> <p>Here is an example :</p> <pre><code>l = np.array([1,2,3,4,5]) M, N = 7, len(l) rand = [i for i in l[np.argsort(np.random(np.amax(l)))][:M-N]] new_l = np.concatenate(l,rand) </code></pre> <p>And here is the output :</p> <pre><code>new_list = np.array([1,2,3,4,5,3,4]) </code></pre>
1
2016-09-15T09:39:02Z
[ "python", "numpy", "sampling" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacement from this list M samples.</p></li> <li><p>If M &lt;= N, then simply use Numpy's random.choice without replacement. </p></li> <li><p>If M > N, then the samples must consist X times all the N numbers in the list, where X is the number of times N fully divides M, i.e. X = floor(M/N) and then sample additional M-(X*N) remainder samples from the list without replacement. </p></li> </ul> <p>For example, let my list be the following: </p> <blockquote> <p>L = [1, 2, 3, 4, 5]</p> </blockquote> <p>and I need to sample 8 samples. Then firstly, I sample the full list once and additional 3 elements randomly without replacement, e.g. my samples could then be: </p> <blockquote> <p>Sampled_list = [1, 2, 3, 4, 5, 3, 5, 1]</p> </blockquote> <p>How can I implement such a code as efficiently as possible in terms of computation time in Python? Can this be done without for-loops? </p> <p>At the moment I'm implementing this using for-loops but this is too inefficient for my purposes. I have also tried Numpy's random.choice without replacement but then I need to have M &lt;= N. </p> <p>Thank you for any help! </p>
2
2016-09-15T09:07:18Z
39,507,924
<p>Use <code>divmod()</code> to get the number of repetitions of the list and the remainder/shortfall. The shortfall can then be randomly selected from the list using <code>numpy.random.choice()</code>.</p> <pre><code>import numpy as np def get_sample(l, n): samples, shortfall = divmod(n, len(l)) return np.concatenate((np.repeat(l, samples), np.random.choice(l, shortfall, False))) &gt;&gt;&gt; get_sample(range(100), 10) array([91, 95, 73, 96, 18, 37, 32, 97, 4, 41]) &gt;&gt;&gt; get_sample(range(10), 100) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]) &gt;&gt;&gt; get_sample([1,2,3,4], 0) array([], dtype=int64) &gt;&gt;&gt; get_sample([1,2,3,4], 4) array([1, 2, 3, 4]) &gt;&gt;&gt; get_sample([1,2,3,4], 6) array([1, 2, 3, 4, 4, 3]) &gt;&gt;&gt; get_sample([1,2,3,4], 6) array([1, 2, 3, 4, 3, 2]) &gt;&gt;&gt; get_sample(list('test string'), 6) array(['n', 's', 'g', 's', 't', ' '], dtype='|S1') &gt;&gt;&gt; get_sample(np.array(list('test string')), 4) array(['r', 't', 's', 'g'], dtype='|S1') </code></pre>
1
2016-09-15T09:45:27Z
[ "python", "numpy", "sampling" ]
Curses Programming with Python
39,507,305
<p>So I have start working with Curses in Python. I have got this source code to start with and slowly I will make some updates to it:</p> <pre><code> #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Testing out the curses lib. """ import curses def main(scr): """ Draw a border around the screen, move around using the cursor and leave a mark of the latest pressed character on the keyboard. Perhaps you could make a nice painting using asciart? Quit using 'q'. """ # Clear the screen of any output scr.clear() # Get screen dimensions y1, x1 = scr.getmaxyx() y1 -= 1 x1 -= 1 y0, x0 = 0, 0 # Get center position yc, xc = (y1-y0)//2, (x1-x0)//2 # Draw a border scr.border() # Move cursor to center scr.move(yc, xc) # Refresh to draw out scr.refresh() # Main loop x = xc y = yc ch = 'o' while True: key = scr.getkey() if key == 'q': break elif key == 'KEY_UP': y -= 1 elif key == 'KEY_DOWN': y += 1 elif key == 'KEY_LEFT': x -= 1 elif key == 'KEY_RIGHT': x += 1 else: ch = key # Draw out the char at cursor position scr.addstr(ch) # Move cursor to new position scr.move(y, x) # Redraw all items on the screen scr.refresh() if __name__ == "__main__": print(__doc__) print(main.__doc__) input("Press enter to begin playing...") curses.wrapper(main) </code></pre> <p>The thing I want to do now is to make sure that when I can't hit the border of the screen. But I'm not sure what function in the this I can use for that. I have read in the <a href="https://docs.python.org/3/library/curses.html#functions" rel="nofollow">python docs</a> but can't find anything I think will work.</p>
0
2016-09-15T09:17:35Z
39,508,038
<p>You know the valid range. From <code>0</code> to to <code>y1</code> inclusive. (0 to <code>x1</code> respectively). So just add tests to ensure the coordinates stay within the range:</p> <pre><code> elif key == 'KEY_UP': if y &gt; 0: y -= 1 elif key == 'KEY_DOWN': if y &lt; y1: y += 1 </code></pre> <p>and similar for the <code>x</code>.</p>
1
2016-09-15T09:50:46Z
[ "python", "python-3.x", "curses" ]
How to unpack variables from tuple and give them names from another tuple?
39,507,350
<p>I have two tuples - one with the keys and another one with a collection of variables of different types (list, float64, int and array) generate with the help of the following formula from a dictionary:</p> <pre><code>keys, values = zip(*[(key, value) for (key, value) in data_dict.items()]) </code></pre> <p>Now I would like to retrieve the variables from the list of values and give them names from the list of keys. How can I do that?</p>
0
2016-09-15T09:20:03Z
39,508,015
<p>If it's really not possible to store your key/value pairs in a <code>dict</code> and serialise them to data file in that format, you can use <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow"><code>exec</code></a> to dynamically construct assignment statements</p> <pre><code>&gt;&gt;&gt; key = 'foo_var' &gt;&gt;&gt; val = 'foo_val' &gt;&gt;&gt; exec('{key} = \'{val}\''.format(key=key, val=val)) &gt;&gt;&gt; foo_var 'foo_val' </code></pre> <p>I'd explore the <code>dict</code> approach first though, in case that can work for you. There are lots of good reasons to avoid runtime code generation using <code>exec</code> and <code>eval</code> where possible.</p>
1
2016-09-15T09:49:16Z
[ "python" ]
How to unpack variables from tuple and give them names from another tuple?
39,507,350
<p>I have two tuples - one with the keys and another one with a collection of variables of different types (list, float64, int and array) generate with the help of the following formula from a dictionary:</p> <pre><code>keys, values = zip(*[(key, value) for (key, value) in data_dict.items()]) </code></pre> <p>Now I would like to retrieve the variables from the list of values and give them names from the list of keys. How can I do that?</p>
0
2016-09-15T09:20:03Z
39,508,083
<p>If you want to create variables in the global scope from your dictionary, perhaps you could update it like this:</p> <pre><code>globals().update(data_dict) </code></pre> <p>without unpacking the dict.</p> <p>I'm not sure if this is what you're looking for.</p>
0
2016-09-15T09:52:57Z
[ "python" ]
The recursive implementation with python for a mathematical puzzle of hailstone sequence or Collatz conjecture?
39,507,395
<p>There is a mathematical puzzle:</p> <ol> <li>Pick a positive integer n as start. </li> <li>If n is even, then divide it by 2.</li> <li>If n is odd, multiply it by 3, and add 1. </li> <li>continue this process until n is 1.</li> </ol> <p>I want to write a recursive function, that takes the n as parameter, and then return a tuple that includes a sequence of track of n in the process, and the length of sequence. But failed. </p> <p>What wrong is my code? How to achieve the task?</p> <pre><code>def hailstone(n): """the implementation of recursive one, return a tuple that includes the hailstone sequence starting at n, and the length of sequence. &gt;&gt;&gt; a = hailstone(1) ([1, 4, 2, 1], 4) """ if n % 2 == 0: n = n//2 else: n = n*3 + 1 if n == 1: return [n] else: """ for some magic code here, it will return a tuple that includes the list track of n, and the length of sequence, like ([1, 4, 2, 1], 4) """ return ([n for some_magic in hailstone(n)], lenght_of_seq) </code></pre>
0
2016-09-15T09:22:01Z
39,507,961
<p>You can use an accumulator:</p> <pre><code>def hailstone(n): """ return a tuple that includes the hailstone sequence starting at n, and the length of sequence. 1) Pick a positive integer n as start. 2) If n is even, then divide it by 2. 3) If n is odd, multiply it by 3, and add 1. 4) continue this process until n is 1. """ def hailstone_acc(n, acc): acc.append(n) if n == 1: return acc, len(acc) elif n % 2 == 0: return hailstone_acc(n//2, acc) else: return hailstone_acc(3*n + 1, acc) if n == 1: return hailstone_acc(4,[1]) else: return hailstone_acc(n, []) </code></pre> <p>Now, in action:</p> <pre><code>(trusty)juan@localhost:~/workspace/testing/hailstone$ python -i hailstone.py &gt;&gt;&gt; hailstone(1) ([1, 4, 2, 1], 4) &gt;&gt;&gt; hailstone(4) ([4, 2, 1], 3) &gt;&gt;&gt; hailstone(23) ([23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1], 16) &gt;&gt;&gt; </code></pre>
2
2016-09-15T09:46:57Z
[ "python", "algorithm", "recursion" ]
The recursive implementation with python for a mathematical puzzle of hailstone sequence or Collatz conjecture?
39,507,395
<p>There is a mathematical puzzle:</p> <ol> <li>Pick a positive integer n as start. </li> <li>If n is even, then divide it by 2.</li> <li>If n is odd, multiply it by 3, and add 1. </li> <li>continue this process until n is 1.</li> </ol> <p>I want to write a recursive function, that takes the n as parameter, and then return a tuple that includes a sequence of track of n in the process, and the length of sequence. But failed. </p> <p>What wrong is my code? How to achieve the task?</p> <pre><code>def hailstone(n): """the implementation of recursive one, return a tuple that includes the hailstone sequence starting at n, and the length of sequence. &gt;&gt;&gt; a = hailstone(1) ([1, 4, 2, 1], 4) """ if n % 2 == 0: n = n//2 else: n = n*3 + 1 if n == 1: return [n] else: """ for some magic code here, it will return a tuple that includes the list track of n, and the length of sequence, like ([1, 4, 2, 1], 4) """ return ([n for some_magic in hailstone(n)], lenght_of_seq) </code></pre>
0
2016-09-15T09:22:01Z
39,509,530
<p>First, you need to decide whether to use an iterative or recursive process - in Python it doesn't matter much (since Python doesn't employ tail call optimization), but in languages it could. For a more in-depth explanation of iterative/recursive process see <a href="http://stackoverflow.com/q/17254240/106471" title="SICP recursive process vs iterative process: using a recursive procedure to generate an iterative process">this question</a>.</p> <p>In either case, it's usually best to start from the ending condition and work your way from there. In this case that's <code>n == 1</code>.</p> <h2>Recursive process</h2> <p>Let's start with a recursive process. In this case, state is maintained in the call chain, and the result is computed once we have reached the innermost call (and we're returning up the call chain).</p> <pre><code>def hailstone(n): if n == 1: return [n], 1 </code></pre> <p>Alright, that's the end condition - now we've made sure the function will return once <code>n</code> is 1. Let's continue and add the rest of the conditions:</p> <pre><code>def hailstone_rec(n): if n == 1: return (n,), 1 if n % 2 == 0: # Even rest = hailstone_rec(n//2) else: # Odd rest = hailstone_rec(n*3+1) return (n,) + rest[0], rest[1] + 1 </code></pre> <p>What happens here when <code>n</code> is not 1, is that we first recurse to compute the rest of the sequence, and then add the values for current invocation to that result. So, if <code>n</code> is 2, this means we'll compute <code>hailstone_rec(2//2)</code> which will return <code>((1,), 1)</code>, and then we add the current values and return the result (<code>((2, 1), 2)</code>).</p> <h2>Iterative process</h2> <p>With an iterative process, the result is computed while proceeding down the call chain, and you pass the current state into the next function call when recursing. This means that the result does not depend on calls higher up in the call chain, which means that when the end is reached, the innermost function can just return the result. This has significance in languages with tail call optimization, since the state of the outer calls may be discarded.</p> <p>When implementing a function with this process it's often helpful to use an inner helper function with extra parameters to pass on the state, so let's define a user-facing function and an inner helper function:</p> <pre><code># user facing function def hailstone_it(n): # Call the helper function with initial values set return hailstone_it_helper(n, (), 0) # internal helper function def hailstone_it_helper(n, seq, length): pass </code></pre> <p>As can be seen, the user-facing function just calls the internal function with the state parameters set to initial values. Let's continue implementing the actual logic, all of which will reside inside the helper. As with the previous solution, let's start with the end condition (<code>n == 1</code>):</p> <pre><code>def hailstone_it_helper(n, seq, length): if n == 1: return seq + (n,), length + 1 </code></pre> <p>This time around, we take partial result from the previous call(s), add the current values, and return that. Now, handle the remaining cases:</p> <pre><code>def hailstone_it_helper(n, seq, length): if n == 1: return seq + (n,), length + 1 if n % 2 == 0: # Even return hailstone_it_helper(n//2, seq + (n,), length + 1) else: return hailstone_it_helper(n*3+1, seq + (n,), length + 1) def hailstone_it(n): return hailstone_it_helper(n, (), 0) </code></pre> <p>When recursing here, we pass in the next n in the series (depending on whether the current n is even or odd), and the result so far.</p> <h2>A more pythonic solution</h2> <p>Finally, since you would normally not code like this in Python, let's finish with a more pythonic solution as a bonus (i.e, one that's not using recursion at all):</p> <pre><code>def hailstone_pythonic(n): seq = [] while n != 1: seq.append(n) if n % 2 == 0: n //= 2 else: n = n * 3 + 1 seq.append(n) return tuple(seq), len(seq) </code></pre>
1
2016-09-15T11:06:14Z
[ "python", "algorithm", "recursion" ]
How can I find one tag between two other tags?
39,507,399
<p>I have a document with structure like this:</p> <pre><code>&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt; ... </code></pre> <p>And I need to get all <code>tag2</code> instances that are after <code>tag1</code> with <code>some_text_1</code> and before the next <code>tag1</code>.</p>
0
2016-09-15T09:22:19Z
39,507,574
<p>You should explain better what you need to find because is hard understand exactly what you want.</p> <p>A good way to do it is using a regular expressions.</p> <p><strong>Re Library Documentation:</strong> <a href="https://docs.python.org/2/library/re.html" rel="nofollow">https://docs.python.org/2/library/re.html</a></p>
-2
2016-09-15T09:29:49Z
[ "python", "python-3.x", "beautifulsoup" ]
How can I find one tag between two other tags?
39,507,399
<p>I have a document with structure like this:</p> <pre><code>&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt; ... </code></pre> <p>And I need to get all <code>tag2</code> instances that are after <code>tag1</code> with <code>some_text_1</code> and before the next <code>tag1</code>.</p>
0
2016-09-15T09:22:19Z
39,508,232
<pre><code>from bs4 import BeautifulSoup html = '''&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt;''' soup = BeautifulSoup(html,"html.parser") def findalltags(tag1,tag2,soup): # tag1 is between which tag # tag2 get info of which tag a = soup.find(tag1) lis = [] while True: a = a.find_next() if(str(a.name) == tag1): break elif(str(a.name) == tag2): lis.append(a) return lis if __name__ == '__main__': print findalltags('tag1','tag2',soup) </code></pre> <p>Hope this will solve the problem but I don't think this is an efficient way. You can use regular expressions if you familiar with them.</p>
0
2016-09-15T10:00:29Z
[ "python", "python-3.x", "beautifulsoup" ]
How can I find one tag between two other tags?
39,507,399
<p>I have a document with structure like this:</p> <pre><code>&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt; ... </code></pre> <p>And I need to get all <code>tag2</code> instances that are after <code>tag1</code> with <code>some_text_1</code> and before the next <code>tag1</code>.</p>
0
2016-09-15T09:22:19Z
39,510,675
<p>Your description <em>I need to get all tag2 instances that are after tag1 with some_text_1 and before the next tag2.</em> basically equates to getting the first <code>tag2</code> after any tag1 with the text <code>some_text_</code>.</p> <p>So find the <code>tag1's</code> with the certain text and check if the next sibling tag is a <code>tag2</code>, if it is pull the tag2:</p> <pre><code>html = """&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt;""" def get_tags_if_preceded_by(soup, tag1, tag2, text): for t1 in soup.find_all(tag1, text=text): nxt_sib = t1.find_next_sibling() if nxt_sib and nxt_sib.name == tag2: yield nxt_sib soup = BeautifulSoup(html, "lxml") print(list(get_tags_if_preceded_by(soup, "tag1", "tag2", "some_text_1"))) </code></pre> <p>If it does not have to be directly after, it actually makes it simpler, you just need to search for a specific <code>tag2</code> sibling:</p> <pre><code>def get_tags_if_preceded_by(soup, tag1, tag2, text): for t1 in soup.find_all(tag1, text=text): nxt_sib = t1.find_next_sibling(t2) if nxt_sib: yield nxt_sib </code></pre> <p>If you really want to find tags between two tags specifically, you can use the logic in <a href="http://stackoverflow.com/questions/38290588/extracting-html-between-tags/38290786#38290786">this answer</a>.</p>
1
2016-09-15T12:08:48Z
[ "python", "python-3.x", "beautifulsoup" ]
TensorFlow, Python, Sharing Variables, initialize at top
39,507,405
<p>I'm having an issue in TensorFlow with Sharing Variables with the Python API.</p> <p>I've read the official documentation (<a href="https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html</a>), but I still can't figure out what is going on.</p> <p>I've written below a minimal working example to illustrate the issue.</p> <p>In a nutshell, I'd like the code below do to the following:</p> <p>1) Initialize one variable "fc1/w" immediately after I create the session,</p> <p>2) Create a npy array "x_npy" to feed into a placeholder "x",</p> <p>3) Run an operation "y", which should realize that the variable "fc1/w" is already created, and then use that variable values (rather than initialize new ones) to compute its output.</p> <p>4) Please note that I added the flag ", reuse=True" in the variable scope in the function "linear", but that doesn't seem to help, since I keep getting the error:</p> <pre><code>ValueError: Variable fc1/w does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope? </code></pre> <p>This is quite confusing since if I were to remove the flag ", reuse=True", then TensorFlow would tell me that the variable does exist:</p> <pre><code>ValueError: Variable fc1/w already exists, disallowed. Did you mean to set reuse=True in VarScope? </code></pre> <p>5) Please note that I'm working with a larger code base, and I'd really like to be able to use the Sharing Variables capability, rather than come up with a hack without using Sharing Variables that might solve the particular example code I wrote below, but might not generalize well.</p> <p>6) Finally, please note also that I'd really like to keep separated the creation of the graph from it's evaluation. In particular, I would not like to use "tf.InteractiveSession()" or create "y" in the session scope, i.e., below: "with tf.Session() as sess:".</p> <p>This is my first post on Stack Overflow, and I'm quite new to TensorFlow, so please accept my apologies if the question is not completely clear. In any case, I'd be happy to provide more details or clarify any aspect further.</p> <p>Thank you in advance.</p> <pre><code>import tensorflow as tf import numpy as np def linear(x_, output_size, non_linearity, name): with tf.variable_scope(name, reuse=True): input_size = x_.get_shape().as_list()[1] # If doesn't exist, initialize "name/w" randomly: w = tf.get_variable("w", [input_size, output_size], tf.float32, tf.random_normal_initializer()) z = tf.matmul(x_, w) return non_linearity(z) def init_w(name, w_initializer): with tf.variable_scope(name): w = tf.get_variable("w", initializer=w_initializer) return tf.initialize_variables([w]) batch_size = 1 fc1_input_size = 7 fc1_output_size = 5 # Initialize with zeros fc1_w_initializer = tf.zeros([fc1_input_size, fc1_output_size]) # x = tf.placeholder(tf.float32, [None, fc1_input_size]) # y = linear(x, fc1_output_size, tf.nn.softmax, "fc1") with tf.Session() as sess: # Initialize "fc1/w" with zeros. sess.run(init_w("fc1", fc1_w_initializer)) # Create npy array to feed into placeholder x x_npy = np.arange(batch_size * fc1_input_size, dtype=np.float32).reshape((batch_size, fc1_input_size)) # Run y, and print result. print(sess.run(y, dict_feed={x: x_npy})) </code></pre>
0
2016-09-15T09:22:33Z
39,513,649
<p>It seems like the call to tf.variable_scope() finds the variable scope/w even if you run it in an empty session. I have cleaned up your code to demonstrate.</p> <pre><code>import tensorflow as tf import numpy as np def shared_layer(x, output_size, non_linearity, name): with tf.variable_scope(name): input_size = x.get_shape().as_list()[1] # If doesn't exist, initialize "name/w" randomly: w = tf.get_variable("w", [input_size, output_size], tf.float32, tf.random_normal_initializer()) z = tf.matmul(x, w) return non_linearity(z) def shared_init(sess, scope, var, initializer): with tf.variable_scope(scope, reuse=True): w = tf.get_variable(var, initializer=initializer) sess.run(tf.initialize_variables([w])) layer_input_size = 2 layer_output_size = 2 w_init = tf.zeros([layer_input_size, layer_output_size]) x = tf.placeholder(tf.float32, [None, layer_input_size]) y = shared_layer(x, layer_output_size, tf.nn.softmax, "scope") with tf.Session() as sess: shared_init(sess, "scope", "w", w_init) with tf.variable_scope("scope", reuse=True): print sess.run(tf.get_variable("w", [2,2])) </code></pre>
0
2016-09-15T14:25:58Z
[ "python", "tensorflow" ]
Identify cells containing specific strings and overwrite content with numbers using Python
39,507,417
<p>I have a dataframe which looks like this:</p> <p><a href="http://i.stack.imgur.com/qe7Y2.png" rel="nofollow"><img src="http://i.stack.imgur.com/qe7Y2.png" alt="enter image description here"></a></p> <p>My goal is to identify for each cell of every column if the following strings are contained: <code>'KSS'</code>, <code>'ABC'</code>, <code>'DEF'</code>, <code>'ABC / DEF'</code>, <code>'KSS / DEF'</code></p> <p>Subsequently I would like to substitute the content with the following values: <code>'KSS'</code> -> 100, <code>'ABC'</code> -> 200, <code>'DEF'</code> -> 300, <code>'ABC / DEF'</code> -> 400, <code>'KSS / DEF'</code> -> 500</p> <p>The output should be like something like this:</p> <p><a href="http://i.stack.imgur.com/ETIMW.png" rel="nofollow"><img src="http://i.stack.imgur.com/ETIMW.png" alt="enter image description here"></a></p> <p>Notice: the algorithm should be generic and check every column, not only number 3. For sake of completeness the data types are all <code>objects</code>.</p> <p>So far my line of codes are these but I guess they are incomplete...</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame([ ['XYZ', 'BALSO', 'PISCO', 'KSS', 'Yes', 660, 'Cop'], ['XYZ', 'TONTO', 'LOLLO', '195', 500, 'Yes', 'nan'], ['XYZ', 'CALLO', 'WANDA', 'ABC / DEF', 'Yes', 500, 'nan'], ['XYZ', 'AZUNGO', 'FINGI', 'KSS / DEF', 'Yes', 500, 'nan'] ]) df = pd.read_csv('prova.csv', sep=',', skiprows=0, header=None, low_memory=False) df.str.replace('KSS|ABC|DEF','?') </code></pre>
0
2016-09-15T09:22:52Z
39,507,870
<p>If you create a dict with your lookup and replacement values then you can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html#pandas.Series.map" rel="nofollow"><code>map</code></a> on this column, additionally you need to pass <code>na_action='ignore'</code> to <code>map</code> otherwise you get a <code>KeyError</code> for the missing values, additionally you will note that as you have missing values the values get converted to <code>float</code> but you can cast again using <code>astype(int)</code> later:</p> <pre><code>In [182]: d={'KSS':100, 'ABC' :200, 'DEF' : 300, 'ABC / DEF' : 400, 'KSS / DEF' : 500} df[3] = df[3].map(d, na_action='ignore') df Out[182]: 0 1 2 3 4 5 0 XYZ BALSO PISCO 100.00 660 Cop 1 XYZ TONTO LOLLO nan 500 nan 2 XYZ CALLO WANDA 400.00 500 nan 3 XYZ AZUNGO FINGI 500.00 500 nan </code></pre> <p>here we cast the type using <code>astype</code>:</p> <pre><code>In [178]: df[3] = df[3].astype(int) df Out[178]: 0 1 2 3 4 5 0 XYZ BALSO PISCO 100 660 Cop 1 XYZ TONTO LOLLO 195 500 nan 2 XYZ CALLO WANDA 400 500 nan 3 XYZ AZUNGO FINGI 500 500 nan </code></pre>
3
2016-09-15T09:43:17Z
[ "python", "pandas", "replace", "substitution" ]
Fill missing values from another Pandas dataframe with different shape
39,507,433
<p>I have 2 tables of different sizes which I would like to merge in the following way in Python using Pandas:</p> <pre><code>UID Property Date 1 A 10/02/2016 2 B NaN 3 A 10/02/2016 4 C NaN 5 C NaN 6 A 10/02/2016 </code></pre> <p>Table 1 contains information about Property transactions and a Date related to the Property. As some of the dates are NaNs, I would like to proxy them from another table (Table 2) containing information solely about properties, but not replacing any dates in Table 1:</p> <pre><code>Property DateProxy A 01/01/2016 B 03/04/2016 C 16/05/2016 </code></pre> <p>In the end I would like to obtain the following:</p> <pre><code>UID Property Date 1 A 10/02/2016 (kept from T1) 2 B 03/04/2016 (imported from T2) 3 A 10/02/2016 (kept from T1) 4 C 16/05/2016 (imported from T2) 5 C 16/05/2016 (imported from T2) 6 A 10/02/2016 (kept from T1) </code></pre>
0
2016-09-15T09:23:19Z
39,507,621
<p>First let's merge the two datasets: we don't overwrite the original date:</p> <pre><code>df_merge = pandas.merge(T1, T2, on='Property') </code></pre> <p>then we replace the missing values copying them from the 'DateProxy' field:</p> <pre><code>df_merge.Date = df_merge.apply( lambda x: x['Date'] + ' (kept from T1)' if x['Date'] == x['Date'] else x['DateProxy'] + ' (imported from T2)', axis=1 ) </code></pre> <p>(the x['Date'] == x['Date'] is to check that it isn't NaN, NaN is not equal to itself). Finally we can drop the proxy column:</p> <pre><code>df_final = df_merge.drop('DateProxy', axis=1) </code></pre>
1
2016-09-15T09:31:39Z
[ "python", "pandas", "merge" ]
YAML key consisting of a list of elements
39,507,595
<p>I need to have a list of elements as a key, so that I can check if several conditions are met. Example (don't know if this is possible and if the syntax is correct):</p> <pre><code>mapping: c_id: [pak, gb]: '4711' [pak, ch]: '4712' [pak]: '4713' d_id: . . . </code></pre> <p>Now I need to know if it is possible to have an approach as in the example.</p>
0
2016-09-15T09:30:37Z
39,507,713
<p>The syntax for your YAML is correct. The only trick is that because in Python a key has to be immutable you need to specify access to the complex key as a tuple:</p> <pre><code>import ruamel.yaml yaml_str = """\ mapping: c_id: [pak, gb]: '4711' [pak, ch]: '4712' [pak]: '4713' """ data = ruamel.yaml.round_trip_load(yaml_str) print(data['mapping']['c_id'][('pak', 'gb')]) </code></pre> <p>gives:</p> <pre><code>4711 </code></pre> <p>Please note that this is not possible with PyYAML, as it doesn't support sequences as keys, you have to use <a href="https://pypi.python.org/pypi/ruamel.yaml/" rel="nofollow"><code>ruamel.yaml</code></a> (disclaimer: I am the author of that package)</p>
2
2016-09-15T09:35:36Z
[ "python", "yaml", "pyyaml" ]
YAML key consisting of a list of elements
39,507,595
<p>I need to have a list of elements as a key, so that I can check if several conditions are met. Example (don't know if this is possible and if the syntax is correct):</p> <pre><code>mapping: c_id: [pak, gb]: '4711' [pak, ch]: '4712' [pak]: '4713' d_id: . . . </code></pre> <p>Now I need to know if it is possible to have an approach as in the example.</p>
0
2016-09-15T09:30:37Z
39,510,765
<p>In addition to Anthon's answer, here is how you can do it with PyYaml:</p> <pre><code>mapping: c_id: !!python/tuple [pak, gb]: '4711' !!python/tuple [pak, ch]: '4712' !!python/tuple [pak]: '4713' </code></pre> <p>The trick is to tell PyYaml that you want to load the keys into a tuple (since a list cannot be used as dict key). There is no way to do this <em>implicitly</em>, but this does not mean that it is not possible.</p> <p>Explicit keys may be more readable in this case:</p> <pre><code>mapping: c_id: ? !!python/tuple [pak, gb] : '4711' ? !!python/tuple [pak, ch] : '4712' ? !!python/tuple [pak] : '4713' </code></pre> <p>This example is semantically equivalent to the first one.</p>
1
2016-09-15T12:13:33Z
[ "python", "yaml", "pyyaml" ]
Python pandas nonzero cumsum
39,507,774
<p>I want to apply <code>cumsum</code> on dataframe in <code>pandas</code> in <code>python</code>, but withouth zeros. Simply I want to leave zeros and do <code>cumsum</code> on dataframe. Suppose I have dataframe like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a' : [1,2,0,1], 'b' : [2,5,0,0], 'c' : [0,1,2,5]}) a b c 0 1 2 0 1 2 5 1 2 0 0 2 3 1 0 5 </code></pre> <p>and result sould be</p> <pre><code> a b c 0 1 2 0 1 3 7 1 2 0 0 3 3 4 0 8 </code></pre> <p>Any ideas how to do that avoiding loops? In <code>R</code> there is <code>ave</code> function, but Im very new to <code>python</code> and I dont know.</p>
2
2016-09-15T09:38:41Z
39,507,811
<p>You can mask the df so that you only overwrite the non-zero cells:</p> <pre><code>In [173]: df[df!=0] = df.cumsum() df Out[173]: a b c 0 1 2 0 1 3 7 1 2 0 0 3 3 4 0 8 </code></pre>
5
2016-09-15T09:40:19Z
[ "python", "pandas" ]
OR-tools routing fails to find 'trivial' optimal solution in the presence of order-constraints
39,507,824
<p>In order to better understand the constraint-programming behind or-tools routing, I created a toy example of a depot and 4 other nodes configured to allow for two routes.</p> <p><a href="http://i.stack.imgur.com/SiZj1.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/SiZj1.jpg" alt="enter image description here"></a></p> <p>The idea is that a vehicle travels from the depot <code>0</code> to <code>1</code>, then either picks <code>2</code> or <code>3</code>, continues to <code>4</code> and returns to the depot <code>0</code>; the vehicle either picks the green or red path. My actual problem is more complicated and has multiple vehicles, but has similar constraints.</p> <p>For this example I created a euclidean-distance function for the cost: </p> <pre class="lang-py prettyprint-override"><code>class Distances: def __init__(self): self.locations = [ [-1, 0], # source [ 0, -1], # waypoint 1 [ 0, 1], # waypoint 2 [ 1, 0], # destination ] def __len__(self): return len(self.locations) + 1 def dist(self, x, y): return int(10000 * math.sqrt( (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2)) def __call__(self, i, j): if i == 0 and j == 0: return 0 if j == 0 or i == 0: return 1 # very small distance between depot and non-depot, simulating 0 return self.dist(self.locations[i - 1], self.locations[j - 1]) distance = Distances() </code></pre> <p>And a l0 distance function to constraint the order:</p> <pre class="lang-py prettyprint-override"><code># l0-distance to add order constraints class Order: def __call__(self, i, j): return 0 if i == j else 1 order = Order() </code></pre> <p>Then I create the model and try to solve this:</p> <pre class="lang-py prettyprint-override"><code>search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.ALL_UNPERFORMED) search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.SIMULATED_ANNEALING search_parameters.time_limit_ms = 3000 routing = pywrapcp.RoutingModel(len(distance), 1) routing.SetArcCostEvaluatorOfAllVehicles(distance) routing.SetDepot(0) solver = routing.solver() routing.AddDimension(order, int(1e18), int(1e18), True, "order") # Since `ALL_UNPERFORMED` is used, each node must be allowed inactive order_dimension = routing.GetDimensionOrDie("order") routing.AddDisjunction([1], int(1e10)) routing.AddDisjunction([2, 3], int(1e10)) routing.AddDisjunction([4], int(1e10)) solver.AddConstraint(order_dimension.CumulVar(1) &lt;= order_dimension.CumulVar(2)) solver.AddConstraint(order_dimension.CumulVar(1) &lt;= order_dimension.CumulVar(3)) solver.AddConstraint(order_dimension.CumulVar(2) &lt;= order_dimension.CumulVar(4)) solver.AddConstraint(order_dimension.CumulVar(3) &lt;= order_dimension.CumulVar(4)) # routing.AddPickupAndDelivery(1, 2) # routing.AddPickupAndDelivery(1, 3) # routing.AddPickupAndDelivery(2, 4) # routing.AddPickupAndDelivery(3, 4) routing.CloseModelWithParameters(search_parameters) assignment = routing.SolveWithParameters(search_parameters) if assignment is not None: print('cost: ' + str(assignment.ObjectiveValue())) route = [] index = routing.Start(0) while not routing.IsEnd(index): route.append(routing.IndexToNode(index)) index = assignment.Value(routing.NextVar(index)) for node in route: print(' - {:2d}'.format(node)) else: print('nothing found') </code></pre> <p>So <code>[1]</code> and <code>[4]</code> are disjunctions to allow for <code>ALL_UNPERFORMED</code> first solution to work, and the disjunction <code>[2, 3]</code> to state that either the green or red path should be chosen.</p> <p>With these disjunctions the solver finds a solution, but if I add that <code>2</code> and <code>3</code> should be visited after <code>1</code> and before <code>4</code>, the solver does not visit <code>2</code> or <code>3</code> at all. Why is this the case? Why can't the solver find the more optimal route <code>0 -&gt; 1 -&gt; 2/3 -&gt; 4 -&gt; 0</code> avoiding the <code>int(1e10)</code> disjunction penalty for <code>[2,3]</code>?</p> <p><strong>EDIT:</strong></p> <p>Soft-constraining the order-constraints by removing them and adding to <code>Distance.__call__</code>:</p> <pre class="lang-py prettyprint-override"><code>if (i == 2 or j == 1) or (i == 3 or j == 1) or (i == 4 or j == 2) or (i == 4 or j == 3): return int(1e10) </code></pre> <p>to penalize a disallowed order, results in the route <code>0 -&gt; 2 -&gt; 1 -&gt; 4 -&gt; 0</code>. So I wonder why or-tools won't swap <code>1</code> and <code>2</code>, even when explicitly enabling <code>use_swap_active</code> and <code>use_relocate_neighbors</code> in <code>search_parameters.local_search_operators</code>.</p> <p><strong>NOTE:</strong> Failed because it should have been:</p> <pre class="lang-py prettyprint-override"><code>if (i == 2 and j == 1) or (i == 3 and j == 1) or (i == 4 and j == 2) or (i == 4 and j == 3): return int(1e10) </code></pre> <p>Concluding: the search-space is small, a better solution is in the neighborhood of <code>use_relocate_neighbors</code> of the returned solution, yet or-tools does not find it. Why?</p> <h1>All code:</h1> <pre class="lang-py prettyprint-override"><code>import pandas import os.path import numpy import math from ortools.constraint_solver import pywrapcp from ortools.constraint_solver import routing_enums_pb2 class Distances: def __init__(self): self.locations = [ [-1, 0], # source [ 0, -1], # waypoint 1 [ 0, 1], # waypoint 2 [ 1, 0], # destination ] def __len__(self): return len(self.locations) + 1 def dist(self, x, y): return int(10000 * math.sqrt( (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2)) def __call__(self, i, j): if i == 0 and j == 0: return 0 if j == 0 or i == 0: return 1 # very small distance between depot and non-depot, simulating 0 return self.dist(self.locations[i - 1], self.locations[j - 1]) distance = Distances() # l0-distance to add order constraints class Order: def __call__(self, i, j): return 0 if i == j else 1 order = Order() search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.ALL_UNPERFORMED) search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.SIMULATED_ANNEALING search_parameters.time_limit_ms = 3000 routing = pywrapcp.RoutingModel(len(distance), 1) routing.SetArcCostEvaluatorOfAllVehicles(distance) routing.SetDepot(0) solver = routing.solver() routing.AddDimension(order, int(1e18), int(1e18), True, "order") # Since `ALL_UNPERFORMED` is used, each node must be allowed inactive order_dimension = routing.GetDimensionOrDie("order") routing.AddDisjunction([1], int(1e10)) routing.AddDisjunction([2, 3], int(1e10)) routing.AddDisjunction([4], int(1e10)) solver.AddConstraint( (routing.ActiveVar(2) == 0) or (order_dimension.CumulVar(1) &lt;= order_dimension.CumulVar(2)) ) solver.AddConstraint( (routing.ActiveVar(3) == 0) or (order_dimension.CumulVar(1) &lt;= order_dimension.CumulVar(3)) ) solver.AddConstraint( (routing.ActiveVar(2) == 0) or (order_dimension.CumulVar(2) &lt;= order_dimension.CumulVar(4)) ) solver.AddConstraint( (routing.ActiveVar(3) == 0) or (order_dimension.CumulVar(3) &lt;= order_dimension.CumulVar(4)) ) # routing.AddPickupAndDelivery(1, 2) # routing.AddPickupAndDelivery(1, 3) # routing.AddPickupAndDelivery(2, 4) # routing.AddPickupAndDelivery(3, 4) routing.CloseModelWithParameters(search_parameters) assignment = routing.SolveWithParameters(search_parameters) if assignment is not None: print('cost: ' + str(assignment.ObjectiveValue())) route = [] index = routing.Start(0) while not routing.IsEnd(index): route.append(routing.IndexToNode(index)) index = assignment.Value(routing.NextVar(index)) for node in route: print(' - {:2d}'.format(node)) else: print('nothing found') </code></pre>
0
2016-09-15T09:41:01Z
39,718,730
<p><strong>@furnon</strong> On github answered my question via the github-issues list: <a href="https://github.com/google/or-tools/issues/252#issuecomment-249646587" rel="nofollow">https://github.com/google/or-tools/issues/252#issuecomment-249646587</a></p> <p>First, constraint programming performs better on tighter constraints, I guess some things are searched for exaustively. In particular, I had to limit the order-dimension:</p> <pre class="lang-py prettyprint-override"><code>routing.AddDimension(order, int(1e18), int(1e18), True, "order") </code></pre> <p>is better constrained via</p> <pre class="lang-py prettyprint-override"><code>routing.AddDimension(order, len(distance) + 1 ,len(distance) + 1, True, "order") </code></pre> <p>Subsequently, the check on whether <code>2</code> or <code>3</code> is active is not needed, hence we can simplify the order-constrains like this:</p> <pre class="lang-py prettyprint-override"><code>solver.AddConstraint(order_dimension.CumulVar(1) &lt;= order_dimension.CumulVar(2)) solver.AddConstraint(order_dimension.CumulVar(1) &lt;= order_dimension.CumulVar(3)) solver.AddConstraint(order_dimension.CumulVar(2) &lt;= order_dimension.CumulVar(4)) solver.AddConstraint(order_dimension.CumulVar(3) &lt;= order_dimension.CumulVar(4)) </code></pre> <p>As I already did in the inline version, but not in the all-code version. Now a feasible solution is returned.</p>
0
2016-09-27T07:33:17Z
[ "python", "or-tools" ]
Make unittest.mock.Mock() return list of dicts
39,507,864
<p>I'm trying to mock a call of method <code>extra_get()</code> which usually returns a list of dicts. As far as I understand from the Mock <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock" rel="nofollow">docs</a>, if I want to return iterable, I should set side_effect param.</p> <pre><code>client.extra_get = mock.Mock( **{'side_effect': [{'foo': 'bar'}]}) </code></pre> <p>But then the following code calls that mocked method:</p> <pre><code>extra = client.extra_get(request, type_id) result = {x.key: x.value for x in extra} return result </code></pre> <p>And the dict comprehention fails because <code>extra</code> there is not a list, but dict <code>{'foo': 'bar'}</code>. What I'm doing wrong? How can I make Mock method return a list of dicts?</p>
0
2016-09-15T09:43:03Z
39,537,404
<pre><code>with mock.patch.object(client, 'extra_get', return_value=[{...}, {...}]) as mock_get: # fill in the rest </code></pre>
1
2016-09-16T17:47:41Z
[ "python", "unit-testing", "python-unittest" ]
Calling functions
39,507,903
<p>this may sound proper nooby, but I'm having some trouble with python functions.</p> <p>i do a level computer science and I'm making a currency converter using a dictionary to define the exchange rates of the currencies.</p> <p>for each conversion, i have made a function that does all the calculations etc for the converting. for example, if i wanted to convert sterling to euro, my script would use the SE function. after i have defined all the functions, there is a algorithm that says </p> <pre><code>if (i == 'SE'): return(SE) </code></pre> <p>because SE is the function name for this conversion. however, when i run this code, it tells me that <code>return</code> cannot be used outside of a function, so is there a way in calling up the function?</p> <p>my code without using functions can be found here: <a href="http://pastebin.com/bt23MeTn" rel="nofollow">http://pastebin.com/bt23MeTn</a></p> <p>my code with the function attempt can be found here: <a href="http://pastebin.com/sLFwrDT8" rel="nofollow">http://pastebin.com/sLFwrDT8</a></p> <p>for those of you who are wondering why I'm using a dictionary, its because my teacher said that the exchange rates can change anytime so using a dictionary will mean the user only has to change the dict entry instead of changing each individual formula. i suppose i could make a scraper algorithm to scrape a website for each rate, but that'll probably be in my next version :)</p>
-2
2016-09-15T09:44:28Z
39,508,139
<p><code>return</code> is used to return variables from a <a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions" rel="nofollow">function definition</a>. </p> <p>To call a function you have simply to write the name of the function with the input parameters in the round brackets. In your case <code>SE</code> function has not input parameters so you have to call it as follow:</p> <pre><code>if i == 'SE': SE() </code></pre>
2
2016-09-15T09:55:51Z
[ "python", "dictionary", "python-3.5.2" ]
Creating a list of lists and appending lists
39,507,943
<pre><code>a=[[2,3],[3,4]] b=[[5,6],[7,8],[9,10]] c=[[11,12],[13,14],[15,16],[17,18]] c1=[[11,12],[13,14],[15,16],[17,18]] listr=[] for number in range(96): listr.append(number) list = [[]]*96 for e in a: for f in b: for g in c: for h in d: for i in listr: list[i].append(e) list[i].append(f) list[i].append(g) print list </code></pre> <p>I am having real difficulty with this simple problem. I would like to create a list of lists of every combination possible from the above lists. If the list repeats, as in [[2,3],[5,6],[11,12],[11,12]] would not be good, the first combination would be [[2,3],[5,6],[11,12],[13,14]]. This isnt a great start but I know it isnt hard but my programming skills arent strong.</p> <p>The final list would look like</p> <pre><code>[[[2,3],[5,6],[11,12],[13,14]],[[2,3],[5,6],[11,12],[15,16]],[[2,3],[5,6],[11,12],[17,18]],...,[[3,4],[9,10],[15,16],[17,18]]] </code></pre> <p>I would also like to add the 1st number of each list in each individual list and add them together. [[31],[33],[35],...,[44]]</p>
-1
2016-09-15T09:46:17Z
39,508,432
<p>You may want to use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> to solve this.</p> <p>Assuming you want combinations from <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code> in groups of 4 (and based on your expected output I think you have a typo in your <code>c1</code> which I'm calling <code>d</code>, adapt as necessary):</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; a = [[2, 3], [3, 4]] # are you sure this isn't actually [[1, 2], [3, 4]]? &gt;&gt;&gt; b = [[5, 6], [7, 8], [9, 10]] &gt;&gt;&gt; c = [[11, 12], [13, 14]] &gt;&gt;&gt; d = [[15, 16], [17, 18]] &gt;&gt;&gt; &gt;&gt;&gt; list(itertools.product(a, b, c, d)) [([2, 3], [5, 6], [11, 12], [15, 16]), # pretty printed for readability ([2, 3], [5, 6], [11, 12], [17, 18]), ([2, 3], [5, 6], [13, 14], [15, 16]), ([2, 3], [5, 6], [13, 14], [17, 18]), ... ([3, 4], [9, 10], [13, 14], [17, 18])] &gt;&gt;&gt; len(list(itertools.product(a, b, c, d))) 24 </code></pre> <p>And btw, when you're trying to create a list of int's, instead of:</p> <pre><code>listr=[] for number in range(96): listr.append(number) </code></pre> <p>you only need to do:</p> <pre><code>listr = range(96) # in Python2 # or listr = list(range(96)) # in Python3 </code></pre>
2
2016-09-15T10:10:14Z
[ "python", "list", "append" ]
pandas: rename axis in df
39,508,001
<p>I have a df which looks like this:</p> <pre><code> Column 1 Channel Apples 1.0 Oranges 2.0 Puppies 3.0 Ducks 4.0 </code></pre> <p>I would like to rename the axis so it looks like this:</p> <pre><code>Channel Column 1 Apples 1.0 Oranges 2.0 Puppies 3.0 Ducks 4.0 </code></pre> <p>I tried these but got the same error msg:</p> <pre><code>merged_df.rename_axis("Channel") merged_df.rename_axis("Channel", axis='columns') TypeError: 'str' object is not callable </code></pre>
1
2016-09-15T09:48:49Z
39,509,360
<p>This is kind of a hack to get you what you eventually wanted it to look like.</p> <pre><code>df = pd.read_csv(data, sep='\s{2,}', index_col='Channel', engine='python') df </code></pre> <p><a href="http://i.stack.imgur.com/CLcCU.png" rel="nofollow"><img src="http://i.stack.imgur.com/CLcCU.png" alt="Image"></a></p> <pre><code>df_excel_format = df.rename_axis('Channel', axis=1) del(df_excel_format.index.name) df_excel_format </code></pre> <p><a href="http://i.stack.imgur.com/Fpif7.png" rel="nofollow"><img src="http://i.stack.imgur.com/Fpif7.png" alt="Image"></a></p>
1
2016-09-15T10:57:55Z
[ "python", "pandas", "dataframe" ]
Pandas: Set variable to value in cell, if another cell on same row contains string
39,508,021
<p>Let's say my Pandas <code>DataFrame</code> contains the following:</p> <pre><code>Row Firstname Middlename Lastname … 10 Roy G. Biv 11 Cnyder M. Uk 12 Pan T. One … </code></pre> <p>If a cell in <code>["Lastname"]</code> contains <code>"Biv"</code>, I would like to set the Python variable <code>first_name =</code> to <code>"Roy"</code>.</p> <p>I've been away from Pandas for a while and am unsure on the right way to accomplish this. I've looked at ways to combine <code>df.iloc</code>/<code>df.loc</code> etc with <code>df.at/df.where</code> and <code>str.contains</code> but have to admit I'm kind of lost on the proper way to put the conditional together with setting the variable.</p> <p>In (poor, <strong>incorrect</strong>) pseudo-code, I'm looking for:</p> <p><code>first_name = df["Firstname"][np.where([df["Lastname"].str.contains("Biv") ...</code></p>
1
2016-09-15T09:49:38Z
39,508,189
<p>If you want just the scalar value then you can access the first value in the result array and assign this:</p> <pre><code>firstname = df.loc[df['Lastname'].str.contains('Biv'), 'Firstname'][0] </code></pre> <p>Note that really you should check if it's not empty though:</p> <pre><code>if len(df.loc[df['Lastname'].str.contains('Biv'), 'Firstname']) &gt; 0: firstname = df.loc[df['Lastname'].str.contains('Biv'), 'Firstname'][0] </code></pre>
1
2016-09-15T09:57:56Z
[ "python", "pandas" ]
Use scrapy as an item generator
39,508,095
<p>I have an existing script (main.py) that requires data to be scraped.</p> <p>I started a scrapy project for retrieving this data. Now, is there any way main.py can retrieve the data from scrapy as an Item generator, rather than persisting data using the Item pipeline?</p> <p>Something like this would be really convenient, but I couldn't find out how to do it, if it's feasible at all.</p> <pre><code>for item in scrapy.process(): </code></pre> <p>I found a potential solution there: <a href="https://tryolabs.com/blog/2011/09/27/calling-scrapy-python-script/" rel="nofollow">https://tryolabs.com/blog/2011/09/27/calling-scrapy-python-script/</a>, using multithreading's queues. </p> <p>Even though I understand this behaviour is not compatible with distributed crawling, which is what Scrapy is intended for, I'm still a little surprised that you wouldn't have this feature available for smaller projects.</p>
0
2016-09-15T09:53:20Z
39,508,698
<p>You could send json data out from the crawler and grab the results. It can be done as follows:</p> <p>Having the spider:</p> <pre><code>class MySpider(scrapy.Spider): # some attributes accomulated=[] def parse(self, response): # do your logic here page_text = response.xpath('//text()').extract() for text in page_text: if conditionsAreOk( text ): self.accomulated.append(text) def closed( self, reason ): # call when the crawler process ends print JSON.dumps(self.accomulated) </code></pre> <p>Write a runner.py script like:</p> <pre><code>import sys from twisted.internet import reactor import scrapy from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.project import get_project_settings from spiders import MySpider def main(argv): url = argv[0] configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s', 'LOG_ENABLED':False }) runner = CrawlerRunner( get_project_settings() ) d = runner.crawl( MySpider, url=url) # For Multiple in the same process # # runner.crawl('craw') # runner.crawl('craw2') # d = runner.join() d.addBoth(lambda _: reactor.stop()) reactor.run() # the script will block here until the crawling is finished if __name__ == "__main__": main(sys.argv[1:]) </code></pre> <p>And then call it from your main.py as:</p> <pre><code>import json, subprocess, sys, time def main(argv): # urlArray has http:// or https:// like urls for url in urlArray: p = subprocess.Popen(['python', 'runner.py', url ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() # do something with your data print out print json.loads(out) # This just helps to watch logs time.sleep(0.5) if __name__ == "__main__": main(sys.argv[1:]) </code></pre> <p><strong>Note</strong> </p> <p>This is not the best way of using Scrapy as you know, but for fast results which do not require a complex post processing, this solution can provide what you need.</p> <p>I hope it helps.</p>
0
2016-09-15T10:23:04Z
[ "python", "scrapy", "scrapy-pipeline" ]
Use scrapy as an item generator
39,508,095
<p>I have an existing script (main.py) that requires data to be scraped.</p> <p>I started a scrapy project for retrieving this data. Now, is there any way main.py can retrieve the data from scrapy as an Item generator, rather than persisting data using the Item pipeline?</p> <p>Something like this would be really convenient, but I couldn't find out how to do it, if it's feasible at all.</p> <pre><code>for item in scrapy.process(): </code></pre> <p>I found a potential solution there: <a href="https://tryolabs.com/blog/2011/09/27/calling-scrapy-python-script/" rel="nofollow">https://tryolabs.com/blog/2011/09/27/calling-scrapy-python-script/</a>, using multithreading's queues. </p> <p>Even though I understand this behaviour is not compatible with distributed crawling, which is what Scrapy is intended for, I'm still a little surprised that you wouldn't have this feature available for smaller projects.</p>
0
2016-09-15T09:53:20Z
39,517,256
<p>You can do it this way in a Twisted or Tornado app:</p> <pre><code>import collections from twisted.internet.defer import Deferred from scrapy.crawler import Crawler from scrapy import signals def scrape_items(crawler_runner, crawler_or_spidercls, *args, **kwargs): """ Start a crawl and return an object (ItemCursor instance) which allows to retrieve scraped items and wait for items to become available. Example: .. code-block:: python @inlineCallbacks def f(): runner = CrawlerRunner() async_items = scrape_items(runner, my_spider) while (yield async_items.fetch_next): item = async_items.next_item() # ... # ... This convoluted way to write a loop should become unnecessary in Python 3.5 because of ``async for``. """ # this requires scrapy &gt;= 1.1rc1 crawler = crawler_runner.create_crawler(crawler_or_spidercls) # for scrapy &lt; 1.1rc1 the following code is needed: # crawler = crawler_or_spidercls # if not isinstance(crawler_or_spidercls, Crawler): # crawler = crawler_runner._create_crawler(crawler_or_spidercls) d = crawler_runner.crawl(crawler, *args, **kwargs) return ItemCursor(d, crawler) class ItemCursor(object): def __init__(self, crawl_d, crawler): self.crawl_d = crawl_d self.crawler = crawler crawler.signals.connect(self._on_item_scraped, signals.item_scraped) crawl_d.addCallback(self._on_finished) crawl_d.addErrback(self._on_error) self.closed = False self._items_available = Deferred() self._items = collections.deque() def _on_item_scraped(self, item): self._items.append(item) self._items_available.callback(True) self._items_available = Deferred() def _on_finished(self, result): self.closed = True self._items_available.callback(False) def _on_error(self, failure): self.closed = True self._items_available.errback(failure) @property def fetch_next(self): """ A Deferred used with ``inlineCallbacks`` or ``gen.coroutine`` to asynchronously retrieve the next item, waiting for an item to be crawled if necessary. Resolves to ``False`` if the crawl is finished, otherwise :meth:`next_item` is guaranteed to return an item (a dict or a scrapy.Item instance). """ if self.closed: # crawl is finished d = Deferred() d.callback(False) return d if self._items: # result is ready d = Deferred() d.callback(True) return d # We're active, but item is not ready yet. Return a Deferred which # resolves to True if item is scraped or to False if crawl is stopped. return self._items_available def next_item(self): """Get a document from the most recently fetched batch, or ``None``. See :attr:`fetch_next`. """ if not self._items: return None return self._items.popleft() </code></pre> <p>The main idea is to listen to <a href="http://doc.scrapy.org/en/latest/topics/signals.html#item-scraped" rel="nofollow">item_scraped</a> signal, and then wrap it to an object with a nicer API.</p> <p>Note that you need an event loop in your main.py script for this to work; the example above works with twisted.defer.inlineCallbacks or tornado.gen.coroutine.</p>
0
2016-09-15T17:43:47Z
[ "python", "scrapy", "scrapy-pipeline" ]
Python list from .txt file
39,508,166
<p>I`m trying to create primitive dictionary (or list) in Python with basic functions that I learned from book (Mark Summerfield).</p> <p>Here is my question.</p> <p>All works as I need, but I had a problem with writing strings to the file.</p> <p>This is a piece of my code:</p> <pre><code> word = input("New word is: ") #adding new word if word: word.strip() #erasing new str from any symbols x = len(word) numeration = str(count) + ". " word = word[:0] + numeration + word[0:] # =to sort as list word = word[:x] + ",\n" # =adding shift to the end of str file = open("test.txt", "a") # =wriing to the file file.write(word) file.close() count += 1 </code></pre> <p>Problem shows itself in the output:</p> <pre><code>======================== RESTART: /home/z177/test.py ======================== Type word to add word, type nothing to read dict, ^D\Z to quit New word is: currently raining New word is: currently not New word is: 1. currently rain, 2. currently , </code></pre> <p>It is overwriting the last 3 symbols in the string. </p> <p>I've solved this problem by replacing </p> <pre><code>word[:x] + ",\n" </code></pre> <p>with </p> <pre><code>word + ",\n" </code></pre> <p>I am still interested why the code is replacing these 3 symbols when I add new symbols to the end of the string. </p> <p>Can you explain this?</p>
3
2016-09-15T09:57:04Z
39,508,466
<p>The issue is created in this line:</p> <pre><code>word = word[:x] + ",\n" # =adding shift to the end of str </code></pre> <p>You need to remember that variable <code>word</code> isn't contain your word any more. You have there for example "0. word" there.</p> <p>So you have to update <code>x</code> - line count to get correct results in your file.</p>
0
2016-09-15T10:11:50Z
[ "python" ]
Python list from .txt file
39,508,166
<p>I`m trying to create primitive dictionary (or list) in Python with basic functions that I learned from book (Mark Summerfield).</p> <p>Here is my question.</p> <p>All works as I need, but I had a problem with writing strings to the file.</p> <p>This is a piece of my code:</p> <pre><code> word = input("New word is: ") #adding new word if word: word.strip() #erasing new str from any symbols x = len(word) numeration = str(count) + ". " word = word[:0] + numeration + word[0:] # =to sort as list word = word[:x] + ",\n" # =adding shift to the end of str file = open("test.txt", "a") # =wriing to the file file.write(word) file.close() count += 1 </code></pre> <p>Problem shows itself in the output:</p> <pre><code>======================== RESTART: /home/z177/test.py ======================== Type word to add word, type nothing to read dict, ^D\Z to quit New word is: currently raining New word is: currently not New word is: 1. currently rain, 2. currently , </code></pre> <p>It is overwriting the last 3 symbols in the string. </p> <p>I've solved this problem by replacing </p> <pre><code>word[:x] + ",\n" </code></pre> <p>with </p> <pre><code>word + ",\n" </code></pre> <p>I am still interested why the code is replacing these 3 symbols when I add new symbols to the end of the string. </p> <p>Can you explain this?</p>
3
2016-09-15T09:57:04Z
39,508,470
<p>The length of word has increased after inserting <code>numeration</code>, so <code>x</code> holds the value of the old length before the update. You should move the line where <code>x</code> is assigned after the update:</p> <pre><code>numeration = str(count) + ". " word = numeration + word[0:] # length of word changes here x = len(word) word = word[:x] + ",\n" </code></pre> <p>Or stick to using <code>word = word + ",\n"</code> which is less verbose and still does the same thing.</p> <hr> <p>The entire logic can however be simplified into the following:</p> <pre><code>word = numeration + word + ',\n' </code></pre>
0
2016-09-15T10:12:02Z
[ "python" ]
Python list from .txt file
39,508,166
<p>I`m trying to create primitive dictionary (or list) in Python with basic functions that I learned from book (Mark Summerfield).</p> <p>Here is my question.</p> <p>All works as I need, but I had a problem with writing strings to the file.</p> <p>This is a piece of my code:</p> <pre><code> word = input("New word is: ") #adding new word if word: word.strip() #erasing new str from any symbols x = len(word) numeration = str(count) + ". " word = word[:0] + numeration + word[0:] # =to sort as list word = word[:x] + ",\n" # =adding shift to the end of str file = open("test.txt", "a") # =wriing to the file file.write(word) file.close() count += 1 </code></pre> <p>Problem shows itself in the output:</p> <pre><code>======================== RESTART: /home/z177/test.py ======================== Type word to add word, type nothing to read dict, ^D\Z to quit New word is: currently raining New word is: currently not New word is: 1. currently rain, 2. currently , </code></pre> <p>It is overwriting the last 3 symbols in the string. </p> <p>I've solved this problem by replacing </p> <pre><code>word[:x] + ",\n" </code></pre> <p>with </p> <pre><code>word + ",\n" </code></pre> <p>I am still interested why the code is replacing these 3 symbols when I add new symbols to the end of the string. </p> <p>Can you explain this?</p>
3
2016-09-15T09:57:04Z
39,508,476
<p>Your problem is that you set <code>x</code> to be the length of the input word, but then add <code>numeration</code> to the string, making it several characters longer (three characters, in the case of a single-digit <code>count</code>). If you were to change</p> <pre><code>word = word[:x] + ",\n" # =adding shift to the end of str </code></pre> <p>to</p> <pre><code>word = word[:len(word)] + ",\n" </code></pre> <p>You should get the correct result.</p> <p>Unrelated to your issue, the code you presented is very un-Pythonic, and when you've mastered the logic of the program I'd take a look at refactoring, using <a href="http://www.pythonforbeginners.com/files/with-statement-in-python" rel="nofollow"><code>with open('test.txt', 'a') as file:</code></a> over the explicit <code>file.close()</code> and using <a href="https://docs.python.org/3.3/library/stdtypes.html#str.format" rel="nofollow"><code>str.format()</code></a> over concatenation.</p>
0
2016-09-15T10:12:27Z
[ "python" ]
BeautifulSoup use unique CSS Selector
39,508,252
<p>From this <a href="https://www.placetel.de/status" rel="nofollow">page</a>, I need to get the status from "Anbindung an das Telefonnetz". </p> <p>I identified 2 ways to get it: </p> <ol> <li>If the status contains the sentence "Das System arbeitet einwandfrei";</li> <li>If the color of the background is green. </li> </ol> <p>I have chosen to go with the first option. </p> <p>I use Python/BeautifulSoup to scrape the page. The thing is, there is no unique id/class or whatsoever to get this element. <br> I then decided to use the CSS selector of this particular element, which is the following: </p> <pre><code>div.system-item:nth-child(2) &gt; div:nth-child(1) &gt; p:nth-child(3) </code></pre> <p>And use it like this: </p> <pre><code>print(page.select("div.system-item:nth-child(2) &gt; div:nth-child(1) &gt; p:nth-child(3)")) </code></pre> <p>However, the only thing I get is an empty element (<code>[]</code>). </p> <p>What could I try more to get this particular element? </p> <p><strong>EDIT</strong> <br> As some of you recommend it, here is the un-complete HTML source of the page.<br>. But to be practical, i recommend you to just take a look yourself at the <a href="https://www.placetel.de/status" rel="nofollow">page</a></p> <pre><code>&lt;!doctype html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Aktueller Status | Placetel&lt;/title&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=Edge"&gt; &lt;meta name="msvalidate.01" content="756F6E40DD887A659CE83E5A92FFBB62"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta name="generator" content="Kirby 2.3.2"&gt; &lt;meta name="description" content="Placetel Systemstatus: Erfahren Sie mehr &amp;uuml;ber den aktuellen Status der Placetel Telefonanlage."&gt; &lt;meta name="keywords" content=""&gt; &lt;meta name="robots" content="index,follow,noodp,noydir"&gt; &lt;link rel="canonical" href="https://www.placetel.de/status"&gt; &lt;link rel="publisher" href="https://plus.google.com/b/111027512373770716962/111027512373770716962/posts"&gt; &lt;link rel="shortcut icon" href="/favicon.ico"&gt; &lt;link rel="apple-touch-icon" href="/apple-touch-icon.png"&gt; &lt;meta name="msapplication-TileColor" content="#0e70b9"&gt; &lt;meta name="msapplication-TileImage" content="/ms-tile-icon.png"&gt; &lt;meta name="theme-color" content="#0e70b9"&gt; &lt;script src="//use.typekit.net/rnw8lad.js"&gt;&lt;/script&gt; &lt;script&gt;try { Typekit.load({ async: true }); } catch (e) {}&lt;/script&gt; &lt;link rel="stylesheet" href="https://www.placetel.de/assets/dist/css/main.css"&gt; &lt;script src="https://www.placetel.de/assets/dist/js/modernizr.js"&gt;&lt;/script&gt; &lt;link rel="dns-prefetch" href="//app.marketizator.com"/&gt; &lt;script&gt; var _mktz = _mktz || []; _mktz.cc_domain = 'placetel.de'; &lt;/script&gt; &lt;script type="text/javascript" src="//d2tgfbvjf3q6hn.cloudfront.net/js/o17fe41.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body id="🚀" class="page page-template-page-sections page-uid-status"&gt; &lt;script&gt; var gaProperty = 'UA-17631409-3'; var disableStr = 'ga-disable-' + gaProperty; if (document.cookie.indexOf(disableStr + '=true') &gt; -1) { window[disableStr] = true; } function gaOptout() { document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/'; window[disableStr] = true; } &lt;/script&gt; &lt;!-- Google Tag Manager --&gt; &lt;noscript&gt;&lt;iframe src="//www.googletagmanager.com/ns.html?id=GTM-KDNGCC" height="0" width="0" style="display:none;visibility:hidden"&gt;&lt;/iframe&gt;&lt;/noscript&gt; &lt;script&gt;(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-KDNGCC');&lt;/script&gt; &lt;!-- End Google Tag Manager --&gt; &lt;header class="header header-condensed" id="header"&gt; &lt;div class="container-fluid"&gt; &lt;nav class="navigation navigation-top"&gt; &lt;ul&gt; &lt;li class=" "&gt; &lt;a title="Unternehmen" href="https://www.placetel.de/unternehmen"&gt; &lt;span&gt;Unternehmen&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=" "&gt; &lt;a title="Partner werden" href="https://www.placetel.de/partner"&gt; &lt;span&gt;Partner werden&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=" "&gt; &lt;a title="Support" href="https://www.placetel.de/support"&gt; &lt;span&gt;Support&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=" "&gt; &lt;a title="Suche" href="javascript:modal('search')"&gt; &lt;span&gt;Suche&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="navigation-top-support"&gt; &lt;a href="https://www.placetel.de/support"&gt; &lt;svg class="svg-phone"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-phone"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;span&gt;0221 29 191 999&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="navigation-top-login"&gt; &lt;a href="https://app.placetel.de/account/login"&gt; &lt;span&gt;Login&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div class="container-fluid"&gt; &lt;a class="site-logo" href="https://www.placetel.de"&gt; &lt;svg class="svg-placetel-logo"&gt;&lt;title&gt;Placetel&lt;/title&gt; &lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-placetel-logo"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/a&gt; &lt;nav class="navigation navigation-main" id="navigation-main"&gt; &lt;ul&gt; &lt;li class="has-sub-navigation"&gt; &lt;a title="Telefonanlage" href="https://www.placetel.de/telefonanlage" class=""&gt; &lt;span&gt;Telefonanlage&lt;/span&gt; &lt;svg class="svg-arrow"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-arrow"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/a&gt; &lt;nav class="sub-navigation"&gt; &lt;ul&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage"&gt; Vorteile &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/preise"&gt; Preise &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/funktionen"&gt; Funktionen &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/unified-communication"&gt; Unified Communication &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/funktionsweise"&gt; Wie funktioniert es? &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/isdn-abschaltung"&gt; ISDN-Abschaltung &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/faq"&gt; FAQ &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a title="Trunking" href="https://www.placetel.de/sip-trunking" class=""&gt; &lt;span&gt;Trunking&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a title="Mobilfunk" href="https://www.placetel.de/mobilfunk" class=""&gt; &lt;span&gt;Mobilfunk&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="navigation-main-shop"&gt; &lt;a title="Endger&amp;auml;te-Shop" href="/shop/" class=""&gt; &lt;span&gt;Endger&amp;auml;te-Shop&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="visible-xs-block visible-sm-block"&gt; &lt;a title="Support" href="https://www.placetel.de/support" class=""&gt; &lt;span&gt;Support&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="visible-xs-block visible-sm-block"&gt; &lt;a title="Partner" href="https://www.placetel.de/partner" class=""&gt; &lt;span&gt;Partner&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="has-sub-navigation visible-xs-block visible-sm-block"&gt; &lt;a title="Unternehmen" href="https://www.placetel.de/unternehmen" class=""&gt; &lt;span&gt;Unternehmen&lt;/span&gt; &lt;svg class="svg-arrow"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-arrow"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/a&gt; &lt;nav class="sub-navigation"&gt; &lt;ul&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen"&gt; &amp;Uuml;ber uns &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/technologie"&gt; Technologie &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/jobs"&gt; Jobs &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/events"&gt; Events &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/presse"&gt; Presse &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/kontakt"&gt; Kontakt &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/li&gt; &lt;li class="navigation-main-register"&gt; &lt;a title="Kostenlos testen!" href="javascript:modal('register')" class="btn"&gt; &lt;span&gt;Kostenlos testen!&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;a class="site-navigation-toggle" id="hotdog"&gt; &lt;i&gt; &lt;span&gt;&lt;/span&gt; &lt;/i&gt; Menü &lt;/a&gt; &lt;/div&gt; &lt;/header&gt; &lt;section class="section section-full section-full-section-einleitung-text section-full-normal"&gt; &lt;div class="container-fluid typography typography-dark"&gt; &lt;h2 class="section-full-title"&gt;Der Placetel System Status&lt;/h2&gt; &lt;h3 class="section-full-subtitle"&gt;Jeden Tag einen Grund zur Freude.&lt;/h3&gt; &lt;p&gt;Wir bei Placetel haben ein Lieblingswort: „läuft“. Der Grund: Ihre Placetel Telefonanlage funktioniert nämlich immer. Darüber freuen wir uns natürlich riesig. Da aber erst eine geteilte Freude eine richtige Freude ist, haben wir Ihnen diese Statusseite eingerichtet. Diese Seite informiert Sie jeden Tag über den einwandfreien Status Ihrer Anlage.&lt;br /&gt; Und falls etwas mal nicht so perfekt funktionieren sollte wie gewohnt, können Sie uns den Fehler gern melden.&lt;/p&gt; &lt;/div&gt; &lt;style&gt; .section-full-section-einleitung-text { background-color: ; } &lt;/style&gt; &lt;/section&gt; &lt;section class="section section-system"&gt; &lt;a class="btn btn-primary btn-transparent btn-with-icon" href="javascript:location.reload();"&gt; &lt;svg class="svg-refresh"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-refresh"&gt;&lt;/use&gt;&lt;/svg&gt; Status aktualisieren &lt;/a&gt; &lt;div class="system flex-grid typography typography-light"&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; System &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Anbindung an das Telefonnetz &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Faxsystem &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Konferenzsystem &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Features und Optionen &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2016-09-15T10:01:07Z
39,509,270
<p>As far as I know <a href="http://stackoverflow.com/a/24720912/4241180">nth-of-child</a> is still not implemented in <code>BeautifulSoup4</code>. Also if you investigate the website's CSS (namely <code>_system.scss</code> file), you'll find out that there are 3 statuses:</p> <ol> <li><code>system-item-green</code> </li> <li><code>system-item-yellow</code> </li> <li><code>system-item-red</code></li> </ol> <p>So you may want to slightly change your code to be like this:</p> <pre><code>import requests from bs4 import BeautifulSoup as BS url = 'https://www.placetel.de/status' headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0' } source = requests.get(url, headers=headers) soup = BS(source.text, 'html.parser') status = soup.select("div.system-item")[1].attrs['class'] if 'system-item-green' in status: print("It works!") elif 'system-item-yellow' in status: print("Something's slightly wrong") elif 'system-item-red' in status: print("Does not work") else: print("Has someone changed page's markup?") </code></pre>
1
2016-09-15T10:53:04Z
[ "python", "html", "css", "beautifulsoup" ]
BeautifulSoup use unique CSS Selector
39,508,252
<p>From this <a href="https://www.placetel.de/status" rel="nofollow">page</a>, I need to get the status from "Anbindung an das Telefonnetz". </p> <p>I identified 2 ways to get it: </p> <ol> <li>If the status contains the sentence "Das System arbeitet einwandfrei";</li> <li>If the color of the background is green. </li> </ol> <p>I have chosen to go with the first option. </p> <p>I use Python/BeautifulSoup to scrape the page. The thing is, there is no unique id/class or whatsoever to get this element. <br> I then decided to use the CSS selector of this particular element, which is the following: </p> <pre><code>div.system-item:nth-child(2) &gt; div:nth-child(1) &gt; p:nth-child(3) </code></pre> <p>And use it like this: </p> <pre><code>print(page.select("div.system-item:nth-child(2) &gt; div:nth-child(1) &gt; p:nth-child(3)")) </code></pre> <p>However, the only thing I get is an empty element (<code>[]</code>). </p> <p>What could I try more to get this particular element? </p> <p><strong>EDIT</strong> <br> As some of you recommend it, here is the un-complete HTML source of the page.<br>. But to be practical, i recommend you to just take a look yourself at the <a href="https://www.placetel.de/status" rel="nofollow">page</a></p> <pre><code>&lt;!doctype html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Aktueller Status | Placetel&lt;/title&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=Edge"&gt; &lt;meta name="msvalidate.01" content="756F6E40DD887A659CE83E5A92FFBB62"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta name="generator" content="Kirby 2.3.2"&gt; &lt;meta name="description" content="Placetel Systemstatus: Erfahren Sie mehr &amp;uuml;ber den aktuellen Status der Placetel Telefonanlage."&gt; &lt;meta name="keywords" content=""&gt; &lt;meta name="robots" content="index,follow,noodp,noydir"&gt; &lt;link rel="canonical" href="https://www.placetel.de/status"&gt; &lt;link rel="publisher" href="https://plus.google.com/b/111027512373770716962/111027512373770716962/posts"&gt; &lt;link rel="shortcut icon" href="/favicon.ico"&gt; &lt;link rel="apple-touch-icon" href="/apple-touch-icon.png"&gt; &lt;meta name="msapplication-TileColor" content="#0e70b9"&gt; &lt;meta name="msapplication-TileImage" content="/ms-tile-icon.png"&gt; &lt;meta name="theme-color" content="#0e70b9"&gt; &lt;script src="//use.typekit.net/rnw8lad.js"&gt;&lt;/script&gt; &lt;script&gt;try { Typekit.load({ async: true }); } catch (e) {}&lt;/script&gt; &lt;link rel="stylesheet" href="https://www.placetel.de/assets/dist/css/main.css"&gt; &lt;script src="https://www.placetel.de/assets/dist/js/modernizr.js"&gt;&lt;/script&gt; &lt;link rel="dns-prefetch" href="//app.marketizator.com"/&gt; &lt;script&gt; var _mktz = _mktz || []; _mktz.cc_domain = 'placetel.de'; &lt;/script&gt; &lt;script type="text/javascript" src="//d2tgfbvjf3q6hn.cloudfront.net/js/o17fe41.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body id="🚀" class="page page-template-page-sections page-uid-status"&gt; &lt;script&gt; var gaProperty = 'UA-17631409-3'; var disableStr = 'ga-disable-' + gaProperty; if (document.cookie.indexOf(disableStr + '=true') &gt; -1) { window[disableStr] = true; } function gaOptout() { document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/'; window[disableStr] = true; } &lt;/script&gt; &lt;!-- Google Tag Manager --&gt; &lt;noscript&gt;&lt;iframe src="//www.googletagmanager.com/ns.html?id=GTM-KDNGCC" height="0" width="0" style="display:none;visibility:hidden"&gt;&lt;/iframe&gt;&lt;/noscript&gt; &lt;script&gt;(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-KDNGCC');&lt;/script&gt; &lt;!-- End Google Tag Manager --&gt; &lt;header class="header header-condensed" id="header"&gt; &lt;div class="container-fluid"&gt; &lt;nav class="navigation navigation-top"&gt; &lt;ul&gt; &lt;li class=" "&gt; &lt;a title="Unternehmen" href="https://www.placetel.de/unternehmen"&gt; &lt;span&gt;Unternehmen&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=" "&gt; &lt;a title="Partner werden" href="https://www.placetel.de/partner"&gt; &lt;span&gt;Partner werden&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=" "&gt; &lt;a title="Support" href="https://www.placetel.de/support"&gt; &lt;span&gt;Support&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=" "&gt; &lt;a title="Suche" href="javascript:modal('search')"&gt; &lt;span&gt;Suche&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="navigation-top-support"&gt; &lt;a href="https://www.placetel.de/support"&gt; &lt;svg class="svg-phone"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-phone"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;span&gt;0221 29 191 999&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="navigation-top-login"&gt; &lt;a href="https://app.placetel.de/account/login"&gt; &lt;span&gt;Login&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div class="container-fluid"&gt; &lt;a class="site-logo" href="https://www.placetel.de"&gt; &lt;svg class="svg-placetel-logo"&gt;&lt;title&gt;Placetel&lt;/title&gt; &lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-placetel-logo"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/a&gt; &lt;nav class="navigation navigation-main" id="navigation-main"&gt; &lt;ul&gt; &lt;li class="has-sub-navigation"&gt; &lt;a title="Telefonanlage" href="https://www.placetel.de/telefonanlage" class=""&gt; &lt;span&gt;Telefonanlage&lt;/span&gt; &lt;svg class="svg-arrow"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-arrow"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/a&gt; &lt;nav class="sub-navigation"&gt; &lt;ul&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage"&gt; Vorteile &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/preise"&gt; Preise &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/funktionen"&gt; Funktionen &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/unified-communication"&gt; Unified Communication &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/funktionsweise"&gt; Wie funktioniert es? &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/isdn-abschaltung"&gt; ISDN-Abschaltung &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/telefonanlage/faq"&gt; FAQ &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a title="Trunking" href="https://www.placetel.de/sip-trunking" class=""&gt; &lt;span&gt;Trunking&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a title="Mobilfunk" href="https://www.placetel.de/mobilfunk" class=""&gt; &lt;span&gt;Mobilfunk&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="navigation-main-shop"&gt; &lt;a title="Endger&amp;auml;te-Shop" href="/shop/" class=""&gt; &lt;span&gt;Endger&amp;auml;te-Shop&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="visible-xs-block visible-sm-block"&gt; &lt;a title="Support" href="https://www.placetel.de/support" class=""&gt; &lt;span&gt;Support&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="visible-xs-block visible-sm-block"&gt; &lt;a title="Partner" href="https://www.placetel.de/partner" class=""&gt; &lt;span&gt;Partner&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="has-sub-navigation visible-xs-block visible-sm-block"&gt; &lt;a title="Unternehmen" href="https://www.placetel.de/unternehmen" class=""&gt; &lt;span&gt;Unternehmen&lt;/span&gt; &lt;svg class="svg-arrow"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-arrow"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/a&gt; &lt;nav class="sub-navigation"&gt; &lt;ul&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen"&gt; &amp;Uuml;ber uns &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/technologie"&gt; Technologie &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/jobs"&gt; Jobs &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/events"&gt; Events &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/presse"&gt; Presse &lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a href="https://www.placetel.de/unternehmen/kontakt"&gt; Kontakt &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/li&gt; &lt;li class="navigation-main-register"&gt; &lt;a title="Kostenlos testen!" href="javascript:modal('register')" class="btn"&gt; &lt;span&gt;Kostenlos testen!&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;a class="site-navigation-toggle" id="hotdog"&gt; &lt;i&gt; &lt;span&gt;&lt;/span&gt; &lt;/i&gt; Menü &lt;/a&gt; &lt;/div&gt; &lt;/header&gt; &lt;section class="section section-full section-full-section-einleitung-text section-full-normal"&gt; &lt;div class="container-fluid typography typography-dark"&gt; &lt;h2 class="section-full-title"&gt;Der Placetel System Status&lt;/h2&gt; &lt;h3 class="section-full-subtitle"&gt;Jeden Tag einen Grund zur Freude.&lt;/h3&gt; &lt;p&gt;Wir bei Placetel haben ein Lieblingswort: „läuft“. Der Grund: Ihre Placetel Telefonanlage funktioniert nämlich immer. Darüber freuen wir uns natürlich riesig. Da aber erst eine geteilte Freude eine richtige Freude ist, haben wir Ihnen diese Statusseite eingerichtet. Diese Seite informiert Sie jeden Tag über den einwandfreien Status Ihrer Anlage.&lt;br /&gt; Und falls etwas mal nicht so perfekt funktionieren sollte wie gewohnt, können Sie uns den Fehler gern melden.&lt;/p&gt; &lt;/div&gt; &lt;style&gt; .section-full-section-einleitung-text { background-color: ; } &lt;/style&gt; &lt;/section&gt; &lt;section class="section section-system"&gt; &lt;a class="btn btn-primary btn-transparent btn-with-icon" href="javascript:location.reload();"&gt; &lt;svg class="svg-refresh"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-refresh"&gt;&lt;/use&gt;&lt;/svg&gt; Status aktualisieren &lt;/a&gt; &lt;div class="system flex-grid typography typography-light"&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; System &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Anbindung an das Telefonnetz &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Faxsystem &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Konferenzsystem &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="system-item system-item-green flex-grid-item"&gt; &lt;div class="system-item-inner"&gt; &lt;h6&gt; Features und Optionen &lt;/h6&gt; &lt;i&gt; &lt;svg class="svg-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-dots"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-dots"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;svg class="svg-not-included"&gt;&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.placetel.de/assets/dist/sprites/svg/sprite.1471515912.svg#svg-not-included"&gt;&lt;/use&gt;&lt;/svg&gt; &lt;/i&gt; &lt;p&gt; Das System arbeitet einwandfrei&lt;br&gt; 11:10 Uhr &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2016-09-15T10:01:07Z
39,509,738
<p>You can use the text to find the h6 for <code>Anbindung an das Telefonnetz</code> and get the p sibling:</p> <pre><code>import requests import re r = requests.get("https://www.placetel.de/status").content soup = BeautifulSoup(r, "lxml") h6 = soup.find("h6", text=re.compile(ur"Anbindung an das Telefonnetz", re.I)) if h6: print(h6.find_next_sibling("p")) </code></pre> <p>If you want full css3 selector support you can use <em>lxml's</em> <a href="http://lxml.de/cssselect.html" rel="nofollow">cssselect</a>:</p> <pre><code>from lxml import html tree = html.fromstring(r) print(tree.cssselect("div.system-item:nth-child(2) &gt; div:nth-child(1) &gt; p:nth-child(3)") </code></pre> <p>You can also just search by the text so if the h6 turned to a h5 or any other tag it would make no odds:</p> <pre><code>match = soup.find(text=re.compile(ur"Anbindung an das Telefonnetz", re.I)) if match: print(match.parent.find_next_sibling("p").text) </code></pre> <p>You could use the outer div to localise the search for the text, bs4 is pretty flexible. Just selecting all the <code>div.system-item</code> and indexing would break if the order changed and you would not know as there would be no error so looking for the text is probably actually a safer approach.</p>
1
2016-09-15T11:16:56Z
[ "python", "html", "css", "beautifulsoup" ]
reading all the file content in directory
39,508,469
<p>I have directory <code>poem</code> which contains 50 files and I want to read them all.</p> <pre><code>for file in os.listdir("/home/ubuntu/Desktop/temp/poem"): print file f = open(file, 'r') print f.read() f.close() </code></pre> <p>This code reads file name of all the files in directory. But it fails at </p> <pre><code>f = open(file, 'r') </code></pre> <p>saying </p> <pre><code>IOError: [Errno 2] No such file or directory: '32' </code></pre>
0
2016-09-15T10:11:59Z
39,508,529
<p><code>os.listdir</code> only returns filenames, to get the full path you need to join that filename with the folder you're reading:</p> <pre><code>folder = "/home/ubuntu/Desktop/temp/poem" for file in os.listdir(folder): print file filepath = os.path.join(folder, file) f = open(filepath, 'r') print f.read() f.close() </code></pre>
5
2016-09-15T10:14:45Z
[ "python", "io" ]
reading all the file content in directory
39,508,469
<p>I have directory <code>poem</code> which contains 50 files and I want to read them all.</p> <pre><code>for file in os.listdir("/home/ubuntu/Desktop/temp/poem"): print file f = open(file, 'r') print f.read() f.close() </code></pre> <p>This code reads file name of all the files in directory. But it fails at </p> <pre><code>f = open(file, 'r') </code></pre> <p>saying </p> <pre><code>IOError: [Errno 2] No such file or directory: '32' </code></pre>
0
2016-09-15T10:11:59Z
39,508,643
<p>you are searching file in current join file path with directory folder.</p> <pre><code>import os for i in os.listdir("/home/ubuntu/Desktop/temp/poem"): if os.path.isfile(os.path.join("/home/ubuntu/Desktop/temp/poem",i)): print os.path.join("/home/ubuntu/Desktop/temp/poem",i) f=open(os.path.join("/home/ubuntu/Desktop/temp/poem",i),"r") print f.readlines() f.close() </code></pre>
1
2016-09-15T10:20:22Z
[ "python", "io" ]
Repeating code 3 times, and making sure input is only a number in Python 2.7
39,508,667
<p>I am trying to find out how to make my code repeat its self 3 times at the end of the set of questions and also I'm trying to make sure my validation is correct so that the input to the questions is only a number. </p> <p><strong>This is my code...</strong></p> <pre><code>import random correct = 0 name = raw_input("Please enter your name: ") print 'ok',name, 'I need you to answer these 10 math simple maths questions' for counter in range(10): num1 = float(random.randint(1, 10)) num2 = float(random.randint(1, 10)) Math = random.choice(["+", "-", "*","/"]) print("Please solve:", num1, Math, num2) user = int(input("")) if Math == "+": answer = num1 + num2 elif Math == "-": answer = num1 - num2 elif Math == "*": answer = num1 * num2 elif Math == "/": answer = num1 / num2 if answer!= int: print ("Please reenter a number") if user == answer: print("Correct!") correct = correct + 1 else: print("Incorrect") print(name, " You Got", correct, "Out Of 10") </code></pre>
0
2016-09-15T10:21:22Z
39,510,953
<p>Your <code>answer != int</code> should be <code>if not isinstance(answer, int)</code> Furthermore, you will get <code>ValueError</code> each time user tries to insert characters.</p> <p>Because of this, you should edit your code to look like this:</p> <pre><code>from __future__ import division import random for i in xrange(3): correct = 0 name = raw_input("Please enter your name: ") print 'ok',name, 'I need you to answer these 10 math simple maths questions' for counter in xrange(3): num1 = random.randint(1, 10) num2 = random.randint(1, 10) Math = random.choice(["+", "-", "*","/"]) print("Please solve: {} {} {}".format(num1, Math, num2)) while True: try: user = int(raw_input("")) except ValueError: print ("Please reenter a number") continue break if Math == "+": answer = num1 + num2 elif Math == "-": answer = num1 - num2 elif Math == "*": answer = num1 * num2 elif Math == "/": answer = round(num1 / num2, 1) if user == answer: print("Correct!") correct = correct + 1 else: print("Incorrect") print("{} You Got {} Out Of 10".format(name, correct)) </code></pre> <p>As you can see there was a lot things that you needed to change.</p>
0
2016-09-15T12:23:51Z
[ "python", "python-2.7" ]
What's the equivalent of MatLab/Octave filt/bode in scipy?
39,508,726
<p>To create a digital system that could be used e.g. in bode or spectrum in matlab or octave I could use:</p> <pre><code>b = [1,0.1,0.2,0.3] a = [1,-1] sys = filt(b,a) bode(sys) spectrum(sys) </code></pre> <p>What will be the scipy equivalent for this command(s)?</p>
1
2016-09-15T10:24:34Z
39,529,035
<p>There are a few options, you can use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.bode.html" rel="nofollow"><code>scipy.signal.bode</code></a> or <a href="http://python-control.readthedocs.io/en/latest/generated/control.bode.html#control.bode" rel="nofollow"><code>python-control.bode</code></a> or <a href="http://harold.readthedocs.io/en/latest/tut_freq_domain.html#harold.bodeplot" rel="nofollow"><code>harold.bodeplot</code></a>. </p>
0
2016-09-16T10:19:02Z
[ "python", "matlab", "scipy", "signal-processing" ]
Numpy efficient indexing with varied size arrays
39,508,846
<p>Take a look at this piece of code:</p> <pre><code>import numpy as np a = np.random.random(10) indicies = [ np.array([1, 4, 3]), np.array([2, 5, 8, 7, 3]), np.array([1, 2]), np.array([3, 2, 1]) ] result = np.zeros(2) result[0] = a[indicies[0]].sum() result[1] = a[indicies[2]].sum() </code></pre> <p>Is there any way to get <code>result</code> more efficiently? In my case <code>a</code> is a very large array.</p> <p>In other words I want to select elements from <code>a</code> with several varying size index arrays and then sum over them in one operation, resulting in a single array.</p>
1
2016-09-15T10:31:01Z
39,509,169
<p>If your array <strong>a</strong> is very large you might have <strong>memory issues</strong> if your array of indices contains many arrays of many indices when looping through it.</p> <p>To avoid this issue use an iterator instead of a list :</p> <pre><code>indices = iter(indices) </code></pre> <p>and then loop through your iterator.</p>
-1
2016-09-15T10:46:54Z
[ "python", "arrays", "numpy" ]
Numpy efficient indexing with varied size arrays
39,508,846
<p>Take a look at this piece of code:</p> <pre><code>import numpy as np a = np.random.random(10) indicies = [ np.array([1, 4, 3]), np.array([2, 5, 8, 7, 3]), np.array([1, 2]), np.array([3, 2, 1]) ] result = np.zeros(2) result[0] = a[indicies[0]].sum() result[1] = a[indicies[2]].sum() </code></pre> <p>Is there any way to get <code>result</code> more efficiently? In my case <code>a</code> is a very large array.</p> <p>In other words I want to select elements from <code>a</code> with several varying size index arrays and then sum over them in one operation, resulting in a single array.</p>
1
2016-09-15T10:31:01Z
39,515,877
<p>With your <code>a</code> and <code>indicies</code> list:</p> <pre><code>In [280]: [a[i].sum() for i in indicies] Out[280]: [1.3986792680307709, 2.6354365193743732, 0.83324677494990895, 1.8195179021311731] </code></pre> <p>Which of course could wrapped in <code>np.array()</code>.</p> <p>For a subset of the <code>indicies</code> items use:</p> <pre><code>In [281]: [a[indicies[i]].sum() for i in [0,2]] Out[281]: [1.3986792680307709, 0.83324677494990895] </code></pre> <p>A comment suggests <code>indicies</code> comes from an Adjacency matrix, possibly sparse.</p> <p>I could recreate such an array with:</p> <pre><code>In [289]: A=np.zeros((4,10),int) In [290]: for i in range(4): A[i,indicies[i]]=1 In [291]: A Out[291]: array([[0, 1, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0, 0, 0]]) </code></pre> <p>and use a matrix product (<code>np.dot</code>) to do the selection and sum:</p> <pre><code>In [292]: A.dot(a) Out[292]: array([ 1.39867927, 2.63543652, 0.83324677, 1.8195179 ]) </code></pre> <p><code>A[[0,2],:].dot(a)</code> would use a subset of rows.</p> <p>A sparse matrix version has that list of row indices:</p> <pre><code>In [294]: Al=sparse.lil_matrix(A) In [295]: Al.rows Out[295]: array([[1, 3, 4], [2, 3, 5, 7, 8], [1, 2], [1, 2, 3]], dtype=object) </code></pre> <p>And a matrix product with that gives the same numbers:</p> <pre><code>In [296]: Al*a Out[296]: array([ 1.39867927, 2.63543652, 0.83324677, 1.8195179 ]) </code></pre>
0
2016-09-15T16:17:29Z
[ "python", "arrays", "numpy" ]
Grouping dictionary items by attribute
39,508,956
<p>I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:</p> <pre><code>[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] </code></pre> <p>And I wanted to group these items by <code>type</code>. According to <a href="http://stackoverflow.com/questions/6602172/how-to-group-a-list-of-tuples-objects-by-similar-index-attribute-in-python">this answer</a> this can be done using <code>defaultdict()</code> because it doesn't raise a <code>KeyError</code>, as follows:</p> <pre><code>grouped = defaultdict() for item in items: grouped[item.type].append(item) </code></pre> <p>However, I am actually getting a <code>KeyError</code>.</p> <p>So what's wrong? All the information I see says <code>defaultdict()</code> is supposed to create an empty list if it's not existing, and the insert the element.</p> <p>I am using Python 2.7.</p>
0
2016-09-15T10:36:29Z
39,508,993
<p>use <code>defaultdict(list)</code>, not <code>defaultdict()</code>. Read the docs for defaultdict to find out more.</p> <p>Also, you cannot use some_dict.a_key (in your case: .type) - you must use some_dict['a_key'] (in your case ['type'])</p>
2
2016-09-15T10:38:38Z
[ "python", "dictionary" ]
Grouping dictionary items by attribute
39,508,956
<p>I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:</p> <pre><code>[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] </code></pre> <p>And I wanted to group these items by <code>type</code>. According to <a href="http://stackoverflow.com/questions/6602172/how-to-group-a-list-of-tuples-objects-by-similar-index-attribute-in-python">this answer</a> this can be done using <code>defaultdict()</code> because it doesn't raise a <code>KeyError</code>, as follows:</p> <pre><code>grouped = defaultdict() for item in items: grouped[item.type].append(item) </code></pre> <p>However, I am actually getting a <code>KeyError</code>.</p> <p>So what's wrong? All the information I see says <code>defaultdict()</code> is supposed to create an empty list if it's not existing, and the insert the element.</p> <p>I am using Python 2.7.</p>
0
2016-09-15T10:36:29Z
39,509,221
<p>You can also use a normal dictionary and its <a href="https://docs.python.org/2/library/stdtypes.html#dict.setdefault" rel="nofollow"><code>setdefault</code></a> method:</p> <pre><code>l = [{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] d = {} for x in l: d.setdefault(x["type"], []).append(x) print d </code></pre> <p>The result would be this (nicely formatted):</p> <pre><code>{'plant' : [{'type': 'plant', 'name': 'orange tree'}], 'animal': [{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'animal', 'name': 'coyote'}]} </code></pre>
0
2016-09-15T10:50:23Z
[ "python", "dictionary" ]
Grouping dictionary items by attribute
39,508,956
<p>I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:</p> <pre><code>[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] </code></pre> <p>And I wanted to group these items by <code>type</code>. According to <a href="http://stackoverflow.com/questions/6602172/how-to-group-a-list-of-tuples-objects-by-similar-index-attribute-in-python">this answer</a> this can be done using <code>defaultdict()</code> because it doesn't raise a <code>KeyError</code>, as follows:</p> <pre><code>grouped = defaultdict() for item in items: grouped[item.type].append(item) </code></pre> <p>However, I am actually getting a <code>KeyError</code>.</p> <p>So what's wrong? All the information I see says <code>defaultdict()</code> is supposed to create an empty list if it's not existing, and the insert the element.</p> <p>I am using Python 2.7.</p>
0
2016-09-15T10:36:29Z
39,509,441
<pre><code>from collections import defaultdict animals=[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] animal_by_type = defaultdict(list) for animal in animals: animal_by_type[animal['type']].append(animal['name']) print animal_by_type </code></pre>
0
2016-09-15T11:02:15Z
[ "python", "dictionary" ]
SVM Scikit-Learn : Why prediction time decrease with SVC when increasing parameter C?
39,509,080
<p>I’m trying to evaluate the influence of the # of features &amp; parameter C (SVM regularization) on the prediction time. I am using a modified version of <a href="http://scikit-learn.org/stable/auto_examples/applications/plot_prediction_latency.html#example-applications-plot-prediction-latency-py" rel="nofollow">code</a> proposed by scikit-learn website. </p> <p>Here are some key lines of code : input </p> <pre><code>'n_train': int(2000), 'n_test': int( 500), 'n_features': np.arange(10,100,10) </code></pre> <p>Functions</p> <pre><code>SVC(kernel='linear', C=0.001) SVC(kernel='linear', C=0.01) SVC(kernel='linear', C=1) SVC(kernel='linear', C=100) </code></pre> <p>predictions</p> <pre><code>estimator.fit(X_train, y_train) .... start = time.time() estimator.predict(X_test) runtimes[i] = time.time() - start </code></pre> <p>Output : <a href="http://i.stack.imgur.com/I3nea.png" rel="nofollow">Evolution of Prediction Time</a> <a href="http://i.stack.imgur.com/I3nea.png" rel="nofollow"><img src="http://i.stack.imgur.com/I3nea.png" alt="enter image description here"></a> I don’t understand why the prediction time is reversed. According to many resources (<a href="http://stats.stackexchange.com/questions/31066/what-is-the-influence-of-c-in-svms-with-linear-kernel">3</a> and others), the latency should increase with C parameter of SVM function.</p>
1
2016-09-15T10:42:54Z
39,513,160
<p>Having a larger C will lead to smaller values for the slack variables. This means that the number of support vectors will decrease. When you run the prediction, it will need to calculate the indicator function for each support vector. </p> <p>Thus; smaller C -> more support vectors -> more calculations -> slower predictions.</p>
0
2016-09-15T14:03:53Z
[ "python", "machine-learning", "scikit-learn", "svm", "latency" ]
Nearest neighbour in pyspark using euclidean distance or similar
39,509,095
<p>So I need to find nearest neighbors of a given row in pyspark DF using euclidean distance or anything. the data that I have 20+ columns, more than thousand rows and all the values are numbers.</p> <p>I am trying to oversample some data in pyspark, as mllib doesn't have inbuilt support for it, i decided to create it myself using smote.</p> <p>my approach till now has been to convert all the categorical distance into index using <strong>stringtoindex</strong> so that i can find the euclidean distance and neighbors and hence perform smote.</p> <p>I am fairly new to spark and ml. Any help would be appreciated.</p>
0
2016-09-15T10:43:38Z
39,530,374
<p>Not tried but Ive found this script: <a href="https://github.com/jakac/spark-python-knn/blob/master/python/gaussalgo/knn/knn.py" rel="nofollow">https://github.com/jakac/spark-python-knn/blob/master/python/gaussalgo/knn/knn.py</a></p> <p>If your data are dataframe, you should first merge your column into a vector with vectorASsembler <a href="https://spark.apache.org/docs/latest/ml-features.html#vectorassembler" rel="nofollow">https://spark.apache.org/docs/latest/ml-features.html#vectorassembler</a>, then use <code>df.select("id", "yourColumnVector")</code></p> <p>The library I provided seems to work only with rdd, so you should convert your dataframe to RDD using <code>df.rdd()</code> or something</p>
1
2016-09-16T11:28:16Z
[ "python", "pyspark", "nearest-neighbor", "knn" ]
Progress bar in tkinter not working
39,509,185
<p>I am writing a small app to copy some files. I have made almost everything that I wanted but 3 things:</p> <p>1) Progress-bar to move while the copy option is in motion. I can display it but it won't react. </p> <p>I am using this to show it:</p> <pre><code>self.p = ttk.Progressbar(self, orient=HORIZONTAL, length=300, mode='indeterminate') self.p.grid(row=5) </code></pre> <p>and then to initiate it in another def which is called upon a press of the button:</p> <pre><code> self.p.start() shutil.copytree(self.source_direcotry0, self.cam0) shutil.copytree(self.source_direcotry1, self.cam1) shutil.copytree(self.source_direcotry2, self.cam2) self.p.stop() </code></pre> <p>Unfortunately the copying occurs but the bar doesn't move at all. </p> <p>2) Second problem is connected to the information bar that I am displaying at the bottom of the app window:</p> <pre><code>self.status = Label(self.master, text="Waiting for process to start...", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) </code></pre> <p>And then when the same copying def is called at the beginning of it I have this: </p> <pre><code>self.status['text'] = "Files are being copyied, have patience ;)".format(self.status) </code></pre> <p>And the status is not changed which is weird as at the end of this def I also have same command to change the status and this one works:</p> <pre><code>self.status['text'] = "Files have been copyied".format(self.status) </code></pre> <p>3) I can't seem to attach a picture I have checked all kinds of different options and none of them seem to work, the one presented here seems like tries to display something (the window gets bigger) but the picture is not visible:</p> <pre><code> self.img = ImageTk.PhotoImage(Image.open("az.png")) self.panel = Label(self, image=self.img, bg="#E6E6E6") self.display = self.img self.panel.grid(row=8) </code></pre> <p>I am a bit unsure why it is happening like that, just in case and also for more info I am posting here the complete code:</p> <pre><code>from tkinter import * from tkinter import ttk import re from tkinter import messagebox from tkinter import filedialog import ntpath import os import shutil import tkinter.filedialog as fdialog from send2trash import send2trash from PIL import Image, ImageTk #os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''') # Here, we are creating our class, Window, and inheriting from the Frame # class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__) class Window(Frame): # Define settings upon initialization. Here you can specify def __init__(self, master=None): # parameters that you want to send through the Frame class. Frame.__init__(self, master, bg="#E6E6E6") #reference to the master widget, which is the tk window self.master = master #with that, we want to then run init_window, which doesn't yet exist self.init_window() def copyy(self): self.status['text'] = "Files are being copyied, have patience ;)".format(self.status) self.source_direcotry0= '/Volumes/CAM0/DCIM/100HDDVR' self.source_direcotry1= '/Volumes/CAM1/DCIM/100HDDVR' self.source_direcotry2= '/Volumes/CAM2/DCIM/100HDDVR' self.source_direcotry3= '/Volumes/CAM3/DCIM/100HDDVR' self.source_direcotry4= '/Volumes/CAM4/DCIM/100HDDVR' self.source_direcotry5= '/Volumes/CAM5/DCIM/100HDDVR' self.source_direcotry6= '/Volumes/CAM6/DCIM/100HDDVR' self.source_direcotry7= '/Volumes/CAM7/DCIM/100HDDVR' self.source_direcotry8= '/Volumes/CAM8/DCIM/100HDDVR' self.source_direcotry9= '/Volumes/CAM9/DCIM/100HDDVR' self.source_direcotry10= '/Volumes/CAM10/DCIM/100HDDVR' self.source_direcotry11= '/Volumes/CAM11/DCIM/100HDDVR' self.path0="recording/CAM0" self.path1="recording/CAM1" self.path2="recording/CAM2" self.path3="recording/CAM3" self.path4="recording/CAM4" self.path5="recording/CAM5" self.path6="recording/CAM6" self.path7="recording/CAM7" self.path8="recording/CAM8" self.path9="recording/CAM9" self.path10="recording/CAM10" self.path11="recording/CAM11" self.cam0=os.path.join(self.Destination.get(), self.path0) self.cam1=os.path.join(self.Destination.get(), self.path1) self.cam2=os.path.join(self.Destination.get(), self.path2) self.cam3=os.path.join(self.Destination.get(), self.path3) self.cam4=os.path.join(self.Destination.get(), self.path4) self.cam5=os.path.join(self.Destination.get(), self.path5) self.cam6=os.path.join(self.Destination.get(), self.path6) self.cam7=os.path.join(self.Destination.get(), self.path7) self.cam8=os.path.join(self.Destination.get(), self.path8) self.cam9=os.path.join(self.Destination.get(), self.path9) self.cam10=os.path.join(self.Destination.get(), self.path10) self.cam11=os.path.join(self.Destination.get(), self.path11) self.p.start() shutil.copytree(self.source_direcotry0, self.cam0) shutil.copytree(self.source_direcotry1, self.cam1) shutil.copytree(self.source_direcotry2, self.cam2) # shutil.copytree(self.source_direcotry3, self.cam3) # shutil.copytree(self.source_direcotry4, self.cam4) # shutil.copytree(self.source_direcotry5, self.cam5) # shutil.copytree(self.source_direcotry6, self.cam6) # shutil.copytree(self.source_direcotry7, self.cam7) # shutil.copytree(self.source_direcotry8, self.cam8) # shutil.copytree(self.source_direcotry9, self.cam9) # shutil.copytree(self.source_direcotry10, self.cam10) # shutil.copytree(self.source_direcotry11, self.cam11) self.p.stop() self.status['text'] = "Files have been copyied".format(self.status) def deletee(self): send2trash('/Volumes/CAM0/DCIM') send2trash('/Volumes/CAM1/DCIM') send2trash('/Volumes/CAM2/DCIM') # send2trash('/Volumes/CAM3/DCIM') # send2trash('/Volumes/CAM4/DCIM') # send2trash('/Volumes/CAM5/DCIM') # send2trash('/Volumes/CAM6/DCIM') # send2trash('/Volumes/CAM7/DCIM') # send2trash('/Volumes/CAM8/DCIM') # send2trash('/Volumes/CAM9/DCIM') # send2trash('/Volumes/CAM10/DCIM') # send2trash('/Volumes/CAM11/DCIM') self.status['text'] = "Files have been moved to trash".format(self.status) def client_exit(self): exit() def about_popup(self): messagebox.showinfo("About", "This is software used to copy or delete files in bulk from the Absolute Zero VR camera") #Creation of init_window def init_window(self): self.Source=StringVar() self.Destination=StringVar() # changing the title of our master widget self.master.title("AZ Data Extractor") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=1) #Creating the menu self.menubar = Menu(self.master) #Creating submenues self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Exit", command=root.quit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label="About", command=self.about_popup) self.menubar.add_cascade(label="Help", menu=self.helpmenu) #Displaying the menu root.config(menu=self.menubar) #Creating the intro label l_instruction = Label(self, justify=CENTER, compound=TOP, text="Choose the destination for the copied files \n and press 'Go!' to start copyting", bg="#E6E6E6") l_instruction.grid(columnspan=2, ipady=10) l_instruction = Label(self, justify=CENTER, compound=TOP, text="Press 'Delete' to move all files \n from the camera to the trash", bg="#E6E6E6") l_instruction.grid(row=6, columnspan=2, ipady=10) # ttk.Style().configure('green/black.TButton', foreground='green', background='black') #Creating the button MyDestination=Entry(self, textvariable=self.Destination, bg="#E6E6E6") MyDestination.grid(row=2, columnspan=2, ipady=10) uploadButton = Button(self, text="Choose destination folder",command=lambda:self.Destination.set(fdialog.askdirectory())) uploadButton.grid(row=3, columnspan=2, ipady=10) goButton = Button(self, text="Go!",command=self.copyy) goButton.grid(row=4, columnspan=2, ipady=10) delButton = Button(self, text="Delete",command=self.deletee) delButton.grid(row=7, columnspan=2, ipady=10) self.p = ttk.Progressbar(self, orient=HORIZONTAL, length=300, mode='indeterminate') self.p.grid(row=5) self.img = ImageTk.PhotoImage(Image.open("az.png")) self.panel = Label(self, image=self.img, bg="#E6E6E6") self.display = self.img self.panel.grid(row=8) #resizing configuration self.grid_columnconfigure(0,weight=1) self.grid_columnconfigure(1,weight=1) self.grid_rowconfigure(0,weight=1) self.grid_rowconfigure(1,weight=1) self.grid_rowconfigure(2,weight=1) self.grid_rowconfigure(3,weight=1) self.grid_rowconfigure(4,weight=1) self.grid_rowconfigure(5,weight=1) self.grid_rowconfigure(6,weight=1) self.grid_rowconfigure(7,weight=1) self.grid_rowconfigure(8,weight=1) self.grid_rowconfigure(9,weight=1) self.grid_rowconfigure(10,weight=1) #status Bar self.status = Label(self.master, text="Waiting for process to start...", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) # root window created. Here, that would be the only window, but you can later have windows within windows. root = Tk() root.resizable(width=False,height=False); # root.configure(background='black'); # fm = Frame(root, width=300, height=200, bg="blue") # fm.pack(side=TOP, expand=NO, fill=NONE) #root.geometry("230x340") #creation of an instance app = Window(root) #mainloop root.mainloop() </code></pre> <p>Edit: Just as and additional problem that came up in the mean time I can't seem to change background colour of the buttons and the frames around entry field. I read up it could be because using MacOS platform, could that be? Any workarounds?</p>
0
2016-09-15T10:48:05Z
39,667,184
<p>I compacted the loading bar I got working in an older project of mine. The only way I had figured it out was to call the progress bar handling calls in a new thread and call the work-intensive functions from this thread into another new thread. </p> <p>It is bad practice to have a separate threads handling UI elements other than the UI thread, including starting and stopping a progress bar; however it does work and I've been using this project to do pretty heavy processing with zero issues for months now.</p> <p>Here the progress bar is working in a small script, using Python 3.5.2 on W10 64-Bit</p> <pre><code>from tkinter import * import tkinter.ttk as ttk import threading import time class Main_Frame(object): def __init__(self, top=None): # save root reference self.top = top # set title bar self.top.title("Loading bar example") # start button calls the "initialization" function bar_init, you can pass a variable in here if desired self.start_button = ttk.Button(top, text='Start bar', command=lambda: self.bar_init(2500)) self.start_button.pack() # the progress bar will be referenced in the "bar handling" and "work" threads self.load_bar = ttk.Progressbar(top) self.load_bar.pack() # run mainloop self.top.mainloop() def bar_init(self, var): # first layer of isolation, note var being passed along to the self.start_bar function # target is the function being started on a new thread, so the "bar handler" thread self.start_bar_thread = threading.Thread(target=self.start_bar, args=(var,)) # start the bar handling thread self.start_bar_thread.start() def start_bar(self, var): # the load_bar needs to be configured for indeterminate amount of bouncing self.load_bar.config(mode='indeterminate', maximum=100, value=0) # 8 here is for speed of bounce self.load_bar.start(8) # start the work-intensive thread, again a var can be passed in here too if desired self.work_thread = threading.Thread(target=self.work_task, args=(var,)) self.work_thread.start() # close the work thread self.work_thread.join() # stop the indeterminate bouncing self.load_bar.stop() # reconfigure the bar so it appears reset self.load_bar.config(value=0, maximum=0) def work_task(self, wait_time): for x in range(wait_time): time.sleep(0.001) if __name__ == '__main__': # create root window root = Tk() # call Main_Frame class with reference to root as top Main_Frame(top=root) </code></pre>
0
2016-09-23T18:17:08Z
[ "python", "tkinter", "progress-bar" ]
Progress bar in tkinter not working
39,509,185
<p>I am writing a small app to copy some files. I have made almost everything that I wanted but 3 things:</p> <p>1) Progress-bar to move while the copy option is in motion. I can display it but it won't react. </p> <p>I am using this to show it:</p> <pre><code>self.p = ttk.Progressbar(self, orient=HORIZONTAL, length=300, mode='indeterminate') self.p.grid(row=5) </code></pre> <p>and then to initiate it in another def which is called upon a press of the button:</p> <pre><code> self.p.start() shutil.copytree(self.source_direcotry0, self.cam0) shutil.copytree(self.source_direcotry1, self.cam1) shutil.copytree(self.source_direcotry2, self.cam2) self.p.stop() </code></pre> <p>Unfortunately the copying occurs but the bar doesn't move at all. </p> <p>2) Second problem is connected to the information bar that I am displaying at the bottom of the app window:</p> <pre><code>self.status = Label(self.master, text="Waiting for process to start...", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) </code></pre> <p>And then when the same copying def is called at the beginning of it I have this: </p> <pre><code>self.status['text'] = "Files are being copyied, have patience ;)".format(self.status) </code></pre> <p>And the status is not changed which is weird as at the end of this def I also have same command to change the status and this one works:</p> <pre><code>self.status['text'] = "Files have been copyied".format(self.status) </code></pre> <p>3) I can't seem to attach a picture I have checked all kinds of different options and none of them seem to work, the one presented here seems like tries to display something (the window gets bigger) but the picture is not visible:</p> <pre><code> self.img = ImageTk.PhotoImage(Image.open("az.png")) self.panel = Label(self, image=self.img, bg="#E6E6E6") self.display = self.img self.panel.grid(row=8) </code></pre> <p>I am a bit unsure why it is happening like that, just in case and also for more info I am posting here the complete code:</p> <pre><code>from tkinter import * from tkinter import ttk import re from tkinter import messagebox from tkinter import filedialog import ntpath import os import shutil import tkinter.filedialog as fdialog from send2trash import send2trash from PIL import Image, ImageTk #os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''') # Here, we are creating our class, Window, and inheriting from the Frame # class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__) class Window(Frame): # Define settings upon initialization. Here you can specify def __init__(self, master=None): # parameters that you want to send through the Frame class. Frame.__init__(self, master, bg="#E6E6E6") #reference to the master widget, which is the tk window self.master = master #with that, we want to then run init_window, which doesn't yet exist self.init_window() def copyy(self): self.status['text'] = "Files are being copyied, have patience ;)".format(self.status) self.source_direcotry0= '/Volumes/CAM0/DCIM/100HDDVR' self.source_direcotry1= '/Volumes/CAM1/DCIM/100HDDVR' self.source_direcotry2= '/Volumes/CAM2/DCIM/100HDDVR' self.source_direcotry3= '/Volumes/CAM3/DCIM/100HDDVR' self.source_direcotry4= '/Volumes/CAM4/DCIM/100HDDVR' self.source_direcotry5= '/Volumes/CAM5/DCIM/100HDDVR' self.source_direcotry6= '/Volumes/CAM6/DCIM/100HDDVR' self.source_direcotry7= '/Volumes/CAM7/DCIM/100HDDVR' self.source_direcotry8= '/Volumes/CAM8/DCIM/100HDDVR' self.source_direcotry9= '/Volumes/CAM9/DCIM/100HDDVR' self.source_direcotry10= '/Volumes/CAM10/DCIM/100HDDVR' self.source_direcotry11= '/Volumes/CAM11/DCIM/100HDDVR' self.path0="recording/CAM0" self.path1="recording/CAM1" self.path2="recording/CAM2" self.path3="recording/CAM3" self.path4="recording/CAM4" self.path5="recording/CAM5" self.path6="recording/CAM6" self.path7="recording/CAM7" self.path8="recording/CAM8" self.path9="recording/CAM9" self.path10="recording/CAM10" self.path11="recording/CAM11" self.cam0=os.path.join(self.Destination.get(), self.path0) self.cam1=os.path.join(self.Destination.get(), self.path1) self.cam2=os.path.join(self.Destination.get(), self.path2) self.cam3=os.path.join(self.Destination.get(), self.path3) self.cam4=os.path.join(self.Destination.get(), self.path4) self.cam5=os.path.join(self.Destination.get(), self.path5) self.cam6=os.path.join(self.Destination.get(), self.path6) self.cam7=os.path.join(self.Destination.get(), self.path7) self.cam8=os.path.join(self.Destination.get(), self.path8) self.cam9=os.path.join(self.Destination.get(), self.path9) self.cam10=os.path.join(self.Destination.get(), self.path10) self.cam11=os.path.join(self.Destination.get(), self.path11) self.p.start() shutil.copytree(self.source_direcotry0, self.cam0) shutil.copytree(self.source_direcotry1, self.cam1) shutil.copytree(self.source_direcotry2, self.cam2) # shutil.copytree(self.source_direcotry3, self.cam3) # shutil.copytree(self.source_direcotry4, self.cam4) # shutil.copytree(self.source_direcotry5, self.cam5) # shutil.copytree(self.source_direcotry6, self.cam6) # shutil.copytree(self.source_direcotry7, self.cam7) # shutil.copytree(self.source_direcotry8, self.cam8) # shutil.copytree(self.source_direcotry9, self.cam9) # shutil.copytree(self.source_direcotry10, self.cam10) # shutil.copytree(self.source_direcotry11, self.cam11) self.p.stop() self.status['text'] = "Files have been copyied".format(self.status) def deletee(self): send2trash('/Volumes/CAM0/DCIM') send2trash('/Volumes/CAM1/DCIM') send2trash('/Volumes/CAM2/DCIM') # send2trash('/Volumes/CAM3/DCIM') # send2trash('/Volumes/CAM4/DCIM') # send2trash('/Volumes/CAM5/DCIM') # send2trash('/Volumes/CAM6/DCIM') # send2trash('/Volumes/CAM7/DCIM') # send2trash('/Volumes/CAM8/DCIM') # send2trash('/Volumes/CAM9/DCIM') # send2trash('/Volumes/CAM10/DCIM') # send2trash('/Volumes/CAM11/DCIM') self.status['text'] = "Files have been moved to trash".format(self.status) def client_exit(self): exit() def about_popup(self): messagebox.showinfo("About", "This is software used to copy or delete files in bulk from the Absolute Zero VR camera") #Creation of init_window def init_window(self): self.Source=StringVar() self.Destination=StringVar() # changing the title of our master widget self.master.title("AZ Data Extractor") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=1) #Creating the menu self.menubar = Menu(self.master) #Creating submenues self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Exit", command=root.quit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label="About", command=self.about_popup) self.menubar.add_cascade(label="Help", menu=self.helpmenu) #Displaying the menu root.config(menu=self.menubar) #Creating the intro label l_instruction = Label(self, justify=CENTER, compound=TOP, text="Choose the destination for the copied files \n and press 'Go!' to start copyting", bg="#E6E6E6") l_instruction.grid(columnspan=2, ipady=10) l_instruction = Label(self, justify=CENTER, compound=TOP, text="Press 'Delete' to move all files \n from the camera to the trash", bg="#E6E6E6") l_instruction.grid(row=6, columnspan=2, ipady=10) # ttk.Style().configure('green/black.TButton', foreground='green', background='black') #Creating the button MyDestination=Entry(self, textvariable=self.Destination, bg="#E6E6E6") MyDestination.grid(row=2, columnspan=2, ipady=10) uploadButton = Button(self, text="Choose destination folder",command=lambda:self.Destination.set(fdialog.askdirectory())) uploadButton.grid(row=3, columnspan=2, ipady=10) goButton = Button(self, text="Go!",command=self.copyy) goButton.grid(row=4, columnspan=2, ipady=10) delButton = Button(self, text="Delete",command=self.deletee) delButton.grid(row=7, columnspan=2, ipady=10) self.p = ttk.Progressbar(self, orient=HORIZONTAL, length=300, mode='indeterminate') self.p.grid(row=5) self.img = ImageTk.PhotoImage(Image.open("az.png")) self.panel = Label(self, image=self.img, bg="#E6E6E6") self.display = self.img self.panel.grid(row=8) #resizing configuration self.grid_columnconfigure(0,weight=1) self.grid_columnconfigure(1,weight=1) self.grid_rowconfigure(0,weight=1) self.grid_rowconfigure(1,weight=1) self.grid_rowconfigure(2,weight=1) self.grid_rowconfigure(3,weight=1) self.grid_rowconfigure(4,weight=1) self.grid_rowconfigure(5,weight=1) self.grid_rowconfigure(6,weight=1) self.grid_rowconfigure(7,weight=1) self.grid_rowconfigure(8,weight=1) self.grid_rowconfigure(9,weight=1) self.grid_rowconfigure(10,weight=1) #status Bar self.status = Label(self.master, text="Waiting for process to start...", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) # root window created. Here, that would be the only window, but you can later have windows within windows. root = Tk() root.resizable(width=False,height=False); # root.configure(background='black'); # fm = Frame(root, width=300, height=200, bg="blue") # fm.pack(side=TOP, expand=NO, fill=NONE) #root.geometry("230x340") #creation of an instance app = Window(root) #mainloop root.mainloop() </code></pre> <p>Edit: Just as and additional problem that came up in the mean time I can't seem to change background colour of the buttons and the frames around entry field. I read up it could be because using MacOS platform, could that be? Any workarounds?</p>
0
2016-09-15T10:48:05Z
39,775,063
<p>So I have used your code to make the improvements in mine and it works :) Unfortunately there is a "but". So the progress bar is nicely moving while files are being copied. What is still not perfect that after the button is pressed to execute the coping there is quite substantial delay time before the copying start. It is long enough that average user might start suspecting program has crashed. I think is has too be something connect to how threads start but I made couple of combinations and non of them improved the issue. I am posting whole code as I though it will be easier for you to see what is going on. Thank in advance @Joules!</p> <p>Here is the code:</p> <pre><code>from tkinter import * from tkinter import ttk import re from tkinter import messagebox from tkinter import filedialog import ntpath import os import shutil import tkinter.filedialog as fdialog from send2trash import send2trash from PIL import Image, ImageTk from threading import Thread import threading os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''') # Here, we are creating our class, Window, and inheriting from the Frame # class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__) class Window(Frame): # Define settings upon initialization. Here you can specify def __init__(self, master=None): # parameters that you want to send through the Frame class. Frame.__init__(self, master, bg="#E6E6E6") #reference to the master widget, which is the tk window self.master = master #with that, we want to then run init_window, which doesn't yet exist self.init_window() def bar_init(self): # first layer of isolation, note var being passed along to the self.start_bar function # target is the function being started on a new thread, so the "bar handler" thread self.start_bar_thread = threading.Thread(target=self.copyy, args=()) # start the bar handling thread self.start_bar_thread.start() def copyy(self): root.update_idletasks() self.status['text'] = "Files are being copyied, have patience ;)".format(self.status) self.source_direcotry0= '/Volumes/CAM0/DCIM/100HDDVR' self.source_direcotry1= '/Volumes/CAM1/DCIM/100HDDVR' self.source_direcotry2= '/Volumes/CAM2/DCIM/100HDDVR' self.source_direcotry3= '/Volumes/CAM3/DCIM/100HDDVR' self.source_direcotry4= '/Volumes/CAM4/DCIM/100HDDVR' self.source_direcotry5= '/Volumes/CAM5/DCIM/100HDDVR' self.source_direcotry6= '/Volumes/CAM6/DCIM/100HDDVR' self.source_direcotry7= '/Volumes/CAM7/DCIM/100HDDVR' self.source_direcotry8= '/Volumes/CAM8/DCIM/100HDDVR' self.source_direcotry9= '/Volumes/CAM9/DCIM/100HDDVR' self.source_direcotry10= '/Volumes/CAM10/DCIM/100HDDVR' self.source_direcotry11= '/Volumes/CAM11/DCIM/100HDDVR' self.path0="recording/CAM0" self.path1="recording/CAM1" self.path2="recording/CAM2" self.path3="recording/CAM3" self.path4="recording/CAM4" self.path5="recording/CAM5" self.path6="recording/CAM6" self.path7="recording/CAM7" self.path8="recording/CAM8" self.path9="recording/CAM9" self.path10="recording/CAM10" self.path11="recording/CAM11" self.cam0=os.path.join(self.Destination.get(), self.path0) self.cam1=os.path.join(self.Destination.get(), self.path1) self.cam2=os.path.join(self.Destination.get(), self.path2) self.cam3=os.path.join(self.Destination.get(), self.path3) self.cam4=os.path.join(self.Destination.get(), self.path4) self.cam5=os.path.join(self.Destination.get(), self.path5) self.cam6=os.path.join(self.Destination.get(), self.path6) self.cam7=os.path.join(self.Destination.get(), self.path7) self.cam8=os.path.join(self.Destination.get(), self.path8) self.cam9=os.path.join(self.Destination.get(), self.path9) self.cam10=os.path.join(self.Destination.get(), self.path10) self.cam11=os.path.join(self.Destination.get(), self.path11) self.p.start(1) self.work_thread = threading.Thread(target=self.copyy2, args=()) self.work_thread.start() self.work_thread.join() self.p.stop() self.status['text'] = "Files have been copyied".format(self.status) def copyy2(self): shutil.copytree(self.source_direcotry0, self.cam0) shutil.copytree(self.source_direcotry1, self.cam1) shutil.copytree(self.source_direcotry2, self.cam2) shutil.copytree(self.source_direcotry3, self.cam3) shutil.copytree(self.source_direcotry4, self.cam4) shutil.copytree(self.source_direcotry5, self.cam5) shutil.copytree(self.source_direcotry6, self.cam6) shutil.copytree(self.source_direcotry7, self.cam7) shutil.copytree(self.source_direcotry8, self.cam8) shutil.copytree(self.source_direcotry9, self.cam9) shutil.copytree(self.source_direcotry10, self.cam10) shutil.copytree(self.source_direcotry11, self.cam11) def deletee(self): send2trash('/Volumes/CAM0/DCIM') send2trash('/Volumes/CAM1/DCIM') send2trash('/Volumes/CAM2/DCIM') send2trash('/Volumes/CAM3/DCIM') send2trash('/Volumes/CAM4/DCIM') send2trash('/Volumes/CAM5/DCIM') send2trash('/Volumes/CAM6/DCIM') send2trash('/Volumes/CAM7/DCIM') send2trash('/Volumes/CAM8/DCIM') send2trash('/Volumes/CAM9/DCIM') send2trash('/Volumes/CAM10/DCIM') send2trash('/Volumes/CAM11/DCIM') self.status['text'] = "Files have been moved to trash".format(self.status) def client_exit(self): exit() def about_popup(self): messagebox.showinfo("About", "This is software used to copy or delete files in bulk from the Absolute Zero VR camera") #Creation of init_window def init_window(self): self.Source=StringVar() self.Destination=StringVar() # changing the title of our master widget self.master.title("AZ Data Extractor") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=1) #Creating the menu self.menubar = Menu(self.master) #Creating submenues self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Exit", command=root.quit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label="About", command=self.about_popup) self.menubar.add_cascade(label="Help", menu=self.helpmenu) #Displaying the menu root.config(menu=self.menubar) #Creating the intro label l_instruction = Label(self, justify=CENTER, compound=TOP, text="Choose the destination for the copied files \n and press 'Go!' to start copyting", bg="#E6E6E6") l_instruction.grid(columnspan=2, ipady=10) l_instruction = Label(self, justify=CENTER, compound=TOP, text="Press 'Delete' to move all files \n from the camera to the trash", bg="#E6E6E6") l_instruction.grid(row=6, columnspan=2, ipady=10) #Creating the button MyDestination=Entry(self, textvariable=self.Destination,highlightbackground="#E6E6E6") MyDestination.grid(row=2, columnspan=2, ipady=10) uploadButton = Button(self, text="Choose destination folder",command=lambda:self.Destination.set(fdialog.askdirectory()),highlightbackground="#E6E6E6") uploadButton.grid(row=3, columnspan=2, ipady=10) goButton = Button(self, text="Go!",command=self.bar_init,highlightbackground="#E6E6E6") goButton.grid(row=4, columnspan=2, ipady=10) delButton = Button(self, text="Delete",command=self.deletee,highlightbackground="#E6E6E6") delButton.grid(row=7, columnspan=2, ipady=10) s = ttk.Style() s.theme_use('alt') s.configure("grey.Horizontal.TProgressbar", troughcolor='#E6E6E6', background='gray', bordercolor='#E6E6E6') self.p = ttk.Progressbar(self, style="grey.Horizontal.TProgressbar", orient=HORIZONTAL, length=300, mode='indeterminate') self.p.grid(row=5) render = PhotoImage(file="az.gif") img = Label(self, image=render, bg="#E6E6E6") img.image = render img.grid(row=10) space = Label(self, bg="#E6E6E6") space.grid(row=8) space2 = Label(self, bg="#E6E6E6") space2.grid(row=9) space3 = Label(self, bg="#E6E6E6") space3.grid(row=11) #resizing configuration self.grid_columnconfigure(0,weight=1) self.grid_columnconfigure(1,weight=1) self.grid_rowconfigure(0,weight=1) self.grid_rowconfigure(1,weight=1) self.grid_rowconfigure(2,weight=1) self.grid_rowconfigure(3,weight=1) self.grid_rowconfigure(4,weight=1) self.grid_rowconfigure(5,weight=1) self.grid_rowconfigure(6,weight=1) self.grid_rowconfigure(7,weight=1) self.grid_rowconfigure(8,weight=1) self.grid_rowconfigure(9,weight=1) self.grid_rowconfigure(10,weight=1) self.grid_rowconfigure(11,weight=1) #status Bar self.status = Label(self.master, text="Waiting for process to start...", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) # root window created. Here, that would be the only window, but you can later have windows within windows. root = Tk() root.resizable(width=False,height=False); #root.geometry("230x340") #creation of an instance app = Window(root) #mainloop root.mainloop() </code></pre>
0
2016-09-29T16:02:02Z
[ "python", "tkinter", "progress-bar" ]
Full blocking generator in twisted thread that runs forever
39,509,254
<p>Let's assume we have a <em>blackbox</em> generator that is fully blocking and runs forever. We're running Twisted, so standard way to handle blocking things is use <code>defers</code> or <code>defers + threads</code>.</p> <pre><code># some very naive example from twisted.internet import reactor def aSillyBlockingMethod(): for results in fullblocking_blockbox_generator_that_runs_forever(): print results reactor.callInThread(aSillyBlockingMethod) reactor.run() </code></pre> <p>Yay! Job's done! ... but not exactly.</p> <p>Everything is great until we want to stop whole Twisted app. One of the shutting down steps is call something like ~<code>threadpool.join()</code> which is waiting for all threads to finish themselves. But not our fullbocking ethernal <em>blackbox</em> generator. We can't do much in loop because we need yielded results from generator that could never happen.</p> <p>I've browse whole internet for ideas. Nothing. Maybe I'm missing something important or there is a clever way to handle this?</p>
0
2016-09-15T10:52:07Z
39,518,362
<p>I took the answer provided from <a href="http://stackoverflow.com/a/2244899/2172464">this post</a> and added example code. Also keep in mind it's always best to have well defined start and end points for threads. As you can see, it can cause some pretty sticky situations if a thread runs forever in an uncontrolled fashion. With that being said, sometimes some situations are unavoidable (but that doesn't mean we shouldn't try to avoid it whenever possible).</p> <p>If the <em>blackbox</em> doesn't require anything from Twisted, you could start it as a daemon thread outside of Twisted's control which will stop when your application stops. In general, this is <strong>very dangerous</strong> because this kills threads immediately which could leave things in an corrupted state. In any case, here is an example:</p> <pre><code>from threading import Thread, Event from time import sleep from twisted.internet import reactor class BlackBox(Thread): def __init__(self, stop_event=None): super(BlackBox, self).__init__() if not stop_event: stop_event = Event() self.stop_event = stop_event def run(self): while True: print('running in thread') if self.stop_event.is_set(): print('STOPPING!') break sleep(1) t = BlackBox() t.daemon = True t.start() # reactor.callLater(5, t.stop_event.set) # if you want to stop thread after 5 seconds reactor.run() </code></pre> <p>The better option would have a control flow within your thread code, such as checking for an <code>Event</code>, and initiate a trigger when the app shuts down. To capture such a trigger in Twisted, use <code>reactor.addSystemEventTrigger</code>.</p> <pre><code>from threading import Event from time import sleep from twisted.internet import reactor def aSillyBlockingMethod(event): while True: print('running in thread') if event.is_set(): print('STOPPING') break sleep(1) stop_event = Event() reactor.callInThread(aSillyBlockingMethod, stop_event) reactor.addSystemEventTrigger('before', 'shutdown', stop_event.set) reactor.run() </code></pre> <p>Option #2 is a much better solution than daemon threads because the threaded code doesn't arbitrarily stop, you could let Twisted manage the thread, and the thread can stop at an appropriate time (deemed by the developer). I hope this helps</p>
0
2016-09-15T18:50:55Z
[ "python", "multithreading", "twisted" ]
Django not creating database table after deleting migrations files and migration table
39,509,392
<p>I have created two tables profile and details through django model and mistakenly i have deleted both these tables. Further when i tried to create table using</p> <pre><code>python2.7 manage.py makemigrations </code></pre> <p>and </p> <pre><code>python2.7 manage.py migrate </code></pre> <p>then it was not creating the tables so i deleted migration files and truncated the django_migration table. Now when i am running command</p> <pre><code>python2.7 manage.py runserver </code></pre> <p>Its giving me error </p> <pre><code>You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. </code></pre> <p>And if i run python manage.py migrate command error is </p> <pre><code>Operations to perform: Apply all migrations: home, contenttypes, auth, sessions Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial...Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 59, in database_forwards schema_editor.create_model(model) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 284, in create_model self.execute(sql, params or None) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "django_content_type" already exists </code></pre>
0
2016-09-15T10:59:49Z
39,509,767
<p>Run following command:</p> <pre><code>python manage.py migrate --fake-initial </code></pre>
0
2016-09-15T11:18:02Z
[ "python", "django" ]
Django not creating database table after deleting migrations files and migration table
39,509,392
<p>I have created two tables profile and details through django model and mistakenly i have deleted both these tables. Further when i tried to create table using</p> <pre><code>python2.7 manage.py makemigrations </code></pre> <p>and </p> <pre><code>python2.7 manage.py migrate </code></pre> <p>then it was not creating the tables so i deleted migration files and truncated the django_migration table. Now when i am running command</p> <pre><code>python2.7 manage.py runserver </code></pre> <p>Its giving me error </p> <pre><code>You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. </code></pre> <p>And if i run python manage.py migrate command error is </p> <pre><code>Operations to perform: Apply all migrations: home, contenttypes, auth, sessions Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial...Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 59, in database_forwards schema_editor.create_model(model) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 284, in create_model self.execute(sql, params or None) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "django_content_type" already exists </code></pre>
0
2016-09-15T10:59:49Z
39,509,790
<p>You need to first fake migrations for each of those built-in apps</p> <p><strong>python manage.py migrate --fake auth</strong><br> <strong>python manage.py migrate --fake contenttypes</strong></p> <p>the run fake initial</p> <p><strong>python manage.py migrate --fake-initial</strong></p> <p>This most probably should work for you.</p>
0
2016-09-15T11:19:22Z
[ "python", "django" ]
Reducing rows in a column for a panda DataFrame for plotting
39,509,404
<p>So I have a csv table of data which I have read into a panda DataFrame, however one of the columns has the same string in multiple rows, which is correct as its a classification data, but when I plot this column against another of values, it treats each cell in this column as separate rather than combining them.</p> <pre><code>Classification Value MIR-weak: 0.0896571179 MIR-weak: 0.1990277968 MIR-bright: 0.2850534357 MIR-bright: 0.0807078051 FIR-dark/MIR-bright: 1.7610864745 MIR-weak: 0.0826692503 MIR-weak: 0.349403222 MIR-weak: 0.7326764485 MIR-weak: 0.0179843643 MIR-weak: 0.0761941975 MIR-bright: 0.4298597194 MIR-weak: 0.4143098599 MIR-weak: 0.1439220025 MIR-weak: 0.0810787048 MIR-bright: 0.6369812293 MIR-weak: 0.0973845298 MIR-weak: 0.1871236732 MIR-weak: 1.5795256821 MIR-weak: 0.9072559132 MIR-weak: 0.6218977498 FIR-dark/MIR-bright: 0.6920326523 MIR-weak: 0.2580561867 MIR-bright: 0.055071288 MIR-weak: 1.0512992066 </code></pre> <p>So when I plot these columns against each other using DataFrame.plot(), the x-axis has every cell in the first column as an x value rather than just four x values, one for each classification</p> <p>Any way to sort this, either with .plot() or doing something with the data?</p>
0
2016-09-15T11:00:28Z
39,510,033
<p>I presume you want a stacked bar plot, so starting with your dataframe looking like this </p> <pre><code>Classification Value 0 MIR-weak 0.089657 1 MIR-weak 0.199028 2 MIR-bright 0.285053 3 MIR-bright 0.080708 4 FIR-dark/MIR-bright 1.761086 5 MIR-weak 0.082669 6 MIR-weak 0.349403 7 MIR-weak 0.732676 8 MIR-weak 0.017984 9 MIR-weak 0.076194 10 MIR-bright 0.429860 11 MIR-weak 0.414310 12 MIR-weak 0.143922 13 MIR-weak 0.081079 14 MIR-bright 0.636981 15 MIR-weak 0.097385 16 MIR-weak 0.187124 17 MIR-weak 1.579526 18 MIR-weak 0.907256 19 MIR-weak 0.621898 20 FIR-dark/MIR-bright 0.692033 21 MIR-weak 0.258056 22 MIR-bright 0.055071 23 MIR-weak 1.051299 </code></pre> <p>you can do these steps:</p> <ul> <li><p>Sort by Classification.</p></li> <li><p>Pivot around Classification.</p></li> <li><p>Change columns to get rid of the multi-index.</p></li> <li><p>Do a stacked bar plot of the transposed dataframe.</p></li> </ul> <p>.</p> <pre><code>D = D.sort_values("Classification").reset_index(drop=True) D = D.pivot(columns='Classification') D.columns = ["FIR-dark/MIR-bright", "MIR-bright", "MIR-weak"] D.T.plot.bar(stacked=True,legend=False) </code></pre> <p>The result looks pretty ugly though, so you need to tweak the appearance.</p> <p>Not sure if that's the correct thing since it only has three categories, but your original also has only three.</p>
0
2016-09-15T11:32:53Z
[ "python", "pandas", "plot", "dataframe" ]
KD Tree gives different results to brute force method
39,509,562
<p>I have an array of 1000 random 3D points &amp; I am interested in the closest 10 points to any given point. <a href="http://stackoverflow.com/questions/2486093/millions-of-3d-points-how-to-find-the-10-of-them-closest-to-a-given-point">In essence the same as this post.</a></p> <p>I checked the 2 solutions offered by J.F. Sebastian, namely a brute force approach &amp; a KD Tree approach. </p> <p>Although both give me the same indices for the closest points, they give different results for the distances</p> <pre><code>import numpy as np from scipy.spatial import KDTree a = 100 * np.random.rand(1000,3) point = a[np.random.randint(0, 1001)] # point chosen at random # KD Tree tree = KDTree(a, leafsize=a.shape[0]+1) dist_kd, ndx_kd = tree.query([point], k=10) # Brute force distances = ((a-point)**2).sum(axis=1) # compute distances ndx = distances.argsort() # indirect sort ndx_brt = ndx[:10] dist_brt = distances[ndx[:10]] # Output print 'KD Tree:' print ndx_kd print dist_kd print print 'Brute force:' print ndx_brt print dist_brt </code></pre> <p>My output,</p> <blockquote> <p>KD Tree: [[838 860 595 684 554 396 793 197 652 330]] [[ 0. 3.00931208 8.30596471 9.47709122 10.98784209 11.39555636 11.89088764 12.01566931 12.551557 12.77700426]]</p> <p>Brute force: [838 860 595 684 554 396 793 197 652 330]<br> [ 0. 9.05595922 68.9890498 89.81525793 120.73267386 129.8587047 141.3932089 144.37630888 157.54158301 163.25183793]</p> </blockquote> <p>So what is the issue here? Am I calculating the distance wrong?</p>
0
2016-09-15T11:07:38Z
39,512,661
<p><code>KDTree</code> algorithm is computing the nearest points based on the square-root of the same distance used by <code>Brute-force</code> algorithm.</p> <p>Basically KDtree uses: <code>sqrt(x^2+y^2+z^2)</code> and Brute-force algorithm uses: <code>x^2+y^2+z^2</code></p>
1
2016-09-15T13:43:03Z
[ "python", "numpy", "scipy", "kdtree" ]
KD Tree gives different results to brute force method
39,509,562
<p>I have an array of 1000 random 3D points &amp; I am interested in the closest 10 points to any given point. <a href="http://stackoverflow.com/questions/2486093/millions-of-3d-points-how-to-find-the-10-of-them-closest-to-a-given-point">In essence the same as this post.</a></p> <p>I checked the 2 solutions offered by J.F. Sebastian, namely a brute force approach &amp; a KD Tree approach. </p> <p>Although both give me the same indices for the closest points, they give different results for the distances</p> <pre><code>import numpy as np from scipy.spatial import KDTree a = 100 * np.random.rand(1000,3) point = a[np.random.randint(0, 1001)] # point chosen at random # KD Tree tree = KDTree(a, leafsize=a.shape[0]+1) dist_kd, ndx_kd = tree.query([point], k=10) # Brute force distances = ((a-point)**2).sum(axis=1) # compute distances ndx = distances.argsort() # indirect sort ndx_brt = ndx[:10] dist_brt = distances[ndx[:10]] # Output print 'KD Tree:' print ndx_kd print dist_kd print print 'Brute force:' print ndx_brt print dist_brt </code></pre> <p>My output,</p> <blockquote> <p>KD Tree: [[838 860 595 684 554 396 793 197 652 330]] [[ 0. 3.00931208 8.30596471 9.47709122 10.98784209 11.39555636 11.89088764 12.01566931 12.551557 12.77700426]]</p> <p>Brute force: [838 860 595 684 554 396 793 197 652 330]<br> [ 0. 9.05595922 68.9890498 89.81525793 120.73267386 129.8587047 141.3932089 144.37630888 157.54158301 163.25183793]</p> </blockquote> <p>So what is the issue here? Am I calculating the distance wrong?</p>
0
2016-09-15T11:07:38Z
39,513,237
<p>distances = ((a-point)**2).sum(axis=1) **0.5<a href="http://i.stack.imgur.com/3idkJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/3idkJ.png" alt="enter image description here"></a></p>
0
2016-09-15T14:07:04Z
[ "python", "numpy", "scipy", "kdtree" ]
python speech to text and voice level differences visualisation
39,509,624
<p>Hi am using pyttsx for converting text to speech and then vise versa making a sort of automatic call replying system. Where one will ask questions and then python will convert it into text and reply with voice(Like SIRI in apple) Now what i want is to have a tool which will show different values of bar when the system is replying. Just like we are having in Microphone. Everytime it receives a voice the sound bar goes up.. <a href="http://i.stack.imgur.com/JLOC0.png" rel="nofollow">enter image description here</a></p>
0
2016-09-15T11:11:26Z
39,510,471
<p>A tool to make that is the standard <a href="https://docs.python.org/2/library/turtle.html" rel="nofollow"><code>turtle</code> library</a> for output, the necessary calculations (how much the bar must go up) can be done without any library.</p>
0
2016-09-15T11:58:06Z
[ "python", "text-to-speech" ]
Python or LibreOffice Save xlsx file encrypted with password
39,509,741
<p>I am trying to save an Excel file <em>encrypted</em> with password. I have tried following the guide on <a href="https://help.libreoffice.org/Common/Protecting_Content_in" rel="nofollow">https://help.libreoffice.org/Common/Protecting_Content_in</a> - and works perfectly. However, this is in the GUI, but I am looking for a solution using the command line interface in headless mode.</p> <p>I have looked at the <code>man libreoffice</code>, but I could not find anything in there. </p> <p>Likewise I have looked at the documentation of the Python 3 library <code>openpyxl</code>, but I did not find anything useful there either.</p> <p>Is it possible to save an Excel 2007+ file <em>encrypted</em> with a password on Ubuntu 14.04/16.04 using the command line (or Python library) that do not require any user interaction or X session?</p>
1
2016-09-15T11:16:59Z
39,898,408
<p>There is solution using <a href="http://jython.org" rel="nofollow">Jython</a> and <a href="https://poi.apache.org/" rel="nofollow">Apache POI</a>. If you want like to use it from CPython/PyPy, you can use <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> module to call external Jython script.</p> <ol> <li>I assume that you have Java JRE/JDK installed</li> <li>Create <em>non-encrypted</em> xlsx file with Excel/Calc or use <a href="http://xlsxwriter.readthedocs.io/" rel="nofollow">xlsxwriter</a> or <a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">openpyxl</a> and save it as <em>test1.xlsx</em></li> <li>Download standalone Jython</li> <li>Download Apache POI</li> <li>Extract Apache POI in same dir where is standalone Jython jar</li> <li>Save following Jython script as <em>encrypt.py</em>:</li> </ol> <pre class="lang-py prettyprint-override"><code>import os import sys from java.io import BufferedInputStream from java.io import FileInputStream from java.io import FileOutputStream from java.io import File from java.io import IOException from org.apache.poi.poifs.crypt import EncryptionInfo, EncryptionMode from org.apache.poi.poifs.crypt import CipherAlgorithm, HashAlgorithm from org.apache.poi.poifs.crypt.agile import AgileEncryptionInfoBuilder from org.apache.poi.openxml4j.opc import OPCPackage, PackageAccess from org.apache.poi.poifs.filesystem import POIFSFileSystem from org.apache.poi.ss.usermodel import WorkbookFactory def encrypt_xlsx(in_fname, out_fname, password): # read in_f = File(in_fname) in_wb = WorkbookFactory.create(in_f, password) in_fis = FileInputStream(in_fname) in_wb.close() # encryption out_poi_fs = POIFSFileSystem() info = EncryptionInfo(EncryptionMode.agile) enc = info.getEncryptor() enc.confirmPassword(password) opc = OPCPackage.open(in_f, PackageAccess.READ_WRITE) out_os = enc.getDataStream(out_poi_fs) opc.save(out_os) opc.close() # write out_fos = FileOutputStream(out_fname) out_poi_fs.writeFilesystem(out_fos) out_fos.close() if __name__ == '__main__': in_fname = sys.argv[1] out_fname = sys.argv[2] password = sys.argv[3] encrypt_xlsx(in_fname, out_fname, password) </code></pre> <ol start="7"> <li>Call it from console:</li> </ol> <pre class="lang-bash prettyprint-override"><code>java -cp "jython-standalone-2.7.0.jar:poi-3.15/lib/commons-codec-1.10.jar:poi-3.15/lib/commons-collections4-4.1.jar:poi-3.15/poi-3.15.jar:poi-3.15/poi-ooxml-3.15.jar:poi-3.15/poi-ooxml-schemas-3.15.jar:poi-3.15/ooxml-lib/curvesapi-1.04.jar:poi-3.15/ooxml-lib/xmlbeans-2.6.0.jar" org.python.util.jython -B encrypt.py test1.xlsx test1enc.xlsx 12345678 </code></pre> <p>Where:</p> <ul> <li>encrypt.py - name of script</li> <li>test1.xlsx - input filename</li> <li>test1enc.xlsx - output filename</li> <li>12345678 - password</li> </ul> <p>Final <em>encrypted</em> xslx should be in <em>test1enc.xlsx</em>.</p>
1
2016-10-06T14:15:05Z
[ "python", "excel", "encryption", "ubuntu-14.04", "libreoffice-calc" ]
Does python perform tasks on lists in parallel by itself?
39,509,770
<p>I stumbled upon this piece of work:</p> <pre><code>def getChild(self, childName): for child in self.children : if(childName == child.data['name']): return child return None </code></pre> <p>As far as ranting is concerned this code implies everything there is to say and know about this library.</p> <p>I am not that deep into python but I afaik the canonic pythonic way of going about this task is</p> <pre><code>def getChild(self, childName): return ( [ child for child in self.children if child.data['name'] == childName ] + [ None ] )[0] </code></pre> <p>or, for better readability,</p> <pre><code>def getChild(self, childName): myChildren = dict([ (child.data['name'],child) for child in self.children ]) try: return myChildren[childName] except: return None </code></pre> <p>Besides the fact that I still have no clue about how and when to indent and where to put <code>{</code>,<code>[</code>,<code>(</code>,<code>)</code>,<code>]</code> and <code>}</code>, my alternatives always operate on all elements of <code>self.children</code>.</p> <p>Does python recognise this and work through the data sets in parallel, or will it still work through the array sequentially? (and therefore always take longer than the simple search I found in that library)</p> <p>With the amount of lookups performed it is of course better to change the library to always maintain a dictionary of children instead of a list, but that is besides the point. I would like to know how python interprets and handles this code. </p>
-2
2016-09-15T11:18:14Z
39,510,146
<p>No, there is no automatic parallelization. Python is about writing your code efficiently, but not about making it computationally efficient. And there is a bigger problem: the GIL - Global Interpreter Lock. That means that only one thread at a time is executed. So there is no big point in parallelization of CPU intensive tasks in python. There are interpreters without GIL, but general rule of thumb: if you don't know about GIL, then you have it.</p> <p>Concerning the code you've posted: python allows you to write in the most common procedural style or in functional style, beloved in universities. You can choose any.</p>
2
2016-09-15T11:39:51Z
[ "python", "list", "dictionary", "parallel-processing" ]
Pandas: KeyError when attempting to print value from df.loc in Excel file
39,509,803
<p>I'm attempting to parse an Excel-file using Pandas.</p> <pre><code>import pandas as pd import xlrd xl_file = pd.ExcelFile("file.xlsx") df = xl_file.parse("Sheet1") </code></pre> <p>Now, if I get a value (<code>name</code>) from the sheet:</p> <pre><code>if len(df.loc[df["Col A"].str.contains("John"), "Col B"]) &gt; 0: name = df.loc[df["Col A"].str.contains("John"), "Col B"] </code></pre> <p>And then <code>print name</code>, the result is:</p> <blockquote> <pre><code>1 John Doe Name: Col B, dtype: object </code></pre> </blockquote> <p>or <code>print name.values</code>:</p> <blockquote> <pre><code>[u'John Doe'] </code></pre> </blockquote> <p>But if I try to retrieve the actual string with <code>print name[0]</code>, I get <code>KeyError</code>:</p> <blockquote> <pre><code> File "pandas/core/series.py", line 583, in __getitem__ result = self.index.get_value(self, key) File "pandas/indexes/base.py", line 1980, in get_value tz=getattr(series.dtype, 'tz', None)) File "pandas/index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas/index.c:3332) File "pandas/index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas/index.c:3035) File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018) File "pandas/hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6610) File "pandas/hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6554) KeyError: 0 </code></pre> </blockquote> <p>What could be the problem?</p>
2
2016-09-15T11:20:15Z
39,510,639
<p><code>name</code> is a series, and <code>0</code> is not in the series' index (check <code>name.index</code>). This explains the error message.</p> <p>If you want to select the first element in the series, do:</p> <pre><code>name.iloc[0] </code></pre>
3
2016-09-15T12:06:35Z
[ "python", "excel", "python-2.7", "pandas" ]
Python unique values per column in csv file row
39,509,824
<p>Crunching on this for a long time. Is there an easy way using Numpy or Pandas or fixing my code to get the unique values for the column in a row separated by "|"</p> <p>I.e the data:</p> <pre><code>"id","fname","lname","education","gradyear","attributes" "1","john","smith","mit|harvard|ft|ft|ft","2003|207|212|212|212","qa|admin,co|master|NULL|NULL" "2","john","doe","htw","2000","dev" </code></pre> <p>Output should be:</p> <pre><code>"id","fname","lname","education","gradyear","attributes" "1","john","smith","mit|harvard|ft","2003|207|212","qa|admin,co|master|NULL" "2","john","doe","htw","2000","dev" </code></pre> <p>My broken code:</p> <pre><code>import csv import pprint your_list = csv.reader(open('out.csv')) your_list = list(your_list) #pprint.pprint(your_list) string = "|" cols_no=6 for line in your_list: i=0 for col in line: if i==cols_no: print "\n" i=0 if string in col: values = col.split("|") myset = set(values) items = list() for item in myset: items.append(item) print items else: print col+",", i=i+1 </code></pre> <p>It outputs:</p> <pre><code>id, fname, lname, education, gradyear, attributes, 1, john, smith, ['harvard', 'ft', 'mit'] ['2003', '212', '207'] ['qa', 'admin,co', 'NULL', 'master'] 2, john, doe, htw, 2000, dev, </code></pre> <p>Thanks in advance!</p>
0
2016-09-15T11:21:14Z
39,510,014
<p>If you don't care about the order when you have many items separated with <code>|</code>, this will work:</p> <pre><code>lst = ["id","fname","lname","education","gradyear","attributes", "1","john","smith","mit|harvard|ft|ft|ft","2003|207|212|212|212","qa|admin,co|master|NULL|NULL", "2","john","doe","htw","2000","dev"] def no_duplicate(string): return "|".join(set(string.split("|"))) result = map(no_duplicate, lst) print result </code></pre> <p>result:</p> <pre><code>['id', 'fname', 'lname', 'education', 'gradyear', 'attributes', '1', 'john', 'smith', 'ft|harvard|mit', '2003|207|212', 'NULL|admin,co|master|qa', '2', 'john', 'doe', 'htw', '2000', 'dev'] </code></pre>
0
2016-09-15T11:31:30Z
[ "python", "pandas", "numpy" ]
Python unique values per column in csv file row
39,509,824
<p>Crunching on this for a long time. Is there an easy way using Numpy or Pandas or fixing my code to get the unique values for the column in a row separated by "|"</p> <p>I.e the data:</p> <pre><code>"id","fname","lname","education","gradyear","attributes" "1","john","smith","mit|harvard|ft|ft|ft","2003|207|212|212|212","qa|admin,co|master|NULL|NULL" "2","john","doe","htw","2000","dev" </code></pre> <p>Output should be:</p> <pre><code>"id","fname","lname","education","gradyear","attributes" "1","john","smith","mit|harvard|ft","2003|207|212","qa|admin,co|master|NULL" "2","john","doe","htw","2000","dev" </code></pre> <p>My broken code:</p> <pre><code>import csv import pprint your_list = csv.reader(open('out.csv')) your_list = list(your_list) #pprint.pprint(your_list) string = "|" cols_no=6 for line in your_list: i=0 for col in line: if i==cols_no: print "\n" i=0 if string in col: values = col.split("|") myset = set(values) items = list() for item in myset: items.append(item) print items else: print col+",", i=i+1 </code></pre> <p>It outputs:</p> <pre><code>id, fname, lname, education, gradyear, attributes, 1, john, smith, ['harvard', 'ft', 'mit'] ['2003', '212', '207'] ['qa', 'admin,co', 'NULL', 'master'] 2, john, doe, htw, 2000, dev, </code></pre> <p>Thanks in advance!</p>
0
2016-09-15T11:21:14Z
39,510,118
<p><code>numpy</code>/<code>pandas</code> is a bit overkill for what you can achieve with <code>csv.DictReader</code> and <code>csv.DictWriter</code> with a <code>collections.OrderedDict</code>, eg:</p> <pre><code>import csv from collections import OrderedDict # If using Python 2.x - use `open('output.csv', 'wb') instead with open('input.csv') as fin, open('output.csv', 'w') as fout: csvin = csv.DictReader(fin) csvout = csv.DictWriter(fout, fieldnames=csvin.fieldnames, quoting=csv.QUOTE_ALL) csvout.writeheader() for row in csvin: for k, v in row.items(): row[k] = '|'.join(OrderedDict.fromkeys(v.split('|'))) csvout.writerow(row) </code></pre> <p>Gives you:</p> <pre><code>"id","fname","lname","education","gradyear","attributes" "1","john","smith","mit|harvard|ft","2003|207|212","qa|admin,co|master|NULL" "2","john","doe","htw","2000","dev" </code></pre>
2
2016-09-15T11:38:31Z
[ "python", "pandas", "numpy" ]
Python write multiline data in a column of a single row in csv
39,509,837
<p>I have a json response similar to as dt1 and i'm writing the json data into CSV with fieldnames NAME, Total and details , below is my code.</p> <pre><code>dt1 = { u'Name': ABC, u'total': 6 , u'Details':{ u'Subject1': {u'Opted': False, u'value': u'100'}, u'Subject2': {u'Opted': True, u'value': u'200'}, u'Subject2': {u'Opted': True, u'value': u'200'} } } with open('file.csv', 'w') as csvfile: fieldnames = ['Name', 'Total', 'Details'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() dt2 = dt1.values()[0].keys( for key in dt1.keys(): if dt1[key]['detected'] is True) writer.writerow({'NAME': dt1['Name'], 'Total' : dt1['Total'], 'Details': ([key, [dt1[key][scan] for scan in dt2]])}) </code></pre> <p>and the CSV generates is :</p> <pre><code>NAME Total Detail ABC 6 Subject1, "[u'Opted': False, u'value': u'100']" ABC 6 Subject2, "[u'Opted': True, u'value': u'200']" ABC 6 Subject3, {u'Opted': True, u'value': u'500'} </code></pre> <p>I want to write multi line data of details dict into single column as shown below. Name and Total not repeating for every subject. Is it possible to do? how do I achieve it.</p> <pre><code>NAME Total Details ABC 6 Subject1, "[u'Opted': False, u'value': u'100']" Subject2, "[u'Opted': True, u'value': u'200']" Subject3, {u'Opted': True, u'value': u'500'} </code></pre>
0
2016-09-15T11:22:01Z
39,537,872
<p>try something like this:</p> <pre><code>import csv dt1 = { u'Name': 'ABC', u'Total': 6 , u'Details':{ u'Subject1': {u'Opted': False, u'value': u'100'}, u'Subject2': {u'Opted': True, u'value': u'200'}, u'Subject3': {u'Opted': True, u'value': u'200'} } } with open('file.csv', 'w') as csvfile: fieldnames = ['Name', 'Total', 'Details'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() first_detail = True for k in dt1['Details']: if first_detail: writer.writerow({'Name': dt1['Name'], 'Total' : dt1['Total'], 'Details': k + ',' + str(dt1['Details'][k])}) first_detail = False else: writer.writerow({'Name': None, 'Total' : None, 'Details': k + ', ' + str(dt1['Details'][k])}) </code></pre> <p><strong>file.csv:</strong></p> <pre><code>Name,Total,Details ABC,6,"Subject3, {'value': '200', 'Opted': True}" ,,"Subject2, {'value': '200', 'Opted': True}" ,,"Subject1, {'value': '100', 'Opted': False}" </code></pre>
0
2016-09-16T18:22:56Z
[ "python", "json", "csv", "dictionary" ]
Can I save a list in Memcache in Google-AppEngine in Python?
39,509,956
<p>I want to save a list in MemCache in AppEngine with Python and I am having the next error : </p> <p>TypeError: <strong>new</strong>() takes exactly 4 arguments (1 given).</p> <p>This is the link of the image with the error : <a href="http://i.stack.imgur.com/we3VU.png" rel="nofollow">http://i.stack.imgur.com/we3VU.png</a></p> <p>And this is my code :</p> <pre><code>def get_r_post_relation(self, url, update = False) : sufix = "r" key = sufix + url list_version = memcache.get(key) if not list_version or update : logging.error("LIST VERSION QUERY") postobj = get_wiki_post(url) list_version = WikiPostVersion.query().filter(WikiPostVersion.r_post == postobj.key) memcache.set(key, list_version) return list_version </code></pre>
1
2016-09-15T11:28:26Z
39,515,702
<p>You are not storing a list. You are storing a query object. To store a list, use <code>.fetch()</code>:</p> <pre><code>list_version = WikiPostVersion.query().filter(WikiPostVersion.r_post == postobj.key).fetch() </code></pre> <p>You can store a simple query object, but when you add <code>.order()</code> or <code>.filter()</code>, you'll get a pickling error. Change to list, and you're all set.</p> <p>Remember, a query object doesn't have any entities in it. It is simply a set of instructions that will go and retrieve the entities when used later with a <code>.get()</code> or <code>.fetch()</code>. So, you are trying to store a python command set, when your intention is to store the actual entity list.</p>
3
2016-09-15T16:07:52Z
[ "python", "google-app-engine", "memcached" ]
How to set the "chunk size" of read lines from file read with Python subprocess.Popen() or open()?
39,509,959
<p>I have a fairly large text file which I would like to run in chunks. In order to do this with the <code>subprocess</code> library, one would execute following shell command:</p> <pre><code>"cat hugefile.log" </code></pre> <p>with the code:</p> <pre><code>import subprocess task = subprocess.Popen("cat hugefile.log", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() </code></pre> <p>Using <code>print(data)</code> will spit out the entire contents of the file at once. How can I present the number of chunks, and then access the contents of this file by the chunk size (e.g. chunk = three lines at a time). </p> <p>It must be something like: </p> <pre><code>chunksize = 1000 # break up hugefile.log into 1000 chunks for chunk in data: print(chunk) </code></pre> <p>The equivalent question with Python <code>open()</code> of course uses the code</p> <pre><code>with open('hugefile.log', 'r') as f: read_data = f.read() </code></pre> <p>How would you <code>read_data</code> in chunks? </p>
0
2016-09-15T11:28:34Z
39,510,102
<p>Using a file, you can iterate on the file handle (no need for subprocess to open <code>cat</code>):</p> <pre><code>with open('hugefile.log', 'r') as f: for read_line in f: print(read_line) </code></pre> <p>Python reads a line by reading all the chars up to <code>\n</code>. To simulate the line-by-line I/O, just call it 3 times. or read and count 3 <code>\n</code> chars but you have to handle the end of file, etc... not very useful and you won't gain any speed by doing that.</p> <pre><code>with open('hugefile.log', 'r') as f: while True: read_3_lines = "" try: for i in range(3): read_3_lines += next(f) # process read_3_lines except StopIteration: # end of file # process read_3_lines if nb lines not divisible by 3 break </code></pre> <p>With <code>Popen</code> you can do exactly the same, as a bonus add <code>poll</code> to monitor the process (no need with <code>cat</code> but I suppose that your process is different and that's only for the question's purpose)</p> <pre><code>import subprocess task = subprocess.Popen("cat hugefile.log", shell=True, stdout=subprocess.PIPE) while True: line = task.stdout.readline() if line == '' and task.poll() != None: break rc = task.wait() # wait for completion and get return code of the command </code></pre> <p>Python 3 compliant code supporting encoding:</p> <pre><code> line = task.stdout.readline().decode("latin-1") if len(line) == 0 and task.poll() != None: break </code></pre> <p>Now, if you want to split the file into a given number of chunks:</p> <ul> <li>you cannot use <code>Popen</code> for obvious reasons: you would have to know the size of the output first</li> <li>if you have a file as input you can do as follows:</li> </ul> <p>code:</p> <pre><code>import os,sys filename = "hugefile.log" filesize = os.path.getsize(filename) nb_chunks = 1000 chunksize = filesize // nb_chunks with open(filename,"r") as f: while True: chunk = f.read(chunksize) if chunk=="": break # do something useful with the chunk sys.stdout.write(chunk) </code></pre>
1
2016-09-15T11:37:35Z
[ "python", "bash", "shell", "subprocess", "chunking" ]
In Python subprocess, what is the difference between using Popen() and check_output()?
39,510,029
<p>Take the shell command "cat file.txt" as an example. </p> <p>With Popen, this could be run with</p> <pre><code>import subprocess task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() </code></pre> <p>With check_output, one could run</p> <pre><code>import subprocess command=r"""cat file.log""" output=subprocess.check_output(command, shell=True) </code></pre> <p>These appears to be equivalent. What is the difference with regards to how these two commands would be used? </p>
1
2016-09-15T11:32:29Z
39,510,073
<p>From <a href="https://docs.python.org/3/library/subprocess.html#exceptions" rel="nofollow">the documentation</a>:</p> <blockquote> <p><code>check_call()</code> and <code>check_output()</code> will raise <code>CalledProcessError</code> if the called process returns a non-zero return code.</p> </blockquote>
1
2016-09-15T11:35:33Z
[ "python", "bash", "shell", "subprocess" ]
In Python subprocess, what is the difference between using Popen() and check_output()?
39,510,029
<p>Take the shell command "cat file.txt" as an example. </p> <p>With Popen, this could be run with</p> <pre><code>import subprocess task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() </code></pre> <p>With check_output, one could run</p> <pre><code>import subprocess command=r"""cat file.log""" output=subprocess.check_output(command, shell=True) </code></pre> <p>These appears to be equivalent. What is the difference with regards to how these two commands would be used? </p>
1
2016-09-15T11:32:29Z
39,510,272
<p><code>Popen</code> is the class that defines an object used to interact with an external process. <code>check_output()</code> is just a wrapper around an instance of <code>Popen</code> to examine its standard output. Here's the definition from Python 2.7 (sans docstring):</p> <pre><code>def check_output(*popenargs, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd, output=output) return output </code></pre> <p>(The definition is quite a bit different, but is still ultimately a wrapper around an instance of <code>Popen</code>.)</p>
1
2016-09-15T11:47:44Z
[ "python", "bash", "shell", "subprocess" ]
Concatenate/stack unpacked numpy array in certain axis to other arrays
39,510,084
<p>I want to create a numpy array <code>variables</code> with a certain structure, as in the example below, consisting of the variables <code>X</code> and <code>Y</code> for a meshgrid and additional parameters <code>params</code>. I need this in the context of plotting a 3D surface plot for a function <code>f(variables)</code>.</p> <p>This is how the <code>variables</code> array should look like with some arbitrary <code>params</code> 5, 5, 5.</p> <pre><code>import numpy as np X = np.linspace(0, 2, num=3) Y = np.linspace(0, 2, num=3) X, Y = np.meshgrid(X, Y) variables = np.array([X, Y, 5, 5, 5]) print(variables) </code></pre> <p>With the desired output:</p> <pre><code>array([[[ 0., 1., 2.], [ 0., 1., 2.], [ 0., 1., 2.]], [[ 0., 0., 0.], [ 1., 1., 1.], [ 2., 2., 2.]], 5, 5, 5]) </code></pre> <p>And my questions is how can I construct this when having the parameters 5, 5, 5 in a numpy array also. (And explicitly not having something like <code>[X, Y, [5, 5, 5]]</code>.)</p> <pre><code>params = np.array([5, 5, 5]) </code></pre> <p>I already looked at different numpy functions like stack or concatenate, but could not figure it out. I'm rather new to numpy, so thanks for any help.</p>
0
2016-09-15T11:36:05Z
39,512,379
<p>You can't get there from here.</p> <p>Numpy arrays are for storing cuboidal grids of data, where each entry is the same shape as every other entry.</p> <p>The best you can do here is have a <code>(5,)</code>-grid, containing <code>object</code>s, where each of the first two objects is itself a numpy array:</p> <pre><code>params = np.array([5, 5, 5]) XY = np.array([X, Y, None])[:-1] # trick numpy into using a 1d object array # there might be a better way to do this variables = np.concatenate((XY, params)) variables array([array([[ 0., 1., 2.], [ 0., 1., 2.], [ 0., 1., 2.]]), array([[ 0., 0., 0.], [ 1., 1., 1.], [ 2., 2., 2.]]), 5, 5, 5], dtype=object) </code></pre> <p>Are you sure you need a numpy array at all here? Is this enough:</p> <pre><code>variables = (X, Y) + tuple(params) </code></pre>
1
2016-09-15T13:30:53Z
[ "python", "arrays", "numpy" ]
Gather rows under the same key in Cassandra/Python
39,510,113
<p>I was working through the <a href="https://academy.datastax.com/resources/getting-started-time-series-data-modeling" rel="nofollow">Pattern 1</a> and was wondering if there is a way, in python or otherwise to "gather" all the rows with the same id into a row with dictionaries.</p> <pre><code>CREATE TABLE temperature ( weatherstation_id text, event_time timestamp, temperature text, PRIMARY KEY (weatherstation_id,event_time) ); </code></pre> <p>Insert some data</p> <pre><code>INSERT INTO temperature(weatherstation_id,event_time,temperature) VALUES ('1234ABCD','2013-04-03 07:01:00','72F'); INSERT INTO temperature(weatherstation_id,event_time,temperature) VALUES ('1234ABCD','2013-04-03 07:02:00','73F'); INSERT INTO temperature(weatherstation_id,event_time,temperature) VALUES ('1234ABCD','2013-04-03 07:03:00','73F'); INSERT INTO temperature(weatherstation_id,event_time,temperature) VALUES ('1234ABCD','2013-04-03 07:04:00','74F'); </code></pre> <p>Query the database.</p> <pre><code>SELECT weatherstation_id,event_time,temperature FROM temperature WHERE weatherstation_id='1234ABCD'; </code></pre> <p>Result:</p> <pre><code> weatherstation_id | event_time | temperature -------------------+--------------------------+------------- 1234ABCD | 2013-04-03 06:01:00+0000 | 72F 1234ABCD | 2013-04-03 06:02:00+0000 | 73F 1234ABCD | 2013-04-03 06:03:00+0000 | 73F 1234ABCD | 2013-04-03 06:04:00+0000 | 74F </code></pre> <p>Which works, but I was wondering if I can turn this into a row per <code>weatherstationid</code>.</p> <p>E.g.</p> <pre><code>{ "weatherstationid": "1234ABCD", "2013-04-03 06:01:00+0000": "72F", "2013-04-03 06:02:00+0000": "73F", "2013-04-03 06:03:00+0000": "73F", "2013-04-03 06:04:00+0000": "74F" } </code></pre> <p>Is there some parameter in cassandra driver that can be specified to gather by certain id (<code>weatherstationid</code>) and turn everything else into dictionary? Or is there needs to be some Python magic to turn list of rows into single row per id (or set of IDs)?</p>
0
2016-09-15T11:38:12Z
39,514,436
<p>Alex, you will have to do some post execution data processing to get this format. The driver returns row by row, no matter what row_factory you use. </p> <p>One of the reasons the driver cannot accomplish the format you suggest is that there is pagination involved internally (default fetch_size is 5000). So the results generated your way could potentially be partial or incomplete. Additionally, this can be easily be done with Python when the query execution is done and you are sure that all required results are fetched.</p>
1
2016-09-15T15:04:17Z
[ "python", "cassandra" ]
skype4py PlaceCall doesn't work on OSX
39,510,212
<p>I'm trying to write a python script which calls skype numbers for a music project. For some reason although the script can connect to the skype instance, when I make a call the app just waits and the call never goes through to the calling device. </p> <p>I've tried this in my own script, and the example record.py script and both don't work. </p> <p>I'm using Python 2.7.10, in 32 bit mode, on OSX 10.11.6. I'm using skype4py version 1.0.35. </p> <p>Does this work better on other platforms? </p>
0
2016-09-15T11:43:38Z
39,531,246
<p>I tried this on windows 8, and osx the API seems to be broken. On ubuntu trusty, the code works exactly as expected. </p>
1
2016-09-16T12:12:59Z
[ "python", "osx", "skype", "skype4py" ]
Django Auth user date_joined field datetime to string
39,510,274
<p>When i am fetching the stored datetime value from auth user in django the value comes as below is there a way to convert this into normal date time format may be like <code>"dd:mm:yyyy hh:mm:ss"</code> or some string value that can be displayed in better(other) format</p> <pre><code> date_joined = request.user.date_joined #date_joined value is #datetime.datetime(2016, 9, 11, 16, 6, 22, 314637, tzinfo=&lt;UTC&gt;) </code></pre>
0
2016-09-15T11:47:50Z
39,511,082
<p>You can format a datetime object using its <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow"><code>strftime()</code></a> method, for example like this:</p> <pre><code> date_joined = request.user.date_joined date_joined.strftime("%d:%m:%y %H:M:S") </code></pre> <p>If you want to display a datetime object in Django template, you can use the builtin <a href="https://docs.djangoproject.com/es/1.10/ref/templates/builtins/#date" rel="nofollow"><code>date</code></a> filter.</p> <pre><code>{{ date_joined|date:"d:m:Y H:i:s") </code></pre>
1
2016-09-15T12:30:11Z
[ "python", "django", "datetime" ]
Django project template loader setup
39,510,368
<p>Is it possible to set the django project template loading priority so that first of all it loads the apps' "templates" folder and after that the project "templates". If the template exists in the app folder, then use it. If it does not exist in the app folder, then try load from project folder.</p> <p>Or it is not normal way to load templates? I ask because I see in the exception, that Django tries to load first of all global templates:</p> <blockquote> <p><strong>Template-loader postmortem</strong></p> <p>Django tried loading these templates, in this order:</p> <p>Using engine django:</p> <ul> <li><p>django.template.loaders.filesystem.Loader: D:\myprojects\my-website\src\templates\home.html (Source does not exist)</p></li> <li><p>django.template.loaders.app_directories.Loader: C:\User\Python27\lib\site-packages\django\contrib\admin\templates\home.html (Source does not exist)</p></li> <li>django.template.loaders.app_directories.Loader: C:\User\Python27\lib\site-packages\django\contrib\auth\templates\home.html (Source does not exist)</li> <li>django.template.loaders.app_directories.Loader: D:\myprojects\my-website\src\website\templates\home.html (Source does not exist)</li> </ul> </blockquote>
0
2016-09-15T11:53:46Z
39,510,662
<p>Update your <code>TEMPLATES</code> setting, and put the <code>app_directories</code> loader before the <code>filesystem</code> loader.</p> <p>If you currently have <code>'APP_DIRS': True</code>, you will have to remove this, and add the <code>loaders</code> option.</p> <p>For example, you could change your <code>TEMPLATES</code> setting to:</p> <pre><code>TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'loaders': [ 'django.template.loaders.app_directories.Loader', 'django.template.loaders.filesystem.Loader', ], }, }] </code></pre>
1
2016-09-15T12:08:13Z
[ "python", "django", "django-templates" ]
Producing a sorted football league table in Python
39,510,399
<p>I have created a program which simulates an entire football season between teams. The user inputs the teams' names and their skill ratings. It then uses the Poisson distribution to compare their skill ratings and calculate the result between the two teams. After each match, the relevant lists are updated: the winning teams gains 3 points (so if it is the third team that has won then the value at index [2] increases by 3). I have a separate list for points, goals scored, goals conceded, games won, games drawn, and games lost (side note - is there a more efficient way of doing this?) The problem I have comes at the end of the season: each team is outputted with their data in the order that the teams were originally input. This is done using the fact that a team's name in the 'names' list is the same index as their points in the 'points' list. So the issue is, if I order the 'points' list then they will be out of sync with their names. I hope this makes sense but here is an example output for a season:</p> <pre><code>Enter number of teams in league: 4 Enter team 1 name: a Enter team 2 name: b Enter team 3 name: c Enter team 4 name: d Enter a skill: 1 Enter b skill: 3 Enter c skill: 5 Enter d skill: 8 =========================================== a's home games: =========================================== a 2 - 0 b a 0 - 2 c a 0 - 0 d =========================================== b's home games: =========================================== b 2 - 3 a b 1 - 0 c b 0 - 0 d =========================================== c's home games: =========================================== c 1 - 0 a c 1 - 0 b c 0 - 1 d =========================================== d's home games: =========================================== d 4 - 0 a d 2 - 0 b d 0 - 0 c Final table: a Skill: 1 Points: 7 For: 5 Against: 9 Goal difference: -4 Wins: 2 Draws: 1 Losses: 3 b Skill: 3 Points: 4 For: 3 Against: 8 Goal difference: -5 Wins: 1 Draws: 1 Losses: 4 c Skill: 5 Points: 10 For: 4 Against: 2 Goal difference: 2 Wins: 3 Draws: 1 Losses: 2 d Skill: 8 Points: 12 For: 7 Against: 0 Goal difference: 7 Wins: 3 Draws: 3 Losses: 0 [4, 7, 10, 12] </code></pre> <p>So what I would now like to do is to be able to print a final league table in descending points order, rather than the way it prints now just in index order.</p> <p>Sorry if this is poorly worded - the code for my program might be more useful so here it is:</p> <pre><code>import math import random #Lambda value in Poisson distribution for higher rated team lambOne = 1.148698355 #Lambda value for lower rated team lambTwo = 0.8705505633 #Poisson distribution calculating goals scored by the home team def homeMatch(homeRating,awayRating): global lambOne global x global y if x == y: raise ValueError else: lamb = lambOne**(int(homeRating)-int(awayRating)) homeScore = 0 z = random.random() while z &gt; 0: z = z - ((lamb**homeScore * math.exp(lamb * -1))/(math.factorial(homeScore))) homeScore += 1 return (homeScore-1) #Poisson distribution calculating goals scored by away team def awayMatch(homeRating,awayRating): global lambTwo global x global y #This check is to stop a team playing itself if x == y: raise ValueError else: lamb = lambTwo**(int(homeRating)-int(awayRating)) awayScore = 0 z = random.random() while z &gt; 0: z = z - ((lamb**awayScore * math.exp(lamb * -1))/(math.factorial(awayScore))) awayScore += 1 return (awayScore-1) #Selecting number of teams in league leagueSize = int(input("Enter number of teams in league: ")) #Initialising empty lists teamNames = [] teamSkill = [] teamPoints = [] teamFor = [] teamAgainst = [] teamWins = [] teamDraws = [] teamLosses = [] #Populating lists with number of zeroes equal to the number of teams (one zero for each) for x in range(leagueSize): teamPoints += [0] teamFor += [0] teamAgainst += [0] teamWins += [0] teamDraws += [0] teamLosses += [0] #Entering names and skill ratings for each team for i in range(leagueSize): teamNames += [input("Enter team "+str(i+1)+" name: ")] for j in range(leagueSize): teamSkill += [input("Enter "+teamNames[j]+" skill: ")] #Initialising variables homeScore = 0 awayScore = 0 #The season begins - each team plays all of its home games in one go for x in range(leagueSize): #input("Press enter to continue ") print("===========================================") print(teamNames[x]+"'s home games: ") print("===========================================\n") for y in range(leagueSize): error = 0 try: homeScore = homeMatch(teamSkill[x],teamSkill[y]) #Skipping a game to stop a team playing itself except ValueError: pass error += 1 try: awayScore = awayMatch(teamSkill[x],teamSkill[y]) except ValueError: pass if error == 0: #Updating lists print(teamNames[x],homeScore,"-",awayScore,teamNames[y],"\n") teamFor[x] += homeScore teamFor[y] += awayScore teamAgainst[x] += awayScore teamAgainst[y] += homeScore if homeScore &gt; awayScore: teamWins[x] += 1 teamLosses[y] += 1 teamPoints[x] += 3 elif homeScore == awayScore: teamDraws[x] += 1 teamDraws[y] += 1 teamPoints[x] += 1 teamPoints[y] += 1 else: teamWins[y] += 1 teamLosses[x] += 1 teamPoints[y] += 3 else: pass #Printing table (unsorted) print("Final table: ") for x in range(leagueSize): #Lots of formatting print(teamNames[x]+(15-len(teamNames[x]))*" "+" Skill: "+str(teamSkill[x])+(5-len(str(teamSkill[x])))*" "+" Points: "+str(teamPoints[x])+(5-len(str(teamPoints[x])))*" "+" For: "+str(teamFor[x])+(5-len(str(teamFor[x])))*" "+" Against: "+str(teamAgainst[x])+(5-len(str(teamPoints[x])))*" "+" Goal difference: "+str(teamFor[x]-teamAgainst[x])+(5-len(str(teamFor[x]-teamAgainst[x])))*" "+" Wins: "+str(teamWins[x])+(5-len(str(teamWins[x])))*" "+" Draws: "+str(teamDraws[x])+(5-len(str(teamDraws[x])))*" "+" Losses: "+str(teamLosses[x])+(5-len(str(teamLosses[x])))*" ") teamPoints.sort() print(teamPoints) </code></pre> <p>Sorry that this is very long and likely poorly worded and inefficient but I hope someone will be able to help me! Thank you very much :)</p>
2
2016-09-15T11:54:46Z
39,511,038
<p>While your current approach is (barely) workable, it makes it very difficult to (for example) change the information you want to store about each team. You might consider defining a Team class instead, each instance of which stores all the information about a specific team.</p> <pre><code>class Team: def __init__(self, name, skill): self.name = name self.skill = skill self.points = self.goals_for = self.goals_against = \ self.wins = self.draws = self.losses = 0 </code></pre> <p>This lets you create a new team object by passing a name and a skill level, in this way:</p> <pre><code>t1 = Team("Bradford City", 3) </code></pre> <p>t1 now has attributes <code>name</code> and <code>skill</code> with the given values, as well as a number of others (<code>points</code>, <code>goals_for</code>, and so on) whose values are all zero.</p> <p>Then you can initialise the league quite easily:</p> <pre><code>league_size = 4 teams = [] for _ in range(league_size): teams.append(Team(input("Name of team "+str(_)+": "), int(input("Team "+str(_)+"'s skill level: "))) </code></pre> <p>Then to print the skill level of each team you can loop over the list:</p> <pre><code>for team in teams: print(team.name, team.skill) </code></pre> <p>I hope this gives you some idea how your approach can be simplified. Your functions to play the matches can also take teams as arguments now, and modify the team objects directly according to the computed outcomes.</p> <p>To get to the answer you want, once you have a list of teams you can print them out sorted by the number of points they hold quite easily:</p> <pre><code>for team in sorted(teams, key=lambda t: t.points): print(team.name, team.skill, team.points, ...) </code></pre> <p>As far as I can see, none of your <code>global</code> declarations were necessary (if a name isn't defined locally Python will look for a global name to satisfy a reference). Besides which, inputs to a function should usually be passed as arguments, it's rather bad practice just to grab things from the environment!</p> <p>I hope this is sufficient for you to rework your program to be more tractable. As a beginner I'd say you have done extremely well to get this far. The next steps are going to be exciting for you!</p> <p><strong>Added later</strong>: Your all-play-all could be easier to program as a result:</p> <pre><code>for home in teams: for away in teams: if home is away: # Teams don't play themselves continue play_match(home, away) </code></pre> <p>The <code>play_match</code> function would simulate the match and adjust each team's statistics. Of course you could simulate the away matches with another line reading</p> <pre><code> play_match(away, home) </code></pre> <p>though I'm not sure your algorithm is symmetrical for that.</p>
3
2016-09-15T12:28:07Z
[ "python", "list", "sorting" ]
Django combine different tables in separate table
39,510,526
<p>I have 2 tables and wanted to <code>combine</code> 1st and 2nd table and show it in 3rd table</p> <pre><code> class Date(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Month(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name </code></pre> <p>I have my 3rd table which is combination of 1st and 2nd table</p> <p>I tried to use <code>models.ForeignKey(Date,Month)</code> in my 3rd table but only <strong>Month table data</strong> was shown in admin panel <strong>Date table data</strong> was not populated </p> <p>My 3rd table looks like this</p> <pre><code>class Group(models.Model): name = models.ForeignKey(Month,Date) def __unicode__(self): return self.name </code></pre> <p>I there any alternate way of populating data from different tables?</p> <p>Any help is populating data of different tables in one table is very helpfull</p> <p>Thanks in advance</p>
0
2016-09-15T12:00:54Z
39,511,339
<p>To get 1st and 2nd table content into 3rd table you need to write separate foreign keys for each model. We should not assign a single foreign key for both models.</p> <pre><code>class Group(models.Model): date = models.ForeignKey(Date) month = models.ForeignKey(Month) def __unicode__(self): return str(self.date.name) + str(seld.month.name) </code></pre> <p>The above code will return both Date and Month names.</p>
2
2016-09-15T12:42:13Z
[ "python", "django", "django-models" ]
How to do regression using tensorflow with series output?
39,510,597
<p>I want to build a regression model with 2 output nodes using tensorflow. I search a code which can build regression model but with 1 output nodes.</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/boston.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/boston.py</a></p> <pre><code>from __future__ import absolute_import from __future__ import division from __future__ import print_function from sklearn import cross_validation from sklearn import metrics from sklearn import preprocessing import tensorflow as tf from tensorflow.contrib import learn def main(unused_argv): # Load dataset boston = learn.datasets.load_dataset('boston') x, y = boston.data, boston.target # Split dataset into train / test x_train, x_test, y_train, y_test = cross_validation.train_test_split( x, y, test_size=0.2, random_state=42) # Scale data (training set) to 0 mean and unit standard deviation. scaler = preprocessing.StandardScaler() x_train = scaler.fit_transform(x_train) # Build 2 layer fully connected DNN with 10, 10 units respectively. feature_columns = learn.infer_real_valued_columns_from_input(x_train) regressor = learn.DNNRegressor( feature_columns=feature_columns, hidden_units=[10, 10]) # Fit regressor.fit(x_train, y_train, steps=5000, batch_size=1) # Predict and score y_predicted = list( regressor.predict(scaler.transform(x_test), as_iterable=True)) score = metrics.mean_squared_error(y_predicted, y_test) print('MSE: {0:f}'.format(score)) if __name__ == '__main__': tf.app.run() </code></pre> <p>I am new to tensorflow, so I searched for the code which has similarity to how mine works, but the output of the code is one.</p> <p>In my model, the input is N*1000, and the output is N*2. I wonder are there effective and efficient code for regression. Please give me some example.</p>
0
2016-09-15T12:04:29Z
39,528,834
<p>Actually, I find a workable code using DNNRegressor:</p> <pre><code>import numpy as np from sklearn.cross_validation import train_test_split from tensorflow.contrib import learn import tensorflow as tf import logging #logging.getLogger().setLevel(logging.INFO) #Some fake data N=200 X=np.array(range(N),dtype=np.float32)/(N/10) X=X[:,np.newaxis] #Y=np.sin(X.squeeze())+np.random.normal(0, 0.5, N) Y = np.zeros([N,2]) Y[:,0] = X.squeeze() Y[:,1] = X.squeeze()**2 X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=0.8, test_size=0.2) reg=learn.DNNRegressor(hidden_units=[10,10]) reg.fit(X_train,Y_train[:,0],steps=500) </code></pre> <p>But, this code will work only if the shape of Y_train is N*1, and it will fail when the shape of Y_train is N*2.</p> <p>However, I want to build a regress model and the input is N*1000, the output is N*2. And I can't fix it.</p>
0
2016-09-16T10:07:19Z
[ "python", "output", "tensorflow", "regression" ]
Convert list of list of integers into a list of strings
39,510,778
<p>I have a list of strings:</p> <pre><code>['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]'] </code></pre> <p>I want output to look like </p> <pre><code>['28','82','253',2530',5302'] </code></pre> <p>I've tried using </p> <pre><code>string1= ''.join(str(e) for e in list[0]) </code></pre> <p>I get output for print (string1) as:</p> <pre><code>[2, 8] </code></pre> <p>What am i doing wrong here?</p>
2
2016-09-15T12:14:01Z
39,510,804
<p>You actually don't have a <code>list</code> of <code>list</code>, you have a <code>list</code> of <code>str</code>. Therefore you can use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a> to interpret each string as a list, then convert to <code>str</code> and <code>join</code>.</p> <pre><code>&gt;&gt;&gt; l = ['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]'] &gt;&gt;&gt; from ast import literal_eval &gt;&gt;&gt; [''.join(str(j) for j in literal_eval(i)) for i in l] ['28', '82', '253', '2530', '5302'] </code></pre>
4
2016-09-15T12:16:01Z
[ "python", "string", "list" ]
Convert list of list of integers into a list of strings
39,510,778
<p>I have a list of strings:</p> <pre><code>['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]'] </code></pre> <p>I want output to look like </p> <pre><code>['28','82','253',2530',5302'] </code></pre> <p>I've tried using </p> <pre><code>string1= ''.join(str(e) for e in list[0]) </code></pre> <p>I get output for print (string1) as:</p> <pre><code>[2, 8] </code></pre> <p>What am i doing wrong here?</p>
2
2016-09-15T12:14:01Z
39,510,866
<p>If you want to use built-in functions only (without imports), you can define a function that parses only the numbers and map that function to your list.</p> <pre><code>def remove_non_digits(z): return "".join(k if k.isdigit() else "" for k in z) &gt;&gt;&gt; map(remove_non_digits, a) ['28', '82', '253', '2530', '5302'] </code></pre>
2
2016-09-15T12:19:12Z
[ "python", "string", "list" ]
Mean or max pooling with masking support in Keras
39,510,809
<pre><code>... print('Build model...') model = Sequential() model.add(Embedding(max_features, 128)) model.add(LSTM(size, return_sequences=True, dropout_W=0.2 dropout_U=0.2)) model.add(GlobalAveragePooling1D()) model.add(Dense(1)) model.add(Activation('sigmoid')) .... </code></pre> <p>I need to be able to take the mean or max of the vectors for all time steps in a sample after LSTM layer before giving this mean or max vector to the dense layer in Keras. </p> <p>I think <code>timedistributedmerge</code> was able to do this but it was deprecated. Using <code>return_sequences=True</code> I can obtain the vectors for all time steps in a sample after the LSTM layer. However, <code>GlobalAveragePooling1D()</code> is not compatible with masking and it considers all time steps whereas I need only the non-masked time steps. </p> <p>I saw posts recommending the <code>Lambda</code> layer but these also do not take masking into account. Any help would be appreciated.</p>
1
2016-09-15T12:16:22Z
39,534,110
<p>Since average pooling is only doing a mean over one axis, you just need to correct the number of elements in the mean since loss masking is handled at the end, not here. You can do this probably with something like this:</p> <pre><code>class GlobalAveragePooling1DMasked(GlobalAveragePooling1D): def call(self, x, mask=None): if mask != None: return K.sum(x, axis=1) / K.sum(mask, axis=1) else: return super().call(x) </code></pre>
0
2016-09-16T14:35:28Z
[ "python", "masking", "keras", "lstm", "pooling" ]
Process each line of text file using Python
39,510,824
<p>I am fairly new to Python. I have a text file containing many blocks of data in following format along with other unnecessary blocks.</p> <pre><code> NOT REQUIRED :: 123 Connected Part-1:: A ~$ Connected Part-3:: B ~$ Connector Location:: 100 200 300 ~$ NOT REQUIRED :: 456 Connected Part-2:: C ~$ </code></pre> <p>i wish to extract the info (A,B,C, 100 200 300) corresponding to each property ( connected part-1, Connector location) and store it as list to use it later. I have prepared following code which reads file, cleans the line and store it as list.</p> <pre><code> import fileinput with open('C:/Users/file.txt') as f: content = f.readlines() for line in content: if 'Connected Part-1' in line or 'Connected Part-3' in line: if 'Connected Part-1' in line: connected_part_1 = [s.strip(' \n ~ $ Connected Part -1 ::') for s in content] print ('PART_1:',connected_part_1) if 'Connected Part-3' in line: connected_part_3 = [s.strip(' \n ~ $ Connected Part -3 ::') for s in content] print ('PART_3:',connected_part_3) if 'Connector Location' in line: # removing unwanted characters and converting into the list content_clean_1 = [s.strip('\n ~ $ Connector Location::') for s in content] #converting a single string item in list to a string s = " ".join(content_clean_1) # splitting the string and converting into a list weld_location= s.split(" ") print ('POSITION',weld_location) </code></pre> <p>here is the output</p> <pre><code> PART_1: ['A', '\t\tConnector Location:: 100.00 200.00 300.00', '\t\tConnected Part-3:: C~\t'] POSITION ['d', 'Part-1::', 'A', '\t\tConnector', 'Location::', '100.00', '200.00', '300.00', '\t\tConnected', 'Part-3::', 'C~\t'] PART_3: ['1:: A', '\t\tConnector Location:: 100.00 200.00 300.00', '\t\tConnected Part-3:: C~\t'] </code></pre> <p>From the output of this program, i may conclude that, since 'content' is the string consisting all the characters in the file, the program is not reading an individual line. Instead it is considering all text as single string. Could anyone please help in this case?</p> <p>I am expecting following output:</p> <pre><code> PART_1: ['A'] PART_3: ['C'] POSITION: ['100.00', '200.00','300.00'] </code></pre> <p>(Note) When i am using individual files containing single line of data, it works fine. Sorry for such a long question</p>
0
2016-09-15T12:17:14Z
39,512,204
<p>I will try to make it clear, and show how I would do it without <code>regex</code>. First of all, the biggest issue with the code presented is that when using the <code>string.strip</code> function the entire content list is being read:</p> <pre><code>connected_part_1 = [s.strip(' \n ~ $ Connected Part -1 ::') for s in content] </code></pre> <p>Content is the entire file lines, I think you want simply something like:</p> <pre><code>connected_part_1 = [line.strip(' \n ~ $ Connected Part -1 ::')] </code></pre> <p>How to parse the file is a bit subjective, but given the file format posted as input, I would do it like this:</p> <pre><code>templatestr = "{}: {}" with open('inputreadlines.txt') as f: content = f.readlines() for line in content: label, value = line.split('::') ltokens = label.split() if ltokens[0] == 'Connected': print(templatestr.format( ltokens[-1], #The last word on the label value.split()[:-1])) #the split value without the last word '~$' elif ltokens[0] == 'Connector': print(value.split()[:-1]) #the split value without the last word '~$' else: #NOT REQUIRED pass </code></pre> <p>You can use the <code>string.strip</code> function to remove the funny characters '~$' instead of removing the last token as in the example.</p>
0
2016-09-15T13:24:02Z
[ "python", "python-3.x" ]
How to copy a .bin file to a text file in Python
39,510,827
<p>I'm trying to take a file with .bin suffix, encode it and then to send it to someone(sending it as .bin is not supported)...the problem is that when i use the command :</p> <pre><code>with open('myfile.bin','r') as fileToCopy: </code></pre> <p>I got an error messages </p> <pre><code>'charmap' codec can't decode byte 0x90 in position 192:chatacter maps to &lt;undefined&gt; </code></pre> <p>So i thought about a workaround which is converting the file to .txt and then to send it. I tried to copy a binary file to a text file, the code that I used is</p> <pre><code>with open('myfile.bin','rb') as fileToCopy: with open('newfile.txt,'w') as myNewFile: for line in fileToCopty: myNewFile.write(line) </code></pre> <p>and the .bin file contains lines like this:</p> <pre><code>244e 504b 0100 3900 9000 0003 0100 0000 8000 0003 0200 0000 a432 0002 0000 0000 0002 0a02 0103 0000 0001 0a02 0003 0000 0001 0a02 0103 0000 0002 0a02 0003 0000 </code></pre> <p>But the results are a file containing rubbish. I tried also to decode the bytes as utf-8 format but i got this error message:</p> <pre><code>'utf-8' codec can't decode byte 0xfa in position 1:invalid start bye </code></pre> <p>The code that I used to decode to 'utf-8 format is :</p> <pre><code>with open('myfile.bin','rb') as fileToCopy: with open('newfile.txt,'w') as myNewFile: for line in fileToCopty: myNewFile.write(line.decode('utf-8')) </code></pre> <p>Am I doing something wrong ? Is there another way to do this ?</p>
0
2016-09-15T12:17:19Z
39,511,331
<p>It's not clear what you are trying to do. Either you are trying to copy an existing file <code>myfile.bin</code> to a new file <code>newfile.txt</code> or you're trying to convert the binary file to a human readable format.</p> <p>Assuming it's your goal to copy the file <code>myfile.bin</code> to <code>newfile.txt</code> you might have a look at the module <a href="https://docs.python.org/3/library/shutil.html" rel="nofollow">shutil</a> from the Python standard library. This contains high-level file operations such as <code>copy</code>, <code>move</code>, <code>delete</code> and more.</p> <p>If it's your goal to decode the content of the file into a human readable format and your only information about the file is its <code>.bin</code> ending you might have a problem. The binary file could encode any information such as images, texts or videos. Without knowing the type of the encoding the content is more or less useless to you.</p>
2
2016-09-15T12:41:36Z
[ "python", "file", "text", "binary", "bin" ]
extract data from website using python
39,510,830
<p>I recently started learning python and one of the first projects I did was to scrap updates from my son's classroom web page and send me notifications that they updated the site. This turned out to be an easy project so I wanted to expand on this and create a script that would automatically check if any of our lotto numbers hit. Unfortunately I haven't been able to figure out how to get the data from the website. Here is one of my attempts from last night.</p> <pre><code>from bs4 import BeautifulSoup import urllib.request webpage = "http://www.masslottery.com/games/lottery/large-winningnumbers.html" websource = urllib.request.urlopen(webpage) soup = BeautifulSoup(websource.read(), "html.parser") span = soup.find("span", {"id": "winning_num_0"}) print (span) Output is here... &lt;span id="winning_num_0"&gt;&lt;/span&gt; </code></pre> <p>The output listed above is also what I see if I "view source" with a web browser. When I "inspect Element" with the web browser I can see the winning numbers in the inspect element panel. Unfortunately I'm not even sure how/where the web browser is getting the data. is it loading from another page or a script in the background? I thought the following tutorial was going to help me but I wasn't able to get the data using similar commands. </p> <p><a href="http://zevross.com/blog/2014/05/16/using-the-python-library-beautifulsoup-to-extract-data-from-a-webpage-applied-to-world-cup-rankings/" rel="nofollow">http://zevross.com/blog/2014/05/16/using-the-python-library-beautifulsoup-to-extract-data-from-a-webpage-applied-to-world-cup-rankings/</a></p> <p>Any help is appreciated. Thanks</p>
0
2016-09-15T12:17:31Z
39,511,176
<p>If you look closely at the source of the page (I just used <code>curl</code>) you can see this block</p> <pre><code>&lt;script type="text/javascript"&gt; // &lt;![CDATA[ var dataPath = '../../'; var json_filename = 'data/json/games/lottery/recent.json'; var games = new Array(); var sessions = new Array(); // ]]&gt; &lt;/script&gt; </code></pre> <p>That <code>recent.json</code> stuck out like a sore thumb (I actually missed the <code>dataPath</code> part at first).</p> <p>After giving that a try, I came up with this:</p> <pre><code>curl http://www.masslottery.com/data/json/games/lottery/recent.json </code></pre> <p>Which, as lari points out in the comments, is way easier than scraping HTML. This easy, in fact:</p> <pre><code>import json import urllib.request from pprint import pprint websource = urllib.request.urlopen('http://www.masslottery.com/data/json/games/lottery/recent.json') data = json.loads(websource.read().decode()) pprint(data) </code></pre> <p><code>data</code> is now a dict, and you can do whatever kind of dict-like things you'd like to do with it. And good luck ;)</p>
0
2016-09-15T12:34:02Z
[ "python", "python-3.x" ]
lambda python function in reversing list
39,511,011
<pre><code>scores = [] with open("scores.txt") as f: for line in f: name, score = line.split(',') score = int(score) scores.append((name, score)) scores.sort(key=lambda s: s[1]) for name, score in scores: print(name + ", " + str(score)) </code></pre> <p>This code can be used to show a txt file looking like this (disordered):</p> <pre><code>alpha, 3 beta, 1 gamma, 2 </code></pre> <p>To looking like this:</p> <pre><code>beta, 1 gamma, 2 alpha, 3 </code></pre> <p>How can I modify the code so that it instead prints as:</p> <pre><code>alpha, 3 gamma, 2 beta, 1 </code></pre>
0
2016-09-15T12:26:40Z
39,511,040
<p>Use the <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>reverse</code></a> argument to <code>list.sort()</code>:</p> <pre><code>scores.sort(key=lambda s: s[1], reverse=True) </code></pre> <p>From the documentation:</p> <blockquote> <p><em>reverse</em> is a boolean value. If set to <code>True</code>, then the list elements are sorted as if each comparison were reversed.</p> </blockquote>
1
2016-09-15T12:28:12Z
[ "python" ]
lambda python function in reversing list
39,511,011
<pre><code>scores = [] with open("scores.txt") as f: for line in f: name, score = line.split(',') score = int(score) scores.append((name, score)) scores.sort(key=lambda s: s[1]) for name, score in scores: print(name + ", " + str(score)) </code></pre> <p>This code can be used to show a txt file looking like this (disordered):</p> <pre><code>alpha, 3 beta, 1 gamma, 2 </code></pre> <p>To looking like this:</p> <pre><code>beta, 1 gamma, 2 alpha, 3 </code></pre> <p>How can I modify the code so that it instead prints as:</p> <pre><code>alpha, 3 gamma, 2 beta, 1 </code></pre>
0
2016-09-15T12:26:40Z
39,511,066
<p>Just use <code>scores[::-1]</code> instead of <code>scores</code> in the last for-loop. Here's a small illustration of this behaviour:</p> <pre><code>a=list(range(10)) print(a[::-1]) </code></pre>
1
2016-09-15T12:29:28Z
[ "python" ]
lambda python function in reversing list
39,511,011
<pre><code>scores = [] with open("scores.txt") as f: for line in f: name, score = line.split(',') score = int(score) scores.append((name, score)) scores.sort(key=lambda s: s[1]) for name, score in scores: print(name + ", " + str(score)) </code></pre> <p>This code can be used to show a txt file looking like this (disordered):</p> <pre><code>alpha, 3 beta, 1 gamma, 2 </code></pre> <p>To looking like this:</p> <pre><code>beta, 1 gamma, 2 alpha, 3 </code></pre> <p>How can I modify the code so that it instead prints as:</p> <pre><code>alpha, 3 gamma, 2 beta, 1 </code></pre>
0
2016-09-15T12:26:40Z
39,511,311
<p>Use <code>reverse</code> when you sort: </p> <pre><code>&gt;&gt;&gt; l = [('a', 1), ('c',5), ('a', 2), ('b', 1)] &gt;&gt;&gt; l.sort(key=lambda i: i[1], reverse=True) &gt;&gt;&gt; l [('c', 5), ('a', 2), ('a', 1), ('b', 1)] </code></pre> <p>You can use it with <code>sorted</code>: </p> <pre><code>&gt;&gt;&gt; l = [('a', 1), ('c',5), ('a', 2), ('b', 1)] &gt;&gt;&gt; sorted(l, key=lambda i: i[1], reverse=True) [('c', 5), ('a', 2), ('a', 1), ('b', 1)] &gt;&gt;&gt; </code></pre>
0
2016-09-15T12:40:29Z
[ "python" ]
Resample xarray Dataset to annual frequency using only winter data
39,511,062
<p>I have a dataset which consists of daily x,y gridded meteorological data for several years. I am interested in calculating annual means of winter data only, ie. not including the summer data as well.</p> <p>I think that I need to use the <code>resample</code> command with, e.g. a frequency of <code>AS-OCT</code> to resample the time series to annual frequency with winter beginning in October each year (it's northern latitudes). </p> <p>What I can't work out is how to specify that I only want to use data from months October through April/May, ignoring June, July and August. </p> <p>As the resample function works with <code>ndarray</code> objects I came up with a fairly unportable way of doing this for a sum:</p> <pre><code>def winter(x,axis): # Only use data from 1 October to end of April (day 211) return np.sum(x[0:211,:,:],axis=0) win_sum = all_data.resample('AS-OCT',how=winter,dim='TIME') </code></pre> <p>but I feel like there should be a more elegant solution. Any ideas?</p>
1
2016-09-15T12:29:15Z
39,516,454
<p>The trick is to create a mask for the dates you wish to exclude. You can do this by using groupby to extract the month.</p> <pre class="lang-python prettyprint-override"><code>import xarray as xr import pandas as pd import numpy as np # create some example data at daily resolution that also has a space dimension time = pd.date_range('01-01-2000','01-01-2020') space = np.arange(0,100) data = np.random.rand(len(time), len(space)) da = xr.DataArray(data, dims=['time','space'], coords={'time': time, 'space': space}) # this is the trick -- use groupby to extract the month number of each day month = da.groupby('time.month').apply(lambda x: x).month # create a boolen Dataaray that is true only during winter winter = (month &lt;= 4) | (month &gt;= 10) # mask the values not in winter and resample annualy starting in october da_winter_annmean = da.where(winter).resample('AS-Oct', 'time') </code></pre> <p>Hopefully this works for you. It is slightly more elegant, but the groupby trick still feels kind of hackish. Maybe there is still a better way.</p>
3
2016-09-15T16:51:52Z
[ "python", "python-xarray" ]
Extract nested tags with other text data as string in scrapy
39,511,122
<p>I am trying to extract data. Here is the specific part of the html-</p> <pre><code> &lt;div class="readable"&gt; &lt;span id="freeTextContainer2123443890291117716"&gt;I write because I need to. &lt;br&gt;I review because I want to. &lt;br&gt;I pay taxes because I have to. &lt;br&gt;&lt;br&gt;If you want to follow me, my username is @colleenhoover pretty much everywhere except my email, which is colleenhooverbooks@gmail.com &lt;br&gt;&lt;br&gt;Founder of &lt;a target="_blank" href="http://www.thebookwormbox.com" rel="nofollow"&gt;www.thebookwormbox.com&lt;/a&gt; &lt;br&gt;&lt;br&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I want output like this-</p> <pre><code> I write because I need to. I review because I want to. I pay taxes because I have to. If you want to follow me, my username is @colleenhoover pretty much everywhere except my email, which is colleenhooverbooks@gmail.com Founder of www.thebookwormbox.com </code></pre> <p>I am trying this-</p> <pre><code>aboutauthor=response.xpath('//div[@id="aboutAuthor"]/div[@class="bigBoxBody"]/div[@class="bigBoxContent containerWithHeaderContent"]/div[@class="readable"]/span[1]/text()').extract() if len(response.xpath('//div[@id="aboutAuthor"]/div[@class="bigBoxBody"]/div[@class="bigBoxContent containerWithHeaderContent"]/div[@class="readable"]/span')) == 1 else response.xpath('//div[@id="aboutAuthor"]/div[@class="bigBoxBody"]/div[@class="bigBoxContent containerWithHeaderContent"]/div[@class="readable"]/span[2]/text()').extract() print aboutauthor </code></pre> <p>And get the output-</p> <pre><code>[u'I write because I need to. ', u'I review because I want to. ', u'I pay taxes because I have to. ', u'If you want to follow me, my username is @colleenhoover pretty much everywhere except my email, which is colleenhooverbooks@gmail.com', u'Founder of ', u' '] </code></pre> <p>What i do so that i get <code>www.thebookwormbox.com</code> with the output ?</p>
0
2016-09-15T12:31:51Z
39,513,567
<p>As per my comment, you can use xpath with <code>//text()</code> to get all the children's text content.</p>
0
2016-09-15T14:22:16Z
[ "python", "scrapy" ]
Python NetworkX creating graph from incidence matrix
39,511,179
<p>I have an incidence matrix (where the rows are nodes and the columns are edges) as follows (it is read from a text file into a NumPy array):</p> <pre><code>[[1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 0 0 0] [1 1 1 1 1 0 1 1 0 0] [0 0 1 1 1 0 1 0 0 0] [1 1 1 1 1 1 0 0 0 0] [1 1 0 1 1 0 0 0 0 0] [1 0 1 0 0 1 0 1 0 0] [0 1 0 1 1 0 0 0 0 0] [1 1 1 0 0 1 0 0 0 0] [0 0 1 1 0 1 0 0 0 0] [1 0 1 0 0 1 0 0 0 0] [1 0 1 1 0 0 0 0 0 0] [1 0 0 0 0 0 1 1 0 0] [1 1 0 0 0 0 1 0 0 0] [0 1 0 0 0 1 0 0 0 0] [1 0 0 1 0 0 0 0 0 0] [0 0 1 1 0 0 0 0 0 0] [1 1 0 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 0] [1 0 0 0 0 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0] [0 0 0 0 0 0 1 0 0 0] [0 1 0 0 0 0 0 0 0 0]] </code></pre> <p>I would like to create a graph using NetworkX from this matrix, but could not find how to do that. NetworkX <a href="https://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html" rel="nofollow">from_numpy_matrix</a> works only with adjacency matrices. <a href="https://stackoverflow.com/questions/28549762/how-to-create-an-incidence-matrix">Here</a> is a good example of how to create an incidence matrix using NetworkX (but that's not my case, because I have already an incidence matrix to begin with). I have also tried <a href="https://dschult-networkx.readthedocs.io/en/latest/_modules/networkx/convert_matrix.html" rel="nofollow">this</a>, but got the nasty error: </p> <pre><code>File "C:\Python27\lib\site-packages\networkx\convert.py", line 150, in to_networkx_graph "Input is not a correct numpy matrix or array.") networkx.exception.NetworkXError: Input is not a correct numpy matrix or array. </code></pre> <p>Looks a simple question, but perhaps it isn't. Can anyone help me with it?</p> <p>Thanks in advance!</p>
2
2016-09-15T12:34:09Z
39,515,259
<p>Networkx has a handy <a href="http://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html" rel="nofollow"><code>nx.from_numpy_matrix</code> function</a> taking an adjacency matrix, so once we convert the incidence matrix to an adjacency matrix, we're good.</p> <p>Say we start with the incidence matrix</p> <pre><code>im = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]]) </code></pre> <p>To convert it to an adjacency matrix, first let's see which nodes are connected:</p> <pre><code>am = (np.dot(im, im.T) &gt; 0).astype(int) </code></pre> <p>Here we're just checking if any two nodes have at least one edge between them. </p> <p>If you want to remove self loops, you can call</p> <pre><code>np.fill_diagonal(am, 0) </code></pre> <p>Let's see now <code>am</code>:</p> <pre><code>&gt;&gt;&gt; am array([[0, 1, 0], [1, 0, 0], [0, 0, 0]]) </code></pre> <p>To create the graph, now we can just call</p> <pre><code>networkx.from_numpy_matrix(am) </code></pre>
2
2016-09-15T15:44:59Z
[ "python", "networkx" ]
Python - Add checkbox to every row in QTableWidget
39,511,181
<p>I am trying to add a checkbow to every row in a QTableWidget, unfortunately it only seems to appear in the first row. Here is my code:</p> <pre><code>data = ['first_row', 'second_row', 'third_row'] nb_row = len(data) nb_col = 2 qTable = self.dockwidget.tableWidget qTable.setRowCount(nb_row) qTable.setColumnCount(nb_col) chkBoxItem = QTableWidgetItem() for row in range(nb_row): for col in [0]: item = QTableWidgetItem(str(data[row])) qTable.setItem(row,col,item) for col in [1]: chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) qTable.setItem(row,col,chkBoxItem) </code></pre> <p>Am I missing something obvious?</p> <p>I checked the following posts also:</p> <ul> <li><a href="http://stackoverflow.com/questions/12366521/pyqt-checkbox-in-qtablewidget">PyQt : Checkbox in QTableWidget</a></li> <li><a href="http://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row">PyQt allign checkbox and put it in every row</a></li> </ul>
0
2016-09-15T12:34:10Z
39,511,449
<p>Ok, I just had to put <code>chkBoxItem = QTableWidgetItem()</code> inside the last loop (<em>I guess it has to create a new <code>QTableWidgetItem()</code> item for each row</em>...):</p> <pre><code>for col in [1]: chkBoxItem = QTableWidgetItem() chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) qTable.setItem(row,col,chkBoxItem) </code></pre>
0
2016-09-15T12:48:59Z
[ "python", "pyqt", "qtablewidget", "qcheckbox" ]
SQLAlchemy can't join two tables with two foreign keys between them
39,511,232
<p>The code below does not work due to this line <code>owner_id = Column(Integer, ForeignKey('employees.employee_id'))</code> in Manager class. SQLAlchemy generates error message:</p> <blockquote> <p>AmbiguousForeignKeysError: Can't determine join between 'employees' and > 'managers'; tables have more than one foreign key constraint relationship > between them. Please specify the 'onclause' of this join explicitly.</p> </blockquote> <p>Please help to fix that!</p> <p>The idea is that every Manager is an Employee and works for some Owner. There might be zero, one or more Managers working for an Owner. </p> <pre><code>from sqlalchemy import (Table, Column, Integer, String, create_engine, MetaData, ForeignKey) from sqlalchemy.orm import mapper, create_session from sqlalchemy.ext.declarative import declarative_base e = create_engine('sqlite:////tmp/foo.db', echo=True) Base = declarative_base(bind=e) class Employee(Base): __tablename__ = 'employees' employee_id = Column(Integer, primary_key=True) name = Column(String(50)) type = Column(String(30), nullable=False) __mapper_args__ = {'polymorphic_on': type} def __init__(self, name): self.name = name class Manager(Employee): __tablename__ = 'managers' __mapper_args__ = {'polymorphic_identity': 'manager'} employee_id = Column(Integer, ForeignKey('employees.employee_id'), primary_key=True) manager_data = Column(String(50)) owner_id = Column(Integer, ForeignKey('employees.employee_id')) def __init__(self, name, manager_data): super(Manager, self).__init__(name) self.manager_data = manager_data class Owner(Manager): __tablename__ = 'owners' __mapper_args__ = {'polymorphic_identity': 'owner'} employee_id = Column(Integer, ForeignKey('managers.employee_id'), primary_key=True) owner_secret = Column(String(50)) def __init__(self, name, manager_data, owner_secret): super(Owner, self).__init__(name, manager_data) self.owner_secret = owner_secret Base.metadata.drop_all() Base.metadata.create_all() s = create_session(bind=e, autoflush=True, autocommit=False) o = Owner('nosklo', 'mgr001', 'ownerpwd') s.add(o) s.commit() </code></pre>
0
2016-09-15T12:36:46Z
39,514,965
<p>You are both extending parent model as well as defining relationship to the same parent model.</p> <p>simply use one way, you could simply created relations and have all your models extend base class</p> <pre><code>class Employee(Base): __tablename__ = 'employees' employee_id = Column(Integer, primary_key=True) ... class Owner(Base): __tablename__ = 'owners' __mapper_args__ = {'polymorphic_identity': 'owner'} owner_id = Column(Integer, primary_key=True) ... ... class Manager(Base): __tablename__ = 'managers' __mapper_args__ = {'polymorphic_identity': 'manager'} manager_id = Column(Integer, primary_key=True) employee_id = Column(Integer, ForeignKey('employees.employee_id'), primary_key=True) owner_id = Column(Integer, ForeignKey('owners.owner_id')) ... ... </code></pre> <p>add the rest of relevant field where indicated as ....</p>
0
2016-09-15T15:29:51Z
[ "python", "sqlalchemy" ]
SQLAlchemy can't join two tables with two foreign keys between them
39,511,232
<p>The code below does not work due to this line <code>owner_id = Column(Integer, ForeignKey('employees.employee_id'))</code> in Manager class. SQLAlchemy generates error message:</p> <blockquote> <p>AmbiguousForeignKeysError: Can't determine join between 'employees' and > 'managers'; tables have more than one foreign key constraint relationship > between them. Please specify the 'onclause' of this join explicitly.</p> </blockquote> <p>Please help to fix that!</p> <p>The idea is that every Manager is an Employee and works for some Owner. There might be zero, one or more Managers working for an Owner. </p> <pre><code>from sqlalchemy import (Table, Column, Integer, String, create_engine, MetaData, ForeignKey) from sqlalchemy.orm import mapper, create_session from sqlalchemy.ext.declarative import declarative_base e = create_engine('sqlite:////tmp/foo.db', echo=True) Base = declarative_base(bind=e) class Employee(Base): __tablename__ = 'employees' employee_id = Column(Integer, primary_key=True) name = Column(String(50)) type = Column(String(30), nullable=False) __mapper_args__ = {'polymorphic_on': type} def __init__(self, name): self.name = name class Manager(Employee): __tablename__ = 'managers' __mapper_args__ = {'polymorphic_identity': 'manager'} employee_id = Column(Integer, ForeignKey('employees.employee_id'), primary_key=True) manager_data = Column(String(50)) owner_id = Column(Integer, ForeignKey('employees.employee_id')) def __init__(self, name, manager_data): super(Manager, self).__init__(name) self.manager_data = manager_data class Owner(Manager): __tablename__ = 'owners' __mapper_args__ = {'polymorphic_identity': 'owner'} employee_id = Column(Integer, ForeignKey('managers.employee_id'), primary_key=True) owner_secret = Column(String(50)) def __init__(self, name, manager_data, owner_secret): super(Owner, self).__init__(name, manager_data) self.owner_secret = owner_secret Base.metadata.drop_all() Base.metadata.create_all() s = create_session(bind=e, autoflush=True, autocommit=False) o = Owner('nosklo', 'mgr001', 'ownerpwd') s.add(o) s.commit() </code></pre>
0
2016-09-15T12:36:46Z
39,518,177
<p>SQLAlchemy is confused about how to join <code>Manager</code> to <code>Employee</code> because you have multiple foreign keys between the two tables, <code>employee_id</code> and <code>owner_id</code>. In this case, you need to specify the <code>inherit_condition</code> to the mapper explicitly:</p> <pre><code>class Manager(Employee): __tablename__ = 'managers' employee_id = Column(Integer, ForeignKey('employees.employee_id'), primary_key=True) manager_data = Column(String(50)) owner_id = Column(Integer, ForeignKey('employees.employee_id')) __mapper_args__ = {'polymorphic_identity': 'manager', 'inherit_condition': employee_id == Employee.employee_id} </code></pre>
1
2016-09-15T18:39:16Z
[ "python", "sqlalchemy" ]
Filtering a pandas data frame with a variable
39,511,378
<p>I'm stuck on something simple but I can't see it despite reading the docs and relevant SO questions. This involves filtering records from data that comes out of a WordPress database. </p> <p>Create some data:</p> <pre><code>import pandas as pd data = {'number': [1,2,3],\ 'field': ['billing_last_name', 'shipping_last_name', 'field_1435'],\ 'name': ['jones', 'smith', 'jones']} dframe = pd.DataFrame(data) print dframe field name number 0 billing_last_name jones 1 1 shipping_last_name smith 2 2 field_1435 jones 3 </code></pre> <p>Select a subset of the data:</p> <pre><code>field_filter = 'billing_last_name' number_filter = 1 choice = dframe[(dframe['field'] == field_filter) &amp; (dframe['number'] == number_filter)] print choice field name number 0 billing_last_name jones 1 0 jones Name: name, dtype: object </code></pre> <p>Use this result to set a variable for further filtering:</p> <pre><code>match = str(choice['name']) </code></pre> <p>Here's where the problem starts. If I filter with the variable it returns nothing:</p> <pre><code>print dframe[dframe['name'] == match] Empty DataFrame Columns: [field, name, number] Index: [] </code></pre> <p>If I run the same filter with the string the variable holds it returns the correct result:</p> <pre><code>print dframe[dframe['name'] == 'jones'] field name number 0 billing_last_name jones 1 2 field_1435 jones 3 </code></pre> <p>Yet both the variable and its contents are strings, apparently:</p> <pre><code>print type('jones') print type(match) &lt;type 'str'&gt; &lt;type 'str'&gt; </code></pre> <p>Why doesn't the filter with the variable work?</p>
0
2016-09-15T12:44:24Z
39,511,431
<p>Maybe you should create match as:</p> <pre><code>match = str(choice['name'][0]) </code></pre> <p>cause <strong>choice['name']</strong> is Series</p>
0
2016-09-15T12:47:59Z
[ "python", "pandas" ]
Filtering a pandas data frame with a variable
39,511,378
<p>I'm stuck on something simple but I can't see it despite reading the docs and relevant SO questions. This involves filtering records from data that comes out of a WordPress database. </p> <p>Create some data:</p> <pre><code>import pandas as pd data = {'number': [1,2,3],\ 'field': ['billing_last_name', 'shipping_last_name', 'field_1435'],\ 'name': ['jones', 'smith', 'jones']} dframe = pd.DataFrame(data) print dframe field name number 0 billing_last_name jones 1 1 shipping_last_name smith 2 2 field_1435 jones 3 </code></pre> <p>Select a subset of the data:</p> <pre><code>field_filter = 'billing_last_name' number_filter = 1 choice = dframe[(dframe['field'] == field_filter) &amp; (dframe['number'] == number_filter)] print choice field name number 0 billing_last_name jones 1 0 jones Name: name, dtype: object </code></pre> <p>Use this result to set a variable for further filtering:</p> <pre><code>match = str(choice['name']) </code></pre> <p>Here's where the problem starts. If I filter with the variable it returns nothing:</p> <pre><code>print dframe[dframe['name'] == match] Empty DataFrame Columns: [field, name, number] Index: [] </code></pre> <p>If I run the same filter with the string the variable holds it returns the correct result:</p> <pre><code>print dframe[dframe['name'] == 'jones'] field name number 0 billing_last_name jones 1 2 field_1435 jones 3 </code></pre> <p>Yet both the variable and its contents are strings, apparently:</p> <pre><code>print type('jones') print type(match) &lt;type 'str'&gt; &lt;type 'str'&gt; </code></pre> <p>Why doesn't the filter with the variable work?</p>
0
2016-09-15T12:44:24Z
39,511,457
<p>The problem is that <code>str(choice.name)</code> will not do what you think. The type is</p> <pre><code>In [205]: type(choice.name) Out[205]: pandas.core.series.Series </code></pre> <p>so <code>str</code> just finds the string representation of the Series.</p> <p>In order to access it the way you want, you can use the following:</p> <pre><code>In [206]: dframe[dframe['name'] == choice.name.values[0]] Out[206]: field name number 0 billing_last_name jones 1 2 field_1435 jones 3 </code></pre>
1
2016-09-15T12:49:20Z
[ "python", "pandas" ]
Filtering a pandas data frame with a variable
39,511,378
<p>I'm stuck on something simple but I can't see it despite reading the docs and relevant SO questions. This involves filtering records from data that comes out of a WordPress database. </p> <p>Create some data:</p> <pre><code>import pandas as pd data = {'number': [1,2,3],\ 'field': ['billing_last_name', 'shipping_last_name', 'field_1435'],\ 'name': ['jones', 'smith', 'jones']} dframe = pd.DataFrame(data) print dframe field name number 0 billing_last_name jones 1 1 shipping_last_name smith 2 2 field_1435 jones 3 </code></pre> <p>Select a subset of the data:</p> <pre><code>field_filter = 'billing_last_name' number_filter = 1 choice = dframe[(dframe['field'] == field_filter) &amp; (dframe['number'] == number_filter)] print choice field name number 0 billing_last_name jones 1 0 jones Name: name, dtype: object </code></pre> <p>Use this result to set a variable for further filtering:</p> <pre><code>match = str(choice['name']) </code></pre> <p>Here's where the problem starts. If I filter with the variable it returns nothing:</p> <pre><code>print dframe[dframe['name'] == match] Empty DataFrame Columns: [field, name, number] Index: [] </code></pre> <p>If I run the same filter with the string the variable holds it returns the correct result:</p> <pre><code>print dframe[dframe['name'] == 'jones'] field name number 0 billing_last_name jones 1 2 field_1435 jones 3 </code></pre> <p>Yet both the variable and its contents are strings, apparently:</p> <pre><code>print type('jones') print type(match) &lt;type 'str'&gt; &lt;type 'str'&gt; </code></pre> <p>Why doesn't the filter with the variable work?</p>
0
2016-09-15T12:44:24Z
39,511,539
<p><code>match</code> is actually a <code>pandas</code> <code>series</code>, not the <code>string</code> variable "jones". In this case, you need to access the <code>string</code> values within the <code>series</code>:</p> <pre><code>field_filter = 'billing_last_name' number_filter = 1 choice = dframe[(dframe['field'] == field_filter) &amp; (dframe['number'] == number_filter)] match = choice['name'].values[0] dframe[dframe['name'] == match] </code></pre> <p>Also, this assumes you only have one <code>name</code> (i.e. "Jones") when you perform your <code>choice</code> filtering. If not, the above will not work. Let me know and I will update the answer.</p>
2
2016-09-15T12:52:49Z
[ "python", "pandas" ]