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
Pandas interpreting datetime wrong
38,490,144
<p>This probably has a quick answer and I'm being silly, but after one hour of struggling and 3 cups of coffee...</p> <p>I have this (not very well formatted) time series which is indexing some readings, here's part of it:</p> <pre><code>71670 9/6/16 8:58:1 71671 9/6/16 8:59:1 71672 9/6/16 9:0:1 71...
0
2016-07-20T20:20:41Z
38,490,208
<p>Use the dayfirst parameter:</p> <pre><code>pd.to_datetime(df[col], dayfirst=True) </code></pre>
4
2016-07-20T20:24:22Z
[ "python", "pandas" ]
Pandas interpreting datetime wrong
38,490,144
<p>This probably has a quick answer and I'm being silly, but after one hour of struggling and 3 cups of coffee...</p> <p>I have this (not very well formatted) time series which is indexing some readings, here's part of it:</p> <pre><code>71670 9/6/16 8:58:1 71671 9/6/16 8:59:1 71672 9/6/16 9:0:1 71...
0
2016-07-20T20:20:41Z
38,490,209
<p>Use the <code>dayfirst</code> parameter.</p> <pre><code>In [42]: pd.to_datetime('9/6/16 8:58:1', dayfirst=True) Out[42]: Timestamp('2016-06-09 08:58:01') </code></pre>
0
2016-07-20T20:24:35Z
[ "python", "pandas" ]
Pandas interpreting datetime wrong
38,490,144
<p>This probably has a quick answer and I'm being silly, but after one hour of struggling and 3 cups of coffee...</p> <p>I have this (not very well formatted) time series which is indexing some readings, here's part of it:</p> <pre><code>71670 9/6/16 8:58:1 71671 9/6/16 8:59:1 71672 9/6/16 9:0:1 71...
0
2016-07-20T20:20:41Z
38,490,214
<p>Using the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code> function</a>.</p> <pre><code>pd.to_datetime(df.iloc[:, 1], format='%d/%m/%y %H:%M:%S') </code></pre>
1
2016-07-20T20:24:54Z
[ "python", "pandas" ]
Connecting to a JDBC database in Python vs. MATLAB
38,490,233
<p>I am trying to connect to a SQL database in Python, but I am have difficult finding documentation/examples of connecting to a JDBC. I can do this in MATLAB using the following code:</p> <pre><code>`Name = 'ServerName'; Username = ''; Password = ''; Server = ['jdbc:sqlserver://ServerName:1433;'... 'database=DB;...
2
2016-07-20T20:26:18Z
38,510,073
<p>I think that MATLAB requires the jdbc driver because of Java, but it is unnecessary in Python. My solution is using pyodbc:</p> <pre><code>conn = pyodbc.connect(driver='{SQL Server}', host=Server, database=DB, trusted_connection='yes', Username ='', Password='', readonly = True) </code></pre>...
1
2016-07-21T16:51:32Z
[ "python", "database", "jdbc", "jaydebeapi" ]
Obtaining access token error 401 in Twython
38,490,314
<p>I am trying to veify Twitter account of user via Twython</p> <pre><code>def twitter_view(request): twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens(callback_url='http://127.0.0.1:8000/confirm/', force_login=True) request.session['oauth_token'] = auth['oauth_token'] request.session['o...
0
2016-07-20T20:31:22Z
38,922,006
<p>On the second Twython instantiation, you have to include the OAUTH_TOKEN and the OAUTH_SECRET_TOKEN obtained in the first step. </p> <pre><code>twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) </code></pre> <p>It is returning Invalid Token because the instantiation you're using didn't...
0
2016-08-12T15:53:11Z
[ "python", "django", "twython" ]
Trying to Detect Circle with Houghcircles in OpenCV
38,490,457
<p>I am trying to detect circles in OpenCV using the method Houghcircles but when I am trying to run my code I get the following error: </p> <pre><code>Traceback (most recent call last): File "detect_circles.py", line 19, in &lt;module&gt; circles = cv2.cv.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 100) A...
0
2016-07-20T20:40:50Z
38,490,809
<pre><code>cv2.cv.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 100) </code></pre> <p>The error message says it all. You have a typo in your code, the method should be called without the second cv module specifier.</p> <pre><code>cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100) </code></pre>
1
2016-07-20T21:03:31Z
[ "python", "opencv" ]
Re-assigning pandas col by dictionary has no effect on original DataFrame?
38,490,479
<p>I have a huge <code>pandas</code> <code>DataFrame</code> that looks like this (sample):</p> <pre><code>df = pd.DataFrame({"col1":{0:"There ARE NO ERRORS!!!", 1:"EVERYTHING is failing", 2:"There ARE NO ERRORS!!!"}, "col2":{0:"WE HAVE SOME ERRORS", 1:"EVERYTHING is failing", 2:"System shutdown!"}}) </code></pre> <p>...
1
2016-07-20T20:42:29Z
38,490,629
<p><code>replace</code> works well with <code>regex</code> - consider putting the logic of <code>clean message()</code> into a nested <code>replace()</code>.</p> <pre><code>df["col2"] = df["col1"].replace(...).replace(...) </code></pre>
1
2016-07-20T20:51:32Z
[ "python", "pandas" ]
Re-assigning pandas col by dictionary has no effect on original DataFrame?
38,490,479
<p>I have a huge <code>pandas</code> <code>DataFrame</code> that looks like this (sample):</p> <pre><code>df = pd.DataFrame({"col1":{0:"There ARE NO ERRORS!!!", 1:"EVERYTHING is failing", 2:"There ARE NO ERRORS!!!"}, "col2":{0:"WE HAVE SOME ERRORS", 1:"EVERYTHING is failing", 2:"System shutdown!"}}) </code></pre> <p>...
1
2016-07-20T20:42:29Z
38,490,712
<pre><code>df.col1 = df.col1.str.lower().str.replace(r'([^a-z ])', '') df </code></pre> <p><a href="http://i.stack.imgur.com/0dnzu.png" rel="nofollow"><img src="http://i.stack.imgur.com/0dnzu.png" alt="enter image description here"></a></p>
0
2016-07-20T20:56:58Z
[ "python", "pandas" ]
Django Sort ManyToMany Field in A Nonsignificant Order
38,490,533
<p>I have two models as below:</p> <pre><code>class Stop(models.Model): """ Showing bus stops in İzmir. """ code = models.PositiveIntegerField( unique=True, primary_key=True, verbose_name="Code" ) label = models.CharField( null=False, blank=False, ...
0
2016-07-20T20:46:51Z
38,491,369
<p>The <code>position</code> of a <code>stop</code> is relative to a <code>Route</code>, e.g. one stop can be first for <code>route 1</code>, 2nd for <code>route 2</code> and etc. So this is a perfect example that you need more <code>metadata</code> about the <code>Route-Stop</code> relation. Djagno solves this by lett...
1
2016-07-20T21:44:28Z
[ "python", "django", "python-3.x", "orm", "manytomanyfield" ]
Python - Getting the average of n lines in a txt file
38,490,602
<p>I've taken a look online to try and solve this problem and used solutions from other posts to build towards my solution, however from here, I don't get what to do next.</p> <p>I basically want to grab the final 5 lines of the PastWinners text file and then get the average of those numbers. What I currently have get...
1
2016-07-20T20:50:00Z
38,490,715
<p>You can read the file in reverse order and use <em>break</em> after 5 reads to get out from the loop. You can also just run 5 iteration of the loop while starting from the end of the file, so you will not have to use <em>break</em> at all.</p> <p><a href="http://stackoverflow.com/questions/2301789/read-a-file-in-re...
1
2016-07-20T20:57:18Z
[ "python", "file", "text", "numbers", "average" ]
Python - Getting the average of n lines in a txt file
38,490,602
<p>I've taken a look online to try and solve this problem and used solutions from other posts to build towards my solution, however from here, I don't get what to do next.</p> <p>I basically want to grab the final 5 lines of the PastWinners text file and then get the average of those numbers. What I currently have get...
1
2016-07-20T20:50:00Z
38,490,754
<p>You can use <a href="http://techearth.net/python/index.php5?title=Python:Basics:Slices" rel="nofollow">slicing</a> to get only the 5 last numbers (I deleted all the irrelevant code):</p> <pre><code>with open('PastWinners.txt') as f: data = [float(line.rstrip()) for line in f] print(sum(data[-5:])/len(data[-5:])...
2
2016-07-20T20:59:57Z
[ "python", "file", "text", "numbers", "average" ]
Python - Getting the average of n lines in a txt file
38,490,602
<p>I've taken a look online to try and solve this problem and used solutions from other posts to build towards my solution, however from here, I don't get what to do next.</p> <p>I basically want to grab the final 5 lines of the PastWinners text file and then get the average of those numbers. What I currently have get...
1
2016-07-20T20:50:00Z
38,490,963
<p>This will work when the file is less than 5 lines, too, and will format your average to 2 decimal places.</p> <pre><code>with open('PastWinners.txt') as f: data = [float(line.rstrip()) for line in f] if len(data) &gt; 5: data = data[-5:] print min(data), max(data), "{:.2f}".format(sum(data)/len(data)) </c...
0
2016-07-20T21:14:52Z
[ "python", "file", "text", "numbers", "average" ]
Assign the same value to multiple keys in a dictionary
38,490,606
<p>I want my dictionary to look like this:</p> <pre><code>{'A': {('B','C'): 'D'}} </code></pre> <p>The code I'm using currently doesn't seem to work to achieve this result.</p> <pre><code>dict1 = {} with open('foo.csv') as f: reader = csv.DictReader(f) for row in reader: for key in ['B','C']: ...
0
2016-07-20T20:50:10Z
38,490,720
<p>You can put both items right where you want them, in the tuple:</p> <pre><code>dict1 = {} with open('foo.csv') as f: reader = csv.DictReader(f) for row in reader: dict1.setdefault(row['A'], {}).update({(row['B'], row['C']): row['D']}) # ^ ^ ...
0
2016-07-20T20:57:43Z
[ "python", "dictionary", "key-value" ]
Creating weight logic in django based off past 7 days
38,490,612
<p>I currently have a <code>Restaurant</code> model with associated models <code>Review</code> and <code>Comment</code>. Users can comment and review a restaurant. </p> <p>I'm trying to create weight logic in Django in which I display the top three restaurants with the largest weight. </p> <p>The current logic looks ...
1
2016-07-20T20:50:32Z
38,491,395
<p>I hope this will help:</p> <pre><code>import datetime from django.db.models import Q from django.utils import timezone week_ago = timezone.now() - datetime.timedelta(days=7) top_3 = Restaurant.objects.filter( Q(review__isnull=True) | Q(review__pub_date__gt=week_ago), Q(comment__isnull=True) | Q(commen...
3
2016-07-20T21:45:59Z
[ "python", "django" ]
Creating NaN values in Pandas (instead of Numpy)
38,490,717
<p>I'm converting a .ods spreadsheet to a Pandas DataFrame. I have whole columns and rows I'd like to drop because they contain only "None". As "None" is a <code>str</code>, I have:</p> <p><code>pandas.DataFrame.replace("None", numpy.nan)</code></p> <p>...on which I call: <code>.dropna(how='all')</code></p> <p>Is th...
0
2016-07-20T20:57:33Z
38,490,842
<p>You can use <code>float('nan')</code> if you really want to avoid importing things from the numpy namespace:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; s = pd.Series([1, 2, 3]) &gt;&gt;&gt; s[1] = float('nan') &gt;&gt;&gt; s 0 1.0 1 NaN 2 3.0 dtype: float64 &gt;&gt;&gt; &gt;&gt;&gt; s.dr...
1
2016-07-20T21:05:31Z
[ "python", "pandas" ]
Creating NaN values in Pandas (instead of Numpy)
38,490,717
<p>I'm converting a .ods spreadsheet to a Pandas DataFrame. I have whole columns and rows I'd like to drop because they contain only "None". As "None" is a <code>str</code>, I have:</p> <p><code>pandas.DataFrame.replace("None", numpy.nan)</code></p> <p>...on which I call: <code>.dropna(how='all')</code></p> <p>Is th...
0
2016-07-20T20:57:33Z
38,491,658
<p>If you are trying to drop directly the rows containing a "None" string value (without converting these "None" cells to <code>NaN</code> values), I guess it can be done without using <code>replace</code> + <code>dropna</code></p> <p>Considering a DataFrame like :</p> <pre><code>In [3]: df = pd.DataFrame({ ...
1
2016-07-20T22:06:45Z
[ "python", "pandas" ]
Horizontally layering LSTM cells
38,490,811
<p>I am pretty new to the whole neural network scene, and I was just going through a couple of tutorials on LSTM cells, specifically, tensorflow.</p> <p>In the tutorial, they have an object <code>tf.nn.rnn_cell.MultiRNNCell</code>, which from my understanding, is a vertical layering of LSTM cells, similar to layering ...
0
2016-07-20T21:03:47Z
38,638,969
<blockquote> <p>However, I couldn't find anything about horizontal LSTM cells, in which the output of one cell is the input of another.</p> </blockquote> <p>This is the definition of recurrence. All RNNs do this. </p>
1
2016-07-28T14:11:37Z
[ "python", "neural-network", "artificial-intelligence", "tensorflow", "recurrent-neural-network" ]
Refresh Excel external data connection using python
38,490,829
<p>I have a excel file with external data connection. I need to refresh the connection data using python.</p> <p>I tried a soultion</p> <pre><code>import win32com.client import os fileName="testconn.xlsx" xl = win32com.client.DispatchEx("Excel.Application") wb = xl.workbooks.open(fileName) xl.Visible = True wb.Refres...
-1
2016-07-20T21:04:25Z
38,491,462
<p>Definitely refreshing an Excel worksheet would require Excel to be installed. So your approach seems to be fine, although there may be easier ways. Pandas has a good library for manipulating Excel spreadsheets <code>pandas.read_excel</code> and <code>pandas.DataFrame.to_excel</code> functions <a href="http://panda...
0
2016-07-20T21:51:25Z
[ "python", "excel" ]
Does Numpy allocate temporary arrays in expressions like x += 2 * y?
38,490,937
<p>When evaluating expressions like</p> <pre><code>x += 2 * y </code></pre> <p>does <code>Numpy</code> first allocate a new temporary array to hold <code>2*y</code>, add it to <code>x</code> and then delete it, or can it perform this whole operation in-place?</p>
4
2016-07-20T21:12:52Z
38,491,048
<p>Yup, that makes a temporary array.</p> <p>If you find yourself needing to mitigate NumPy's love of giant scratch arrays, additional libraries like <a href="https://github.com/pydata/numexpr" rel="nofollow">Numexpr</a> can help quite a bit, but make sure you're attributing performance problems to the right causes. N...
2
2016-07-20T21:20:33Z
[ "python", "performance", "numpy" ]
Pyspark command in terminal launches Jupyter notebook
38,490,946
<p>I have run into an issue with spark-submit , throws an error is not a Jupyter Command i.e, pyspark launches a web ui instead of pyspark shell </p> <p>Background info:</p> <ol> <li>Installed Scala , Spark using brew on MAC</li> <li>Installed Conda Python 3.5</li> <li>Spark commands work on Jupyter Notebook</li> <li...
0
2016-07-20T21:13:34Z
38,510,399
<p>The PYSPARK_DRIVER_PYTHON variable is set to start ipython/jupyter automatically (probably as intended.) Run <code>unset PYSPARK_DRIVER_PYTHON</code> and then try pyspark again.</p> <p>If you wish this to be the default, you'll probably need to modify your profile scripts. </p>
0
2016-07-21T17:10:33Z
[ "python", "pyspark", "jupyter", "jupyter-notebook" ]
Passing Too Many Arguments to Object Method - Python
38,491,056
<p>So I think I have an incredibly simple case but I'm utterly lost about why it won't execute.</p> <p>Here's my source - this is my main.py file that I'm running by just executing 'python main.py' from the command line:</p> <pre><code>import player import enemy p1 = player.playerClass(health = 200.0, position = [1,...
0
2016-07-20T21:21:02Z
38,491,196
<p>Try defining your player.playerClass like this</p> <pre><code>class playerClass: def __init__ (self, health, position, damage): self.health = health self.position = position self.damage = damage def Attack(self, target, damage): self.CurrentTarget = target target.Health -= damage self.Cu...
1
2016-07-20T21:31:30Z
[ "python", "arguments" ]
Passing Too Many Arguments to Object Method - Python
38,491,056
<p>So I think I have an incredibly simple case but I'm utterly lost about why it won't execute.</p> <p>Here's my source - this is my main.py file that I'm running by just executing 'python main.py' from the command line:</p> <pre><code>import player import enemy p1 = player.playerClass(health = 200.0, position = [1,...
0
2016-07-20T21:21:02Z
38,491,710
<p>I did end up finding the solution and it has a little to do with @martijin's suggestion.</p> <p>The issue was that I had compiled python files in the directory that my main.py file was run from - in turn, when python was executing, it was referring to these compiled .pyc files and not the actual script files that I...
0
2016-07-20T22:11:04Z
[ "python", "arguments" ]
Flask-Testing signals not supported error
38,491,075
<p>When running my tests I am getting the following traceback.</p> <pre><code>in get_context_variable raise RuntimeError("Signals not supported") RuntimeError: Signals not supported </code></pre> <p><strong>__init__.py</strong></p> <pre><code>from flask_testing import TestCase from app import create_app, db class...
1
2016-07-20T21:22:16Z
38,491,198
<p>Flask only provides signals as an optional dependency. Flask-Testing requires signals in some places and raises an error if you try to do something without them. For some reason, some messages are more vague than others Flask-Testing raises elsewhere. <sub>(This is a good place for a beginner to contribute a pull...
1
2016-07-20T21:31:35Z
[ "python", "flask", "flask-testing" ]
Python unexpected character after line continuation character
38,491,082
<p>I am very new to Python. I am constructing a string that is nothing but a path to the network location as follows. But it outputs the error: "Python unexpected character after line continuation character". Please help. I saw this post but I am not sure if it applies to my scenario:</p> <p><a href="http://stackoverf...
0
2016-07-20T21:22:55Z
38,491,119
<p>One of your <code>\</code> backslashes <em>escapes</em> the <code>"</code> double quote following it. The rest of the string then <em>ends</em> just before the next <code>\</code> backslash, and that second backslash is seen as a line-continuation character. Because there's another <code>"</code> right after that yo...
3
2016-07-20T21:25:04Z
[ "python", "python-3.x" ]
how can I remove a widget in kivy?
38,491,124
<p>I am trying to do the same as I did to add these widgets, but without success. I am working with the kv language and bind function. With this code below is possible add a buttons dynamically, but isn't possible remove them.</p> <p>.py</p> <pre><code>class PrimeiroScreen(Screen): def __init__(self, **kwargs): ...
0
2016-07-20T21:25:18Z
38,491,700
<p>Change<br> <code>btn = Button(text="Botão",size_hint=(.1,.1))</code><br> to<br> <code>self.btn = Button(text="Botão",size_hint=(.1,.1))</code><br> So you make it a class attribute. </p> <p>And then remove it like this<br> <code>self.remove_widget(self.btn)</code></p>
0
2016-07-20T22:10:30Z
[ "python", "kivy" ]
Numpy: "<<" and ">>" operators
38,491,204
<p>I was doing some Numpy exercises and came across this example:</p> <pre><code>z = np.arange(10) 2 &lt;&lt; z </code></pre> <p>It outputs: array([ 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024])</p> <p>There are a few other operators like this for example: z >> 2, z &lt;- z, z >- z</p> <p>I did a ...
-3
2016-07-20T21:32:05Z
38,491,310
<p>The operators <code>&lt;&lt;</code> and <code>&gt;&gt;</code> are bit shift operators (left and right, respectively). In your particular example (with <code>&lt;&lt;</code>), you are performing <code>x = x * 2^z</code> for each array element, resulting in your modified output. The operator <code>&gt;&gt;</code> in t...
1
2016-07-20T21:40:27Z
[ "python", "numpy" ]
Python: Replace keys in a nested dictionary
38,491,318
<p>I have a nested dictionary <code>{1: {2: {3: None}}}</code> and a dictionary that maps keys of the nested dictionary to a set of values such as <code>{1: x, 2: y, 3: z}</code>. I want to transform the nested dictionary to this form <code>{x: {y: {z: None}}}</code>. I have tried a couple of recursive functions but I ...
2
2016-07-20T21:40:42Z
38,491,565
<p>You need to recurse through the dictionary while building a new one with new keys. Note that if you have a list or tuple in there somewhere that has other dictionaries in it, they won't be processed - you'd have to add some code to do that. You can actually do this without building a new dictionary, but I think th...
1
2016-07-20T21:59:26Z
[ "python", "dictionary", "recursion", "nested" ]
Efficient way for python date string manipulation
38,491,376
<p>I want to turn '07/18/2013' to '07/2013' and there are a lot of these strings to be processed. What would be the most efficient way to do it?</p> <p>I am thinking of using </p> <pre><code>''.join(['07/18/2013'[0:3],'07/18/2013'[6:]]) </code></pre>
1
2016-07-20T21:44:43Z
38,491,452
<p>Use datetime module:</p> <pre><code>import datetime print datetime.datetime.strptime("07/18/2013", '%m/%d/%Y').strftime('%m/%Y') </code></pre>
1
2016-07-20T21:50:49Z
[ "python", "string", "date" ]
Efficient way for python date string manipulation
38,491,376
<p>I want to turn '07/18/2013' to '07/2013' and there are a lot of these strings to be processed. What would be the most efficient way to do it?</p> <p>I am thinking of using </p> <pre><code>''.join(['07/18/2013'[0:3],'07/18/2013'[6:]]) </code></pre>
1
2016-07-20T21:44:43Z
38,491,471
<p>Look into strftime and strptime.</p> <p>Assuming you start with the string <em>s</em> you can put it into a datetime object using strptime then take that back out into a string with only the necessary fields using strftime. I didn't actually run this code so I don't know if it is perfect, but the idea is here.</p>...
3
2016-07-20T21:52:11Z
[ "python", "string", "date" ]
Pyspark Dataframe Join using UDF
38,491,377
<p>I'm trying to create a custom join for two dataframes (df1 and df2) in PySpark (similar to <a href="http://stackoverflow.com/questions/30132533/custom-join-with-non-equal-keys">this</a>), with code that looks like this:</p> <pre><code>my_join_udf = udf(lambda x, y: isJoin(x, y), BooleanType()) my_join_df = df1.join...
2
2016-07-20T21:44:47Z
38,498,610
<p>Theoretically you can join and filter:</p> <pre><code>df1.join(df2).where(my_join_udf(df1.col_a, df2.col_b)) </code></pre> <p>but in general you shouldn't to it all. Any type of <code>join</code> which is not based on equality requires a full Cartesian product (same as the answer) which is rarely acceptable (see a...
3
2016-07-21T08:13:13Z
[ "python", "apache-spark", "pyspark", "pyspark-sql" ]
Python efficient way to copy one dictionary as value of key
38,491,461
<p>I am working on a monitoring tool in python. It has a global dictionary with all hosts as keys and their details as values.</p> <p>At the moment I do it like this:</p> <pre><code>host = hostname hostDictionary["a"] = a hostDictionary["b"] = b hostDictionary["c"] = c globalDictionary[host] = hostDictionary </code><...
1
2016-07-20T21:51:23Z
38,491,542
<p>1\2 - It is a reference, you need to make a copy in this way. </p> <pre><code>from copy import copy globalDictionary[host] = copy(hostDictionary) </code></pre> <p>3 - I don't think so, I think that a copy to all the object can be quicker than access on each elements.</p>
1
2016-07-20T21:57:59Z
[ "python", "dictionary" ]
Python efficient way to copy one dictionary as value of key
38,491,461
<p>I am working on a monitoring tool in python. It has a global dictionary with all hosts as keys and their details as values.</p> <p>At the moment I do it like this:</p> <pre><code>host = hostname hostDictionary["a"] = a hostDictionary["b"] = b hostDictionary["c"] = c globalDictionary[host] = hostDictionary </code><...
1
2016-07-20T21:51:23Z
38,491,564
<ol> <li><p>Nopes, it ain't copying the whole dictionary, its just referencing it. To check this the best method is to do this - </p> <pre><code>host = 'hostname' hostDictionary = {} globalDictionary = {} hostDictionary["a"] = a hostDictionary["b"] = b hostDictionary["c"] = c globalDictionary[host] = hostDictionary` <...
1
2016-07-20T21:59:00Z
[ "python", "dictionary" ]
Python efficient way to copy one dictionary as value of key
38,491,461
<p>I am working on a monitoring tool in python. It has a global dictionary with all hosts as keys and their details as values.</p> <p>At the moment I do it like this:</p> <pre><code>host = hostname hostDictionary["a"] = a hostDictionary["b"] = b hostDictionary["c"] = c globalDictionary[host] = hostDictionary </code><...
1
2016-07-20T21:51:23Z
38,491,591
<p>I get this from Python CLI:</p> <pre><code>&gt;&gt;&gt; a = {} &gt;&gt;&gt; b = {} &gt;&gt;&gt; c = {} &gt;&gt;&gt; a["foo"] = 1 &gt;&gt;&gt; b = a &gt;&gt;&gt; c = a.copy() &gt;&gt;&gt; b["bar"] = 2 &gt;&gt;&gt; a {'foo': 1, 'bar': 2} &gt;&gt;&gt; b {'foo': 1, 'bar': 2} &gt;&gt;&gt; c {'foo': 1} </code></pre> <p>...
1
2016-07-20T22:01:03Z
[ "python", "dictionary" ]
Python efficient way to copy one dictionary as value of key
38,491,461
<p>I am working on a monitoring tool in python. It has a global dictionary with all hosts as keys and their details as values.</p> <p>At the moment I do it like this:</p> <pre><code>host = hostname hostDictionary["a"] = a hostDictionary["b"] = b hostDictionary["c"] = c globalDictionary[host] = hostDictionary </code><...
1
2016-07-20T21:51:23Z
38,491,642
<p>I think it will be faster if you initialize dict like this</p> <pre><code>lobalDictionary[host] = { "a": a, "b": b, "c": c } </code></pre> <p>Also if you don't want to use copy or deepcopy, you can copy your dictionary like this:</p> <pre><code>globalDictionary[host] = dict(hostDictionary.items()) </c...
1
2016-07-20T22:05:12Z
[ "python", "dictionary" ]
Internal Server Error when get the tags of the virtual guest
38,491,538
<p>The API is returning Internal Server Error when I try to get the tags of the virtual guests of a customer account.</p> <p>Code example using the SoftLayer API library: </p> <pre><code>api = SoftLayer.Client(username=customer_id, api_key=customer_apikey) api['Account'].getVirtualGuests(mask='fullyQualifiedDomainNam...
0
2016-07-20T21:57:47Z
38,492,656
<p>it looks like an error because the reponse contains a big amount of data try to add limits in your request:</p> <pre><code>api = SoftLayer.Client(username=customer_id, api_key=customer_apikey) api['Account'].getVirtualGuests(mask='fullyQualifiedDomainName,tagReferences.tag.name',limit=10, offset=0) </code></pre> <...
0
2016-07-20T23:54:30Z
[ "python", "softlayer" ]
Improving runtime of weighted moving average filter function?
38,491,572
<p>I have a weighted moving average function which smooths a curve by averaging 3*width values to the left and to the right of each point using a gaussian weighting mechanism. I am only worried about smoothing a region bounded by [start, end]. The following code works, but the problem is runtime with large arrays.</p> ...
1
2016-07-20T21:59:56Z
38,491,834
<p>That slicing and summing/averaging on a weighted window basically corresponds to 1D convolution with the kernel being flipped. Now, for <a href="https://en.wikipedia.org/wiki/Convolution" rel="nofollow"><code>1D</code> convolution</a>, NumPy has a very efficient implementation in <a href="http://docs.scipy.org/doc/n...
2
2016-07-20T22:21:20Z
[ "python", "numpy", "runtime", "ipython", "vectorization" ]
Improving runtime of weighted moving average filter function?
38,491,572
<p>I have a weighted moving average function which smooths a curve by averaging 3*width values to the left and to the right of each point using a gaussian weighting mechanism. I am only worried about smoothing a region bounded by [start, end]. The following code works, but the problem is runtime with large arrays.</p> ...
1
2016-07-20T21:59:56Z
38,491,867
<p>The main concern with looping over a large array is that the memory allocation for the large array can be expensive, and the whole thing has to be initialized before the loop can start.</p> <p>In this particular case I'd go with what Divakar is saying.</p> <p>In general, if you find yourself in a circumstance wher...
0
2016-07-20T22:24:58Z
[ "python", "numpy", "runtime", "ipython", "vectorization" ]
Python script: problems with shebang line (unix)
38,491,587
<p>I am trying to get a feel for the Flask microframework by launching a test application to local server. When trying to run my code, <code>app.py</code>, I keep getting the error message:</p> <pre><code>-bash: ./app.py: /flask/bin/python: bad interpreter: No such file or directory </code></pre> <p>Here is the basic...
0
2016-07-20T22:00:45Z
38,491,625
<p><code>pwd</code> tells you the current directory. It doesn't tell you where a command is located. The output from that command is a red herring.</p> <p>You may be looking for <code>which python</code>. Put that path into your shebang line. Note that this will give you the Python interpreter from your <code>$PATH</c...
1
2016-07-20T22:04:07Z
[ "python", "bash", "shebang" ]
Python script: problems with shebang line (unix)
38,491,587
<p>I am trying to get a feel for the Flask microframework by launching a test application to local server. When trying to run my code, <code>app.py</code>, I keep getting the error message:</p> <pre><code>-bash: ./app.py: /flask/bin/python: bad interpreter: No such file or directory </code></pre> <p>Here is the basic...
0
2016-07-20T22:00:45Z
38,491,659
<p>Bash shebangs expect an absolute path to the interpreter. So in your case you need to specify the full path to your Python interpreter i.e.:</p> <pre><code>#!/Users/me/Documents/Python/todo-api/flask/bin </code></pre> <p>You might want to investigate the use of <code>/usr/bin/env python</code> to be able to use th...
3
2016-07-20T22:06:48Z
[ "python", "bash", "shebang" ]
Python script: problems with shebang line (unix)
38,491,587
<p>I am trying to get a feel for the Flask microframework by launching a test application to local server. When trying to run my code, <code>app.py</code>, I keep getting the error message:</p> <pre><code>-bash: ./app.py: /flask/bin/python: bad interpreter: No such file or directory </code></pre> <p>Here is the basic...
0
2016-07-20T22:00:45Z
39,044,051
<p>I was having a similar issue with trying to setup a python script as an executable for testing some things and realized that bash was getting in the way more than it was helping. I ended up setting up pyinstaller (which is incredibly easy) and then making my script a stand alone executable without bash being in the ...
0
2016-08-19T16:43:31Z
[ "python", "bash", "shebang" ]
change endian of hex in bitstring unpack
38,491,602
<p>I'm using the module bitstring to unpack a 24 byte boundary file. I dont have control over the input file. The default interpretation of the module is big-endian apparently which is easy to fix when unpacking data types like int or float but some data I want to be represented as hex values. Using the unpack hex valu...
1
2016-07-20T22:02:22Z
38,787,831
<p>You could use ordinary Python formatting on a little-endian integer interpretation.</p> <p>Rather than a <code>read</code> then <code>unpack</code> you also can do both together:</p> <pre><code>print('{:0&gt;4X}'.format(fp.read('uintle:16'))) </code></pre> <p>This reads then next 16 bits from the stream, interpre...
0
2016-08-05T11:11:47Z
[ "python", "unpack", "bitstring" ]
Attaching/Cloning a submenu to more than one menu item
38,491,714
<p>So I have a basic menu structure:</p> <pre><code>menu = gtk.menu() item1 = gtk.MenuItem('Item 1') item2 = gtk.MenuItem('Item 2') menu.append(item1) menu.append(item2)` menu.show_all() </code></pre> <p>And I have a submenu:</p> <pre><code>submenu = gtk.menu() subitem1 = gtk.MenuItem('Option 1') subitem2 = gtk.Menu...
1
2016-07-20T22:11:24Z
38,568,650
<p>As the warning you get on the terminal specifies, you cannot attach the same instance of GtkMenu to different menus — just like you cannot add the same widget to multiple containers.</p> <p>Your menu hierarchy seems to be overly complex if you find the need to have the same sub-menu in multiple places; it will un...
0
2016-07-25T13:07:19Z
[ "python", "menu", "gtk", "submenu" ]
What will be the Hadoop Streaming Run Command to access the files in the Sub Directory
38,491,716
<p>I have written a mapper program in python for hadoop Map-Reduce framework.</p> <p>And I am executing it through the command:</p> <p><code>hadoop jar /usr/hdp/2.3.2.0-2950/hadoop-mapreduce/hadoop-streaming.jar -mapper "python wordcount_mapper.py" -file wordcount_mapper.py -input inputfile -output outputfile3</code>...
0
2016-07-20T22:11:48Z
38,517,426
<p>Use regular expressions: </p> <p><code>inputfile/*</code> - will work for 1 level of sub directories</p> <p><code>inputfile/*/*</code> - will work for 2 level of sub directories </p> <p>Run As:</p> <p><code>hadoop jar /usr/hdp/2.3.2.0-2950/hadoop-mapreduce/hadoop-streaming.jar -mapper "python wordcount_mapper....
0
2016-07-22T02:55:32Z
[ "python", "python-2.7", "hadoop", "hadoop-streaming" ]
python how to find if a dictionary contains data from other dictionary
38,491,717
<p>In Python, how do i find if a dictionary contains data from the other dictionary.</p> <p>my data is assigned to a variable like this</p> <pre><code>childDict = { "assignee" : { "first":"myFirstName", "last":"myLastName" }, "status" : "alive" } </code></pre> <p>I have another dictionary named maste...
2
2016-07-20T22:11:52Z
38,491,928
<p>Note that there were some errors in your dictionary (missing commas).</p> <pre><code>childDict1 = { "assignee": { "first":"myFirstName", "last":"myLastName" }, "status" : "alive" } childDict2 = { "assignee": { "first":"myFirstName", "last":"myLastName" }, "st...
2
2016-07-20T22:30:12Z
[ "python", "dictionary", "compare", "contains" ]
Reading a github file using python returns HTML tags
38,491,722
<p>I am trying to read a text file saved in github using requests package. Here is the python code I am using:</p> <pre><code> import requests url = 'https://github.com/...../filename' page = requests.get(url) print page.text </code></pre> <p>Instead of getting the text, I am reading HTML tags. How can...
1
2016-07-20T22:12:31Z
38,491,755
<p>You can access a text version by changing the beginning of your link to </p> <pre><code>https://raw.githubusercontent.com/ </code></pre>
3
2016-07-20T22:14:52Z
[ "python" ]
Reading a github file using python returns HTML tags
38,491,722
<p>I am trying to read a text file saved in github using requests package. Here is the python code I am using:</p> <pre><code> import requests url = 'https://github.com/...../filename' page = requests.get(url) print page.text </code></pre> <p>Instead of getting the text, I am reading HTML tags. How can...
1
2016-07-20T22:12:31Z
38,497,199
<p>There are some good solutions already, but if you use <code>requests</code> just follow Github's <a href="https://developer.github.com/v3/repos/contents/#get-contents" rel="nofollow">API</a>.</p> <p>The endpoint for all content is</p> <pre><code>GET /repos/:owner/:repo/contents/:path </code></pre> <p>But keep in ...
1
2016-07-21T07:04:01Z
[ "python" ]
How can i select a file with python?
38,491,810
<p><a href="http://i.stack.imgur.com/mMIsq.png" rel="nofollow">enter image description here</a></p> <p>I can do like this on Java, but i can't do on Python</p> <pre><code>StringSelection ss = new StringSelection("C:\\Users\\Mert\\Desktop\\hello.png"); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, n...
-2
2016-07-20T22:20:11Z
38,492,642
<p>You can open a file GUI similar to Java using Python's <code>tkinter</code>:</p> <pre><code>from Tkinter import Tk from tkFileDialog import askopenfilename Tk().withdraw() filename = askopenfilename() print(filename) </code></pre> <p>And the Python3 equivalent:</p> <pre><code>from tkinter.filedialog import askop...
1
2016-07-20T23:53:08Z
[ "python", "selenium" ]
Django and MySQL, cannot gain access to connect with the database ERROR:1045
38,491,869
<p>Hello I am working on a project with a few people. We are using django 1.9 my mysql and someone set up django to connect with mysql and then wrote instructions for the rest of us on what we need to download to connect python with mysql. I correctly installed mysql but I have issues with accessing the database. We ar...
0
2016-07-20T22:25:03Z
38,492,016
<p>If people are pulling your code, and you want them to access YOUR database, then they probably shouldn't be using "localhost." If you're getting this error while running on your localhost, too, then it's a permission problem.</p> <p>The first thing to do is see if you can use the command line MySQL, or another MyS...
1
2016-07-20T22:37:50Z
[ "python", "mysql", "django", "connector" ]
Django and MySQL, cannot gain access to connect with the database ERROR:1045
38,491,869
<p>Hello I am working on a project with a few people. We are using django 1.9 my mysql and someone set up django to connect with mysql and then wrote instructions for the rest of us on what we need to download to connect python with mysql. I correctly installed mysql but I have issues with accessing the database. We ar...
0
2016-07-20T22:25:03Z
38,492,873
<h2>Mysql Privileges</h2> <p>This error is because the <code>django</code> user does not have access to the <code>lolProject</code> database. You can rectify that by using the <a href="http://dev.mysql.com/doc/refman/5.7/en/grant.html" rel="nofollow">GRANT</a> command. The django user needs a lot of privileges because...
1
2016-07-21T00:21:58Z
[ "python", "mysql", "django", "connector" ]
Grouping and ungrouping based on a column
38,491,881
<p>My goal is to be able to group rows of a CSV file by a column value, and also to perform the inverse operation. To give an example, it is desired to be able to transform back and forth between these two formats:</p> <pre><code>uniqueId, groupId, feature_1, feature_2 1, 100, text of 1, 10 2, 100, some text of 2, 20 ...
1
2016-07-20T22:26:20Z
38,492,356
<p>To perform the grouping, you can <code>groupby</code> on <code>'groupId'</code>, and then within each group perform a join with your given delimiter on each column:</p> <pre><code>def group_delim(grp, delim='|'): """Join each columns within a group by the given delimiter.""" return grp.apply(lambda col: del...
4
2016-07-20T23:13:31Z
[ "python", "csv", "pandas" ]
Grouping and ungrouping based on a column
38,491,881
<p>My goal is to be able to group rows of a CSV file by a column value, and also to perform the inverse operation. To give an example, it is desired to be able to transform back and forth between these two formats:</p> <pre><code>uniqueId, groupId, feature_1, feature_2 1, 100, text of 1, 10 2, 100, some text of 2, 20 ...
1
2016-07-20T22:26:20Z
38,492,679
<p>A solution in R:</p> <p>I define the initial data frame (for clarity)</p> <pre><code>df &lt;- data.frame(uniqueID = c(1,2,3,4,5), groupID = c(100,100,200,200,100), feature_1 = c("text of 1","some text of 2", "text of 3", "more text of 4", "another...
2
2016-07-20T23:58:34Z
[ "python", "csv", "pandas" ]
Why can't Python find the built-in print function when calling from an imported function?
38,491,927
<p>Take this <strong>main.py</strong>:</p> <pre><code>from __future__ import print_function from sub import print print("hello, world") </code></pre> <p>and this <strong>sub.py</strong>:</p> <pre><code>from __future__ import print_function def print(*args, **kwargs): return __builtins__.print(*args, **kwargs)...
2
2016-07-20T22:30:07Z
38,492,040
<p>Try this:</p> <pre><code>import __builtin__ from __future__ import print_function def print(*args, **kwargs): return __builtin__.print(*args, **kwargs) </code></pre> <hr> <pre><code>&gt;&gt;&gt; print &lt;function print at 0x7f80cd622668&gt; &gt;&gt;&gt; print("Hello", "world", sep="\n") Hello world </code><...
3
2016-07-20T22:39:55Z
[ "python" ]
Why can't Python find the built-in print function when calling from an imported function?
38,491,927
<p>Take this <strong>main.py</strong>:</p> <pre><code>from __future__ import print_function from sub import print print("hello, world") </code></pre> <p>and this <strong>sub.py</strong>:</p> <pre><code>from __future__ import print_function def print(*args, **kwargs): return __builtins__.print(*args, **kwargs)...
2
2016-07-20T22:30:07Z
38,492,042
<p>To quote an answer on this question: <a href="http://stackoverflow.com/questions/550470/overload-print-python">overload print python</a></p> <blockquote> <p>In Python 2.x you can't, because print isn't a function, it's a statement. In Python 3 print is a function, so I suppose it could be overridden (haven't ...
-1
2016-07-20T22:40:06Z
[ "python" ]
How to apply RANSAC in Python OpenCV
38,491,959
<p>Can someone show me how to apply RANSAC to find the best 4 feature matching points and their corresponding (x,y) coordinate so I can use them in my homography code?</p> <p>The feature matching points were obtained by SIFT and here is the code:</p> <pre><code>import numpy as np import cv2 from matplotlib import pyp...
0
2016-07-20T22:33:03Z
38,496,220
<p>You don't have to use RANSAC before <code>findHomography</code>. RANSAC is applied inside the function. Just pass two arrays of features that match each other (no need to only pass the four best).</p> <p>However, what you can do is filter out the matches that have large distances. Usually, you try to find two match...
1
2016-07-21T06:13:02Z
[ "python", "opencv", "homography", "ransac" ]
understanding kivy code snippet
38,491,963
<p>I am using the following code from web:</p> <pre><code>from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Line class DrawInput(Widget): def on_touch_down(self, touch): print(touch) with self.canvas: touch.ud["line"] = Line(points=(touch.x, touch.y...
-1
2016-07-20T22:33:18Z
38,492,700
<p>They get called, because they are Widget class methods that you override. They are events bound to click/touch, on the Widget.</p> <p>As from the <a href="https://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget" rel="nofollow">Widget</a> docs</p> <blockquote> <p>Events: </p> <p>on_touch_d...
0
2016-07-21T00:00:46Z
[ "python", "kivy" ]
django forloopcounter in template
38,491,977
<p>How can i autoincrement a item of my list?</p> <p>I have something like this:</p> <p>data = {'port': [22,80,443], 'banner': ['OpenSSH','Apache2','Apache'], 'protocol': ['tcp','tcp','tcp'] }</p> <pre><code>{% for key, value in data.items %} &lt;tr&gt; &lt;th class="white"&gt;{{key}}&lt...
1
2016-07-20T22:34:37Z
38,492,017
<p>You can iterate over the values using another <code>for</code> loop:</p> <pre><code>{% for key, value in ack.items %} &lt;tr&gt; &lt;th class="white"&gt;{{key}}&lt;/th&gt; {% for v in value %} &lt;th class="black"&gt;{{v}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% endf...
1
2016-07-20T22:37:57Z
[ "python", "django", "templates" ]
Adding and Renaming a Column in a Multiindex DataFrame
38,491,990
<p>The purpose of this post is to understand how to add a column to a level in a <code>MultiIndex.DataFrame</code> using <code>apply()</code> and <code>shift()</code></p> <p><strong>Create the DataFrame</strong></p> <pre><code>import pandas as pd df = pd.DataFrame( [ [5777, 100, 5385, 200, 5419, 4887, 100, 200],...
2
2016-07-20T22:35:23Z
38,493,363
<p>Skip the <code>groupby</code> it is not necessary</p> <pre><code>amount = df.loc[:, pd.IndexSlice[:, :, 'amount']] inject = df.loc[:, pd.IndexSlice[:, :, 'injection']] dav = amount - amount.shift() - inject.shift().values #dav.columns.set_levels(['daily_added_value'], level=2, inplace=True) pd.concat([df, dav], ax...
2
2016-07-21T01:21:59Z
[ "python", "pandas" ]
virtualenv with --always-copy throws error "Operation not permitted"
38,491,992
<p>I'm trying to run virtualenv without symlinking python2.7 but I get permission errors when I use the flag --always-copy.</p> <pre><code>virtualenv --always-copy myenv Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 11, in &lt;module&gt; sys.exit(main()) File "/Library/Pytho...
1
2016-07-20T22:35:48Z
39,237,120
<p>Hard to answer without additional details but my guess would be you need to sudo first.</p> <p>so <code>sudo virtualenv --always-copy myenv</code> </p>
0
2016-08-30T21:08:32Z
[ "python", "python-2.7", "virtualenv" ]
Unclear IndexError on Python
38,492,045
<pre><code>def scan_for_match(T1, T2): i = 0 j = 0 while i &lt;= (len(T1)): if T1[i] == T2[j]: keywords = open('keywords.txt', 'w+') keywords.write(T1.pop(i)) T2.pop(j) if i &gt; (len(T1)): i = 0 j += 1 if j &gt; (len(T2)): ...
1
2016-07-20T22:40:18Z
38,492,058
<p>Change the condition on the <code>while</code> to:</p> <pre><code>while i &lt; len(T1) # ^ </code></pre> <p>When <code>i = len(T1)</code> and you try to index your list, you'll get an <code>IndexError</code> because your index starts counting from zero.</p>
1
2016-07-20T22:41:43Z
[ "python", "python-2.7", "runtime-error" ]
Unclear IndexError on Python
38,492,045
<pre><code>def scan_for_match(T1, T2): i = 0 j = 0 while i &lt;= (len(T1)): if T1[i] == T2[j]: keywords = open('keywords.txt', 'w+') keywords.write(T1.pop(i)) T2.pop(j) if i &gt; (len(T1)): i = 0 j += 1 if j &gt; (len(T2)): ...
1
2016-07-20T22:40:18Z
38,492,071
<p><code>while i &lt;= (len(T1)):</code> is wrong, when i equals the length, it will have IndexError, change it to <code>&lt;</code>. Index is starting from <strong>0</strong> to <strong>(length - 1)</strong></p> <p>I suggest not using <code>pop()</code> method, it will remove element(s) from your list, scan for match...
2
2016-07-20T22:42:26Z
[ "python", "python-2.7", "runtime-error" ]
strange python index out of range
38,492,126
<p>I got a strange problem with my python code </p> <p>when i test it with : </p> <pre><code>4 Prashant 32 Pallavi 36 Dheeraj 39 Shivam 40 </code></pre> <p>it works well but when i try to test it with this :</p> <pre><code>5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 </code></pre> <p>it fail with this er...
-3
2016-07-20T22:48:40Z
38,492,406
<p>It pays to unit test your functions or at least add a few print statements to see what they return. I added</p> <pre><code>print find(nested,minimum(nested)) </code></pre> <p>which printed</p> <pre><code>[] </code></pre> <p><code>find</code> isn't working the way you want it to and after inspection, it appears t...
2
2016-07-20T23:20:22Z
[ "python", "indexing", "range" ]
Audio corrective feedback on psychopy (older version that supports sound)
38,492,137
<p>As some of you may know, psychopy has errors playing sound files on the newer versions, so I have the oldest version installed currently and am trying to make audio corrective feedback for a behavioral test meant to be in an fMRI scanner. The feedback is needed to keep the participants awake. I'm having a lot of tro...
0
2016-07-20T22:50:34Z
38,492,240
<p>Are you coding this from scratch or transferred from builder to coder view and making edits? If you are making edits in the coder view, make sure the indents and punctuations remain the same.</p> <p>From what you've shared, I can see that</p> <pre><code> if key_resp.corr feedback= hit_sound.play else: ...
1
2016-07-20T23:00:59Z
[ "python", "psychopy" ]
Group by in SFrame without installing graphlab
38,492,159
<p>How to use groupby operation in SFrame, without installing graphlab.</p> <p>I would love to do some aggregation, but in all examples in the internet I have seen aggregation function comes from Graphlab.</p> <p>Like:</p> <pre><code>import graphlab.aggregate as agg user_rating_stats = sf.groupby(key_columns='user_...
1
2016-07-20T22:52:30Z
38,492,735
<p>The <code>sframe</code> package contains the same aggregation module as the <code>graphlab</code> package, so you shouldn't need to resort to numpy.</p> <pre><code>import sframe import sframe.aggregate as agg sf = sframe.SFrame({'user_id': [1, 1, 2], 'rating': [3.3, 3.6, 4.1]}) grp = sf.groupby...
2
2016-07-21T00:05:25Z
[ "python", "numpy", "group-by", "graphlab", "sframe" ]
Local variable referenced before assignment Python 3.4.5
38,492,223
<p>I'm going through LearnPythonTheHardWay book and I'm stuck on ex35. I decided to create my own game as he asked on Study Drills. I have <code>gold_room</code> function that is just like his, but it raises the title's errors on both codes(his and mine).</p> <pre><code>def gold_room(): print("You enter a room fu...
-2
2016-07-20T22:59:35Z
38,492,273
<p>You are receiving that error because you are referencing the variable <code>how_much</code> before any value is assigned to it. :)</p> <p>This happens at line: <code>if how_much &lt; 50:</code></p> <p>At that point in code execution, whether <code>how_much</code> is defined or not depends on whether the previous c...
2
2016-07-20T23:04:15Z
[ "python" ]
Python error: cannot concatenate 'str' and 'builtin_function_or_method' objects
38,492,226
<p>I am currently in the process of programming a text-based adventure in Python as a learning exercise. So far, the player can name themselves, the value of which is stored in a dictionary key. However, when I attempt to allow the player to choose their race, I get the following error:</p> <p><em>cannot concatenate '...
0
2016-07-20T22:59:39Z
38,492,236
<p>You need to call that lower method, it's a <em>callable</em> attribute:</p> <pre><code>player_race = raw_input("&gt;&gt; ").lower() # ^^ </code></pre>
0
2016-07-20T23:00:43Z
[ "python", "command-line", "text-based" ]
MatPlotLib: Control Ind Increments
38,492,292
<p>Given this chart:</p> <pre><code>import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data people = ('Tom', 'Dick', 'Harry', 'Slim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) plt.barh(y_pos, performance, align='center...
0
2016-07-20T23:06:47Z
38,492,353
<p>Use the <code>yticks</code> function like this:</p> <pre><code>plt.yticks(range(len(y_pos))) </code></pre>
1
2016-07-20T23:13:18Z
[ "python", "matplotlib" ]
reordering cluster numbers for correct correspondence
38,492,314
<p>I have a dataset that I clustered using two different clustering algorithms. The results are about the same, but the cluster numbers are permuted. Now for displaying the color coded labels, I want the label ids to be same for the same clusters. How can I get correct permutation between the two label ids?</p> <p>I c...
0
2016-07-20T23:08:55Z
38,499,466
<p>The most well-known algorithm for finding the optimum matching is the <strong>hungarian method</strong>.</p> <p>Because it cannot be explained in a few sentences, I have to refer you to a book of your choice, or <a href="https://en.wikipedia.org/wiki/Hungarian_algorithm" rel="nofollow">Wikipedia article "Hungarian ...
1
2016-07-21T08:53:01Z
[ "python", "python-2.7", "cluster-analysis", "permutation" ]
Is it superfluous to declare # -*- coding: utf-8 -*- after #!/usr/bin/python3?
38,492,358
<p>I have been writing: </p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- </code></pre> <p>But I believe Python3 uses Unicode by default.</p>
0
2016-07-20T23:13:42Z
38,492,402
<p>The default encoding for python3 code <em>is</em> utf-8. See <a href="https://docs.python.org/3/howto/unicode.html#python-s-unicode-support" rel="nofollow">python's unicode support</a>.</p> <p>If you want to support python2.x in the same file or if you want to use a coding other than utf-8, you need that comment, ...
3
2016-07-20T23:18:55Z
[ "python", "utf-8" ]
How do I reference adjacent elements in a matrix?
38,492,553
<p>I am trying to make some code so that a single element a matrix can reference elements adjacent to it. Sort of like how you can only move game pieces to spaces adjacent. For example, I want to be able to say something like:</p> <pre><code>if x matrix element is adjacent to y element: y_element_adjacent = True ...
-1
2016-07-20T23:41:17Z
38,492,593
<p>Here's a simple way to obtain indices of all adjacent elements. </p> <pre><code>from itertools import product, starmap x, y = (x_coordinate, y_coordinate) # matrix values here cells = starmap(lambda a,b: (x+a, y+b), product((0,-1,+1), (0,-1,+1))) </code></pre> <p>For an input of <code>x,y = (1,1)</code>, this ret...
0
2016-07-20T23:46:42Z
[ "python", "algorithm" ]
get key and value from a list with dict
38,492,725
<p>I have a list of dict: </p> <pre><code>dividends=[ {"2005":0.18}, {"2006":0.21}, {"2007":0.26}, {"2008":0.31}, {"2009":0.34}, {"2010":0.38}, {"2011":0.38}, {"2012":0.38}, {"2013":0.38}, {"2014":0.415}, {"2015":0.427} ] </code></pre> <p>I want to retrieve the key and ...
1
2016-07-21T00:04:25Z
38,492,779
<p>Assuming your dictionaries always have a single key,value pair that you are extracting, you could use two list comprehensions:</p> <pre><code>l1 = [d.values()[0] for d in dividends] # ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'] l2 = [d.keys()[0] for d in dividends] # [0...
3
2016-07-21T00:10:08Z
[ "python", "list", "dictionary" ]
get key and value from a list with dict
38,492,725
<p>I have a list of dict: </p> <pre><code>dividends=[ {"2005":0.18}, {"2006":0.21}, {"2007":0.26}, {"2008":0.31}, {"2009":0.34}, {"2010":0.38}, {"2011":0.38}, {"2012":0.38}, {"2013":0.38}, {"2014":0.415}, {"2015":0.427} ] </code></pre> <p>I want to retrieve the key and ...
1
2016-07-21T00:04:25Z
38,492,789
<p>you can create two list and append keys in yearlist and values in dividendlist.</p> <p>here is the code.</p> <pre><code>dividends=[ {"2005":0.18}, {"2006":0.21}, {"2007":0.26}, {"2008":0.31}, {"2009":0.34}, {"2010":0.38}, {"2011":0.38}, {"2012":0.38}, {"2013":0.38}, {"2014":...
1
2016-07-21T00:10:59Z
[ "python", "list", "dictionary" ]
get key and value from a list with dict
38,492,725
<p>I have a list of dict: </p> <pre><code>dividends=[ {"2005":0.18}, {"2006":0.21}, {"2007":0.26}, {"2008":0.31}, {"2009":0.34}, {"2010":0.38}, {"2011":0.38}, {"2012":0.38}, {"2013":0.38}, {"2014":0.415}, {"2015":0.427} ] </code></pre> <p>I want to retrieve the key and ...
1
2016-07-21T00:04:25Z
38,492,798
<p>Try:</p> <pre><code>yearslist = dictionary.keys() dividendlist = dictionary.values() </code></pre> <p>For both keys and values:</p> <pre><code>items = dictionary.items() </code></pre> <p>Which can be used to split them as well:</p> <pre><code>yearslist, dividendlist = zip(*dictionary.items()) </code></pre>
0
2016-07-21T00:11:57Z
[ "python", "list", "dictionary" ]
fail to visualize a network in python - issue with pygraphviz?
38,492,870
<p>As I use some code to visualize a network, I encountered an error</p> <pre><code>Traceback (most recent call last): File "networkplot.py", line 21, in &lt;module&gt; pos = graphviz_layout(G, prog='neato') File "/opt/conda/lib/python2.7/site-packages/networkx/drawing/nx_agraph.py", line 228, in graphviz_layout retur...
0
2016-07-21T00:21:39Z
38,492,902
<p><code>libcgraph</code> is part of the graphviz package from <a href="http://graphviz.org/" rel="nofollow">http://graphviz.org/</a>. You'll need to install that before you install <code>pygraphviz</code>. The <code>graphviz</code> package you are installing with pip is a Python package and not the graphviz package yo...
0
2016-07-21T00:25:40Z
[ "python", "networkx", "pygraphviz" ]
Counting how many times each word occures in a text
38,492,913
<p>What I wanted this code to do, is read a textfile, and print how much each word occures in a percent. It <em>almost</em> works..</p> <p>I can't figure out how to sort the print out from highest occurrence to least (I had it at one point when I was copy/pasting other peoples code, I think I imported collections and ...
0
2016-07-21T00:27:29Z
38,493,020
<p>You can iterate through your dictionary like this:</p> <pre><code>for word in counts: print word, counts[word] </code></pre> <p>This will print each key in the dictionary once. For sorting, you should look at the built-in <code>sorted()</code> function: <a href="https://docs.python.org/3.4/library/functions.ht...
1
2016-07-21T00:39:00Z
[ "python", "python-2.7" ]
Counting how many times each word occures in a text
38,492,913
<p>What I wanted this code to do, is read a textfile, and print how much each word occures in a percent. It <em>almost</em> works..</p> <p>I can't figure out how to sort the print out from highest occurrence to least (I had it at one point when I was copy/pasting other peoples code, I think I imported collections and ...
0
2016-07-21T00:27:29Z
38,493,046
<p>For your first problem you can just Collections an OrderedDict as such:</p> <pre><code>sortedCounts = collections.OrderedDict(sorted(counts.items(),key=lambda t: t[1])) </code></pre> <p>To only print each word once:</p> <pre><code>for key, value in sortedCounts.iteritems(): print key, percent(value,total),"%" <...
0
2016-07-21T00:42:28Z
[ "python", "python-2.7" ]
Counting how many times each word occures in a text
38,492,913
<p>What I wanted this code to do, is read a textfile, and print how much each word occures in a percent. It <em>almost</em> works..</p> <p>I can't figure out how to sort the print out from highest occurrence to least (I had it at one point when I was copy/pasting other peoples code, I think I imported collections and ...
0
2016-07-21T00:27:29Z
38,493,163
<p>Your code is very close to being workable; I just see a few issues that are causing your problems:</p> <p><strong>P1:</strong> Your code doesn't take non-word characters into account. For example, <code>word;</code>, <code>word.</code>, and <code>word</code> would all be treated as unique words. </p> <pre><code>te...
0
2016-07-21T00:55:23Z
[ "python", "python-2.7" ]
Python MySQLdb response times are extremely different on silmiliar set
38,492,932
<p>I am designing a crontab job with Python+MySQLdb to extract data from MySQL, generate XML files and get them zipped. Yes, it is an archive task happens at noon everyday.</p> <p>My code:</p> <pre><code>#!/usr/bin/env python #encoding: utf-8 from dmconfig import DmConf #from dmdb import Dmdb import redis import MySQ...
0
2016-07-21T00:29:25Z
38,516,060
<p>I did more labs on this SQL query. At last I found it is related to memory usage of MySQLdb. Although the total dataset may have only 5794 row, if I added LIMIT 5000, the query only takes 0.3 second, otherwise it takes 60+ seconds. </p> <p>So, as a work-around approach, I use LIMIT and some pagination methotd to qu...
0
2016-07-21T23:44:42Z
[ "python", "mysql" ]
Which way is better to read/write data from/to large files?
38,492,942
<p>If we need to read/write some data from/to a large file each time before/after processing, which of the following way (with some demonstration Python codes) is better?</p> <ol> <li><p>Open the file each time when we need to read/writing and close immediately after reading/writing. This way seems to be safer? but s...
1
2016-07-21T00:30:07Z
38,493,128
<p>You should wrap your code in solution 2 in a <code>try except finally</code> and always close the file in finally. This way even if there will be errors, your file will close itself.</p> <p>EDIT: as someone else pointed out you can use <code>with</code> to handle that for you.</p>
0
2016-07-21T00:51:58Z
[ "python", "matlab", "file", "io", "hdf5" ]
Which way is better to read/write data from/to large files?
38,492,942
<p>If we need to read/write some data from/to a large file each time before/after processing, which of the following way (with some demonstration Python codes) is better?</p> <ol> <li><p>Open the file each time when we need to read/writing and close immediately after reading/writing. This way seems to be safer? but s...
1
2016-07-21T00:30:07Z
38,493,152
<p>If you are concerned about using multiple files within the "with" statement, you can open more than one file with a compound statement, or nest the "with" blocks. This is detailed in the answer here:</p> <p><a href="http://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement">How to ...
0
2016-07-21T00:54:14Z
[ "python", "matlab", "file", "io", "hdf5" ]
Problems in datatype while csv file as panda dataframe
38,492,963
<p>I have been trying to import my dataset using read.csv in python notebook. However, on importing my dataset I see that the datatype of each column becomes as object. <a href="http://i.stack.imgur.com/eayYS.png" rel="nofollow">Plz click this image to see the issue</a></p> <p>Is there a way that I can retain the d...
2
2016-07-21T00:32:42Z
38,493,025
<p>This occurs when you have inconsistent datatypes, e.g. integers and characters such as a blank space. It is difficult to tell without viewing a sample of your actual data, but I suspect this is the issue. For example,</p> <pre><code>&gt;&gt;&gt; pd.DataFrame([1, 2, '']).info() &lt;class 'pandas.core.frame.DataFra...
1
2016-07-21T00:39:20Z
[ "python", "csv", "pandas", "dataframe", "import" ]
Multiple boolean tests in IF statement with 'all()' function
38,492,991
<pre><code>def common(num): #returns true if num is divisible by all the 'i' integers if all(num%divisor==0 for divisor in (1,10)): return True else: return False print(common(2520)) --&gt; True print(common(10)) --&gt; True print(common(17)) --&gt; False </code></pre> <p>Hi all, this...
1
2016-07-21T00:36:05Z
38,493,068
<p>The way to find oneself:</p> <pre><code>num=10 for divisor in (1,10): print(divisor, num%divisor , num%divisor==0) </code></pre> <p>gives</p> <pre><code>1 0 True 10 0 True </code></pre> <p>and makes you understand that <code>(1,10)</code> is a tuple, while you certainly wanted <code>range(1,10)</code>.</p> ...
3
2016-07-21T00:45:58Z
[ "python", "function", "boolean-logic", "boolean-expression", "boolean-operations" ]
Global Not Working Properly [Python]
38,493,045
<p>It's kind of hard to explain by situation. I'll try the best I can.</p> <p>I'm making a program to make using driftnet easier for new users. You first enter the gateway IP and then the target IP, the your interface. In the program, once you enter all those, it opens a new terminal window, you then start the second ...
2
2016-07-21T00:42:25Z
38,493,073
<p>Have you tried adding the global variable after import etc...then calling the var inside functions as global? </p> <pre><code>import os import time from subprocess import call gateway = '' target = '' inter = '' </code></pre>
0
2016-07-21T00:46:44Z
[ "python" ]
Global Not Working Properly [Python]
38,493,045
<p>It's kind of hard to explain by situation. I'll try the best I can.</p> <p>I'm making a program to make using driftnet easier for new users. You first enter the gateway IP and then the target IP, the your interface. In the program, once you enter all those, it opens a new terminal window, you then start the second ...
2
2016-07-21T00:42:25Z
38,493,153
<p>I don't know what "Driftnet" is, and I'm not sure exactly what you're trying to do, but I can explain the behavior you're seeing.</p> <p>In Driftnet2.py, you call:</p> <pre><code>import Driftnet </code></pre> <p>which causes the Python code in Driftnet.py to be evaluated. That is what the <code>import</code> sta...
1
2016-07-21T00:54:19Z
[ "python" ]
Global Not Working Properly [Python]
38,493,045
<p>It's kind of hard to explain by situation. I'll try the best I can.</p> <p>I'm making a program to make using driftnet easier for new users. You first enter the gateway IP and then the target IP, the your interface. In the program, once you enter all those, it opens a new terminal window, you then start the second ...
2
2016-07-21T00:42:25Z
38,497,934
<p>This is what the <a href="http://stackoverflow.com/questions/419163/what-does-if-name-main-do"><code>if __name__=='__main__':</code></a> construct exists for. Change the code in Driftnet.py to this:</p> <pre><code>import os import time from subprocess import call def drift(): global gateway gateway = raw_i...
0
2016-07-21T07:39:27Z
[ "python" ]
Getting Django for Python 3 Started for Mac django-admin not working
38,493,057
<p>I have been trying to set up Django for Python 3 for for 2 days now. I have installed python 3.5.2 on my Mac Mini. I have also have pip3 installed succesfully. I have installed Django using <code>pip3 install Django</code>. The problem is that when I try to start my project by typing <code>django-admin startproject ...
1
2016-07-21T00:44:06Z
38,493,996
<p>Activate <code>virtualenv</code> and install Django there (with <code>python -m pip install django</code>). Try <code>python -m django startproject mysite</code>. You can use <code>python -m django</code> instead of <code>django-admin</code> since Django 1.9.</p>
0
2016-07-21T02:42:17Z
[ "python", "django", "python-3.x", "django-admin" ]
Python 2.7 Pip module not installing or setting paths via cmd?
38,493,144
<p>I've been having some really odd issues with trying to install and use the Python "Pip" module. Firstly, I've installed the pip module by downloading the getpip.py file and running it which has replaced my pre existing pip which seemed to work fine. However whenever I try to use pip it always comes up with "pip is n...
0
2016-07-21T00:53:25Z
38,493,199
<p>You're using the wrong path, Pip should reside in the <code>Scripts</code> sub directory, set PATH to <code>C:\Python27\Scripts</code> then you should restart cmd.</p>
0
2016-07-21T00:59:47Z
[ "python", "windows", "python-2.7" ]
Using BeautifulSoup to find all tags containing a AND NOT containing b
38,493,154
<p>I am using bs4 to pull out li tags with class of js-stream-item but not containing scroll-bump-user-card from the following. (which is getting a, b only)</p> <pre><code>&lt;li class="js-stream-item stream-item "&gt;a&lt;li&gt; &lt;li class="js-stream-item stream-item stream-item "&gt;b&lt;li&gt; &lt;li class="js-st...
1
2016-07-21T00:54:20Z
38,493,584
<p>First of all, <code>class</code> is a special <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#multi-valued-attributes" rel="nofollow">multi-valued attribute</a> which requires <a href="http://stackoverflow.com/a/34294195/771848">special handling</a>.</p> <p>One option is to use a <a href="https://ww...
0
2016-07-21T01:51:27Z
[ "python", "regex", "python-2.7", "beautifulsoup" ]
Get distinct datatypes within the same Series in Pandas
38,493,213
<p>Let's say we have a pandas series which contains a mixture of datatypes as below (string, int and datetime)</p> <p>If i check the dtype on the diff_series (<code>diff_series.dtype</code>), it shows me that it's an object as expected. I would like to get the distinct datatypes that are in the series. I have the foll...
2
2016-07-21T01:01:45Z
38,493,419
<p>This should be more pandonic:</p> <pre><code>diff_series.apply(type) 0 &lt;type 'str'&gt; 1 &lt;type 'str'&gt; 2 &lt;type 'int'&gt; 3 &lt;type 'str'&gt; 4 &lt;type 'datetime.datetime'&gt; dtype: object </code></pre>
4
2016-07-21T01:30:09Z
[ "python", "numpy", "pandas", "types", "series" ]
Get distinct datatypes within the same Series in Pandas
38,493,213
<p>Let's say we have a pandas series which contains a mixture of datatypes as below (string, int and datetime)</p> <p>If i check the dtype on the diff_series (<code>diff_series.dtype</code>), it shows me that it's an object as expected. I would like to get the distinct datatypes that are in the series. I have the foll...
2
2016-07-21T01:01:45Z
38,493,484
<p>We could do something like:</p> <pre><code>In [4]: diff_series.map(type).value_counts() Out[4]: &lt;class 'str'&gt; 3 &lt;class 'datetime.datetime'&gt; 1 &lt;class 'int'&gt; 1 dtype: int64 </code></pre> <p>Or, might as well "go all out": </p> <pre><code>In [5]: diff_series.ma...
3
2016-07-21T01:37:18Z
[ "python", "numpy", "pandas", "types", "series" ]
Convert .xls to .xlsx so that Openpyxl can work with it
38,493,257
<p>I wrote a flask application that will be used to process some excel files, however, I wrote it for .xlsx files. The inputted files might be .xls files, which I know Openpyxl can't open. How can I convert the file to .xlsx before processing it with Openpyxl in my application?</p> <p>I saw something online about usin...
0
2016-07-21T01:07:11Z
38,494,890
<p>My recommendation: Use xlrd to read the values you need, and openpyxl to create a new xlsx workbook. You just need to be able to get all of the relevant info using xlrd.</p> <p>The only thing you're doing which isn't just reading values from cells is selecting the "active" worksheet. I found <a href="https://groups...
0
2016-07-21T04:29:27Z
[ "python", "openpyxl", "xlrd" ]
Convert .xls to .xlsx so that Openpyxl can work with it
38,493,257
<p>I wrote a flask application that will be used to process some excel files, however, I wrote it for .xlsx files. The inputted files might be .xls files, which I know Openpyxl can't open. How can I convert the file to .xlsx before processing it with Openpyxl in my application?</p> <p>I saw something online about usin...
0
2016-07-21T01:07:11Z
38,502,394
<p>Best thing is to pipe the XLS file through OpenOffice / LibreOffice in <a href="https://ask.libreoffice.org/en/question/53173/libreoffice-444-and-the-headless-install/" rel="nofollow">headless mode</a> to do the conversion and then load the file in Python for processing.</p>
0
2016-07-21T10:57:11Z
[ "python", "openpyxl", "xlrd" ]
I am getting the error 'Response' object has no attribute 'fromstring'
38,493,295
<p>I am trying to use xpath in my django app and I keep getting the error</p> <pre><code>'Response' object has no attribute 'fromstring' </code></pre> <p>I don't understand why. I have researched and the only thing I saw was people having probblems with text instead of from string. Heres my code</p> <pre><code>def p...
0
2016-07-21T01:12:07Z
38,493,400
<p>Don't nest functions like this. Un-nest your function and it will work fine.</p> <p>You define <code>html = requests.get(*)</code></p> <p>What this returns is a response object.</p> <p>In your nested function you're using this <code>html</code> instead of what you imported <code>from lxml import html</code> becau...
3
2016-07-21T01:27:44Z
[ "python", "django", "xpath", "web-scraping" ]
Python: Even if the the if statement equals false it still executes the code inside the if statement
38,493,326
<p>Even if the the if statement equals false it still executes the code inside the if statement. Here is the code:</p> <pre><code># Imports: import time # Code Starts Here: print("Welcome to a test application By: David(Toxicminibro)") time.sleep(1.25) Donald = "Donald Trump" donald = "donald trump" Hillary = "Hilla...
1
2016-07-21T01:17:38Z
38,493,371
<p>I think you mean to do :</p> <pre><code>if name == Donald or name == donald or name == Hillary or name == hillary: </code></pre> <p>Have a <a href="https://docs.python.org/2.4/lib/truth.html" rel="nofollow">look at this link</a>; it explains how various values are considered to be "true" or "false"</p>
2
2016-07-21T01:22:43Z
[ "python", "if-statement" ]
Python: Even if the the if statement equals false it still executes the code inside the if statement
38,493,326
<p>Even if the the if statement equals false it still executes the code inside the if statement. Here is the code:</p> <pre><code># Imports: import time # Code Starts Here: print("Welcome to a test application By: David(Toxicminibro)") time.sleep(1.25) Donald = "Donald Trump" donald = "donald trump" Hillary = "Hilla...
1
2016-07-21T01:17:38Z
38,493,382
<pre><code>if name in (Donald, donald, Hillary, hillary): print("No. Stop it.") else: print("Hello " + name + " !") </code></pre>
2
2016-07-21T01:25:26Z
[ "python", "if-statement" ]
Python: Even if the the if statement equals false it still executes the code inside the if statement
38,493,326
<p>Even if the the if statement equals false it still executes the code inside the if statement. Here is the code:</p> <pre><code># Imports: import time # Code Starts Here: print("Welcome to a test application By: David(Toxicminibro)") time.sleep(1.25) Donald = "Donald Trump" donald = "donald trump" Hillary = "Hilla...
1
2016-07-21T01:17:38Z
38,493,390
<p>A more Pythonic way of doing this is: <code>if name.lower() in [donald, hillary]:</code></p>
1
2016-07-21T01:26:37Z
[ "python", "if-statement" ]
multiple conditions in conditional
38,493,383
<p>So i'm not exactly sure how to ask this question exactly but basically I want to see if any value between two variables is also in between two other variables. So for instance here is a sample of what code might look like of what I'm explaining</p> <pre><code>var1 = 0 var2 = 20 var3 = 5 var4 = 15 if var3 &lt;= [any...
1
2016-07-21T01:25:32Z
38,493,426
<p>Always remember when you want to set a condition for some value, lets say 'a' between x and y, you can set a condition, <code>a&gt;x and a&lt;y</code>, which is what you want:</p> <pre><code>if var3 &gt;= var1 and var3 &lt;= var2 and var3 &lt;=var4: do something </code></pre> <p>I am not 100% sure whether you ...
0
2016-07-21T01:30:39Z
[ "python", "variables", "if-statement", "conditional" ]
multiple conditions in conditional
38,493,383
<p>So i'm not exactly sure how to ask this question exactly but basically I want to see if any value between two variables is also in between two other variables. So for instance here is a sample of what code might look like of what I'm explaining</p> <pre><code>var1 = 0 var2 = 20 var3 = 5 var4 = 15 if var3 &lt;= [any...
1
2016-07-21T01:25:32Z
38,493,439
<p>You mean to do: </p> <pre><code> for i in range(var1, var2+1): if var3 &lt;= i &lt;=var4: do something </code></pre>
0
2016-07-21T01:31:36Z
[ "python", "variables", "if-statement", "conditional" ]
multiple conditions in conditional
38,493,383
<p>So i'm not exactly sure how to ask this question exactly but basically I want to see if any value between two variables is also in between two other variables. So for instance here is a sample of what code might look like of what I'm explaining</p> <pre><code>var1 = 0 var2 = 20 var3 = 5 var4 = 15 if var3 &lt;= [any...
1
2016-07-21T01:25:32Z
38,493,489
<p>Let's use a bit of mathematical notation. So you have two number ranges, [<em>a</em>, <em>b</em>] and [<em>x</em>, <em>y</em>], where [<em>a</em>, <em>b</em>] represents the concept of "all numbers between <em>a</em> and <em>b</em>".</p> <p>One interpretation is you want to see if [<em>a</em>, <em>b</em>] is a <str...
1
2016-07-21T01:37:51Z
[ "python", "variables", "if-statement", "conditional" ]
multiple conditions in conditional
38,493,383
<p>So i'm not exactly sure how to ask this question exactly but basically I want to see if any value between two variables is also in between two other variables. So for instance here is a sample of what code might look like of what I'm explaining</p> <pre><code>var1 = 0 var2 = 20 var3 = 5 var4 = 15 if var3 &lt;= [any...
1
2016-07-21T01:25:32Z
38,493,505
<p>Assuming that there isn't an ordering among the variables that's known ahead of time....</p> <pre><code>min34 = min(var3, var4) max34 = max(var3, var4) if ( (min34 &lt; var1 &amp;&amp; max34 &gt; var1) || (min34 &lt; var2 &amp;&amp; max34 &gt; var2) ) : do something </code></pre> <p>Use "&lt;=" and ">=" if th...
0
2016-07-21T01:39:47Z
[ "python", "variables", "if-statement", "conditional" ]
multiple conditions in conditional
38,493,383
<p>So i'm not exactly sure how to ask this question exactly but basically I want to see if any value between two variables is also in between two other variables. So for instance here is a sample of what code might look like of what I'm explaining</p> <pre><code>var1 = 0 var2 = 20 var3 = 5 var4 = 15 if var3 &lt;= [any...
1
2016-07-21T01:25:32Z
38,811,854
<p>I'm surprised at the complexity of other answers. This should simply be:</p> <pre><code>def intersect(a, A, x, X): '''Return True if any number in range(a, A+1) is in range(x, X+1).''' return a &lt;= X and x &lt;= A </code></pre> <p>Note that intersection is symmetric, so <code>intersect(a,b,x,y) == intersect(...
2
2016-08-07T07:15:45Z
[ "python", "variables", "if-statement", "conditional" ]