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
Argparse Reopening file.
39,333,854
<p>I'm using the argparse module and I have a log file which is continuously appended to. I want to open args.file, do something with the content, then close it and opening it again after some time. </p> <p>An example piece of code:</p> <pre><code>import argparse import time parser = argparse.ArgumentParser() parser.add_argument('file',type=file) args = parser.parse_args() for _ in range(3): data = args.file.read() print data time.sleep(3) </code></pre> <p>Note that args.file.seek(0) is no solution here. I can close the file with args.file.close() but how to open it again? </p> <p>I can make the filename-argument just a normal string of the filename but i would like to know a solution keeping the argumenttype as a filename. </p>
0
2016-09-05T15:36:25Z
39,333,897
<p>you can open it again using</p> <pre><code>args.file = open(args.file.name) </code></pre>
0
2016-09-05T15:39:59Z
[ "python", "io", "argparse" ]
Argparse Reopening file.
39,333,854
<p>I'm using the argparse module and I have a log file which is continuously appended to. I want to open args.file, do something with the content, then close it and opening it again after some time. </p> <p>An example piece of code:</p> <pre><code>import argparse import time parser = argparse.ArgumentParser() parser.add_argument('file',type=file) args = parser.parse_args() for _ in range(3): data = args.file.read() print data time.sleep(3) </code></pre> <p>Note that args.file.seek(0) is no solution here. I can close the file with args.file.close() but how to open it again? </p> <p>I can make the filename-argument just a normal string of the filename but i would like to know a solution keeping the argumenttype as a filename. </p>
0
2016-09-05T15:36:25Z
39,334,519
<pre><code>parser.add_argument('file',type=file) </code></pre> <p>does not mean, <code>the argument is to be a file</code>. It means</p> <pre><code>value = file(astring) args.file = value </code></pre> <p>The <code>type</code> parameter is a function that operates on a string. In Python3 <code>file</code> has been removed; the equivalent would be:</p> <pre><code>parser.add_argument('file',type=open) </code></pre> <p>There is a <code>argparse.FileType</code> class than can be used to open a file with a defined mode; it also recognizes the <code>-</code> value. This can be useful in small scripts that take an input and output, and do little else. But generally it is better to open the file yourself, preferably in a <code>with</code> context so ensure it is closed when no longer used.</p> <pre><code>parser.add_argument('file_name') args = parser.parse_args() for _ in range(3): with open(args.file_name) as f: data = f.read() print data time.sleep(3) </code></pre> <p>What <code>Filetype</code> does do for you is give a 'nice' argparse error message if the file can't be opened. For example if the name was mistyped in the command line.</p>
1
2016-09-05T16:25:43Z
[ "python", "io", "argparse" ]
Python: Pandas: making a dictionary from dataframe
39,333,881
<p>I am trying to convert a dataframe to dictionary:</p> <pre><code>xtest_cat = xtest_cat.T.to_dict().values() </code></pre> <p>but it gives a warning :</p> <blockquote> <p>Warning: DataFrame columns are not unique, some columns will be omitted python</p> </blockquote> <p>I checked the columns names of the dataframe(xtest_cat) : </p> <pre><code>len(list(xtest_cat.columns.values)) len(set(list(xtest_cat.columns.values))) </code></pre> <p>they are all unique. Can anyone help me out ? </p>
1
2016-09-05T15:38:49Z
39,334,000
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> for create <code>unique</code> index:</p> <pre><code>xtest_cat = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]}) xtest_cat.index = [0,1,1] print (xtest_cat) A B C 0 1 4 7 1 2 5 8 1 3 6 9 print (xtest_cat.index.is_unique) False xtest_cat.reset_index(drop=True, inplace=True) print (xtest_cat) A B C 0 1 4 7 1 2 5 8 2 3 6 9 xtest_cat = xtest_cat.T.to_dict().values() print (xtest_cat) dict_values([{'B': 4, 'C': 7, 'A': 1}, {'B': 5, 'C': 8, 'A': 2}, {'B': 6, 'C': 9, 'A': 3}]) </code></pre> <p>You can also omit <code>T</code> and add parameter <code>orient='index'</code>:</p> <pre><code>xtest_cat = xtest_cat.to_dict(orient='index').values() print (xtest_cat) dict_values([{'B': 4, 'C': 7, 'A': 1}, {'B': 5, 'C': 8, 'A': 2}, {'B': 6, 'C': 9, 'A': 3}]) </code></pre> <p><code>orient='record'</code> is better:</p> <pre><code>xtest_cat = xtest_cat.to_dict(orient='records') print (xtest_cat) [{'B': 4, 'C': 7, 'A': 1}, {'B': 5, 'C': 8, 'A': 2}, {'B': 6, 'C': 9, 'A': 3}] </code></pre>
1
2016-09-05T15:48:20Z
[ "python", "pandas", "dictionary", "dataframe", "multiple-columns" ]
Python 3 - Cant get data to display when called
39,333,882
<p>This is the function defined in class "Roster"</p> <pre><code>class Roster: def __init__(self, name, phone, jersy): self.name = name self.phone = phone self.jersy = jersy def setName(self, name): self.name = name def setPhone(self, phone): self.phone = phone def setnumber(self, jersy): self.number = jersy def getName(self): return self.name def getPhone(self): return self.phone def getNumber(self): return self.jersy def displayMenu(self): print ("==========Selection Menu==========") print ("1. Display the Roster") print ("2. Add a Player to the Roster") print ("3. Remove a Player from the Roster") print ("4. Change a Player Name displayed in the Roster") print ("5. Load the Roster") print ("6. Save the Roster") print ("7. Quit") print () return int (input ("Selection&gt;&gt;&gt; ")) def displayRoster(self): print ("****Team Roster****") print ("Player's Name:", self.name) print ("Player's Telephone number:", self.phone) print ("Player's Jersey number:", self.jersy) </code></pre> <p>This is the code:( I understand that you don't have to "Import" a class into itself so there is no Import call)</p> <pre><code>Players = {} def addPlayer(Players): newName = input ("Add a player's Name: ") newPhone = input ("Phone number: ") newNumber = input ("Jersey number: ") Players[newName] = newName, newPhone, newNumber return Players def removePlayer(Players): removeName = input ("What name would you like to remove? ") if removeName in Players: del Players[removeName] else: print ("Name was not found!") return Players def editPlayer(Players): oldName = input ("What name would you like to change? ") if oldName in Players: newName = input ("What is the new name? ") newPhone = input ("Phone number: ") newNumber = input ("Jersey number: ") Players[newName] = newName, newPhone, newNumber del Players[oldName] print ("***", oldName, "has been changed to", newName) else: print ("Name was not found!") return Players def saveRoster(Players): print("Saving data...") outFile = open("D:\Documents\Grantham\Python Projects\Python Week Six\Roster.txt", "wt") for x in Players.keys(): name = Roster.getName(Players) phone = Roster.getPhone(Players) jersy = Roster.getNumber(Players) outFile.write("name+","+phone+","+jersy+","\n") print("Data saved.") outFile.close() return Players def loadRoster(): Players = {} filename = input("Filename to load: ") inFile = open(Filename(Players), "rt") print("Loading data...") while True: inLine = inFile.readline() if not inLine: break inLine = inLine[:-1] name, phone, jersy = inLine.split(",") Players[name] = RosterClass.Players(name, phone, jersy) print("Data Loaded Successfully.") inFile.close() return Players print ("Welcome to the Team Manager") menuSelection = Roster.displayMenu ('Players') while menuSelection != 7: if menuSelection == 1: myRoster.displayRoster (Players) elif menuSelection == 2: Players = addPlayer (Players) elif menuSelection == 3: Players = removePlayer (Players) elif menuSelection == 4: Players = editPlayer (Players) elif menuSelection==5: loadRoster(Players) elif menuSelection==6: saveRoster(Players) menuSelection = Roster.displayMenu (Players) print ("Exiting Program...") </code></pre> <p>I keep getting this error:</p> <pre><code>Traceback (most recent call last): File ".idea/Adv Team Roster.py", line 108, in &lt;module&gt; Roster.displayRoster ('Players') File ".idea/Adv Team Roster.py", line 39, in displayRoster print ("Player's Name:", self.name) AttributeError: 'str' object has no attribute 'name' </code></pre> <p>I'm also having problems with the save/load routine but that's another post.</p>
-2
2016-09-05T15:38:50Z
39,333,986
<p>Your code has a number of conceptual problems that you need to solve before you can start trying to run it and start asking for help with compiler errors. Here are three, to get you started.</p> <p>(1) Your <code>Roster</code> class is designed to be instantiated, but you never create an instance. Whenever you write a class, among the early questions you should ask yourself are, "What code will create instances of this class? Under what circumstances? How will that code get the data it needs to create an instance? What will that code do with the instance right after it has created the instance?" </p> <p>(2) Your <code>Roster</code> class is misnamed, which is probably confusing you. A roster is a list of players. Your <code>Roster</code> is data about a single player. I recommend renaming <code>Roster</code> to <code>Player</code>, creating some data structure (like your current <code>Players</code>) called <code>roster</code> to hold a bunch of players, and then following the consequences of that change.</p> <p>(3) Once you have a clear idea of what rosters and players are, you can ask questions like, "Where will I store rosters and players? How will I pass them around to different parts of my code? What functionality should be associated with a roster? with a player? with the top level of my code? with other entities that I haven't thought about yet?"</p> <p>After all that thinking, you might come the conclusion that <code>displayPlayer</code> should be a function on the <code>Player</code> class and that you therefore need to rename <code>displayRoster</code> to <code>displayPlayer</code>. Since you will have created instances of Player, perhaps one called myplayer (that's just an example name), you will now be able to say <code>myplayer.displayPlayer()</code>, and Python will run the <code>displayPlayer</code> code with <code>self</code> automatically set to the myplayer instance. At that point the compiler error you are complaining about will disappear, not because you "fixed" it, but because it naturally goes away once you are thinking clearly about your system.</p> <p>And in general, that is the way to think about compiler errors: If it's not immediately obvious how to fix it, then it's probably a sign that you aren't thinking clearly about your system, so you need to take a step back and think about higher-level problems than the specific error.</p>
3
2016-09-05T15:46:31Z
[ "python", "attributeerror" ]
Exporting a random sample from CSV file to a new CSV file - output is messy
39,333,994
<p>I am trying to export a random subset of a CSV file to a new CSV file using the following code:</p> <pre><code>with open("DepressionEffexor.csv", "r") as effexor: lines = [line for line in effexor] random_choice = random.sample(lines, 229) with open("effexorSample.csv", "w") as sample: sample.write("\n".join(random_choice)) </code></pre> <p>But the problem is that the output CSV file is very messy. for example, some part of a data in a filed was printed in the next line. How can I solve the problem? In addition, I want to know how can I use pandas for this problem rather than CSV. Thanks !</p>
0
2016-09-05T15:47:15Z
39,334,078
<p>Assuming you had a CSV read into pandas:</p> <pre><code>df = pandas.read_csv("csvfile.csv") sample = df.sample(n) sample.to_csv("sample.csv") </code></pre> <p>You could make it even shorter:</p> <pre><code>df.sample(n).to_csv("csvfile.csv") </code></pre> <p>The <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-in-csv" rel="nofollow">Pandas IO docs</a> have a great deal more information and options available, as does the <code>dataframe.sample</code> method.</p>
3
2016-09-05T15:54:07Z
[ "python", "csv", "pandas", "random" ]
Exporting a random sample from CSV file to a new CSV file - output is messy
39,333,994
<p>I am trying to export a random subset of a CSV file to a new CSV file using the following code:</p> <pre><code>with open("DepressionEffexor.csv", "r") as effexor: lines = [line for line in effexor] random_choice = random.sample(lines, 229) with open("effexorSample.csv", "w") as sample: sample.write("\n".join(random_choice)) </code></pre> <p>But the problem is that the output CSV file is very messy. for example, some part of a data in a filed was printed in the next line. How can I solve the problem? In addition, I want to know how can I use pandas for this problem rather than CSV. Thanks !</p>
0
2016-09-05T15:47:15Z
39,334,082
<p>Using pandas, this translates to:</p> <pre><code>import pandas as pd #Read the csv file and store it as a dataframe df = pd.read_csv('DepressionEffexor.csv') #Shuffle the dataframe and store it df_shuffled = df.iloc[np.random.permutation(len(df))] #You can reset the index with the following df_shuffled.reset_index(drop=True) </code></pre> <p>You can splice the dataframe later to choose what you want.</p>
0
2016-09-05T15:54:40Z
[ "python", "csv", "pandas", "random" ]
How to keep track of whether all strings in a list have a specific string present in them?
39,334,049
<p>I have a list of strings within which I need to search for a specific sub-string and return a result only when the sub-string is present in every string that is in the list. My first idea was to create a list of boolean values that correspond with whether the sub-string is present in each larger string in my list, and then write another loop to check whether this list of booleans is True at every index. Does anybody have any suggestions for a more elegant and efficient method?</p> <p>Thank you kindly!</p>
1
2016-09-05T15:52:27Z
39,334,089
<p>you can use <a href="https://docs.python.org/2/library/functions.html#all" rel="nofollow"><code>all()</code></a> and <a href="https://docs.python.org/2/reference/expressions.html#in" rel="nofollow"><code>in</code></a>:</p> <pre><code>l = ["pie", "lie", "die"] all( ['ie' in x for x in l] ) </code></pre> <p>The above version may perform <a href="http://cis.poly.edu/cs1114/pyLecturettes/short-circuit-eval.html" rel="nofollow">unnecessary checks</a>.</p> <pre><code>all( 'ie' in x for x in l ) </code></pre>
2
2016-09-05T15:55:16Z
[ "python", "list", "boolean" ]
How to keep track of whether all strings in a list have a specific string present in them?
39,334,049
<p>I have a list of strings within which I need to search for a specific sub-string and return a result only when the sub-string is present in every string that is in the list. My first idea was to create a list of boolean values that correspond with whether the sub-string is present in each larger string in my list, and then write another loop to check whether this list of booleans is True at every index. Does anybody have any suggestions for a more elegant and efficient method?</p> <p>Thank you kindly!</p>
1
2016-09-05T15:52:27Z
39,334,942
<p>I would use the built-in <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all</code></a> function along with <a href="https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions" rel="nofollow">generator expression</a> to avoid creating a throw-away intermediate list. Since the code can be expressed as one line, I'd also define it using a <a href="https://docs.python.org/3/reference/expressions.html#lambda" rel="nofollow"><code>lambda</code> expression</a> instead of the usual <code>def function()</code>:</p> <pre><code># define function via lambda in_all = lambda strings, specific: all(specific in strng for strng in strings) in_all.__doc__ = """ Check whether all strings in list contain specified string. """ l1 = ["day", "lay", "may"] l2 = ["day", "lay", "may", "not"] print(in_all(l1, "ay")) # -&gt; True (all had specific string) print(in_all(l2, "ay")) # -&gt; False (at least one didn't have # the specific string) </code></pre>
0
2016-09-05T16:58:33Z
[ "python", "list", "boolean" ]
plot a fuction in the same graph with different arguments next to each other
39,334,057
<p>I have a matrix H, that can take 3 directional arguments. I want to plot the eigenvalues (just think of it as function) with one set of arguments &amp; next to it - still in the same graph - the function with another set of arguments. This is used in physics very often i.e. when plotting band structures. It looks like: </p> <p><a href="http://i.stack.imgur.com/gvJED.png" rel="nofollow"><img src="http://i.stack.imgur.com/gvJED.png" alt="enter image description here"></a></p> <p>This is not just changing 0 to Gamma and 2pi (lattice constant =1) to X, but really doing mutlipleplots next to each other in one plot. </p> <p>Edit:</p> <p>I have no measured data--> this is all calculated. I have a np.matrix (Hamiltonian - 8x8) that depends on 7 arguments, the only ones I change here are that of the directions. g=Gamma, X, ... are positions (I know the directions of them.) Each plot is generated like this:</p> <pre><code>fig4=plt.figure() LG=fig4.add_subplot(111) for val in np.linspace(-np.pi/a, 0, 1000): LG.scatter([val]*8, H(val, val , val, -15.2, -s*10.25, 19.60, -5.30)) plt.grid() plt.title(r"$L-\Gamma$") plt.xlabel(r"$k$ in high symmetry points") plt.xticks([-C*0.5, 0.], ["L", "$\Gamma$"]) plt.ylabel("energy/eV") plt.show() </code></pre> <p>I included the physics, so that physicians understand it easier. In case they are not many here:</p> <p>I have a function plot1 and plot2 &amp; I want to append plot2 horizontally in one graph with same y-axes but different x- axes. Like in the picture(from g-X is one function, from X to W another and so on).</p> <p>Edit2: The answer of TobyD &amp; pathoren made it possible to plot a function w/ several arguments next to each w/ free arguments. I think that my problem is in principle solveable by this, but since I don't have functions but a matrix and want to calculate eigenvalues and have more than one directional argument it's complicated. I manage to produce a plot I only want to cut horizontally together (but not like paint, but with one x-axes description).</p> <p>Edit3: Thank you pathoren &amp; TobyD for your help. The easiest way was just to change the argument x+something, x-something, now I have more than way, which can proof usefull eventually. </p> <p><a href="http://i.stack.imgur.com/KqMN9.png" rel="nofollow">final answer</a></p>
-1
2016-09-05T15:52:52Z
39,334,208
<p>Below is a script where a function <code>f</code> takes 3 parameters <code>a, b, c</code>. The x-values are split into three different regimes, <code>x1, x2, x3</code>, with corresponding function values <code>f1, f2, f3</code>. At some breakpoints (defined by <code>x_ticks</code>) there are lines drawn, and the xticks are only shown for those points. The xlabels are set by <code>x_ticklabels</code>, only at <code>x_ticks</code>-position.</p> <pre><code> import numpy as np import matplotlib.pyplot as plt def f(x, a, b, c): return a*x**2 + b*x + c x1 = np.linspace(0, 10, 100) f1 = f(x1, 1, 2, 3) x2 = np.linspace(10, 20, 100) f2 = f(x2, 3, -2, 0) x3 = np.linspace(20, 50, 100) f3 = f(x3, -1, 2, 1) fig, ax = plt.subplots(1, 1) ax.plot(x1, f1, label='f1') ax.plot(x2, f2, label='f2') ax.plot(x3, f3, label='f3') x_ticks = [10, 20, 50] x_ticklabels = ['K', 'L', 'M'] ax.vlines(x_ticks, ax.get_ylim()[0], ax.get_ylim()[1]) ax.set_xticks(x_ticks) ax.set_xticklabels(x_ticklabels) ax.set_yticks([]) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/TIwwl.png" rel="nofollow"><img src="http://i.stack.imgur.com/TIwwl.png" alt="enter image description here"></a></p>
-1
2016-09-05T16:03:48Z
[ "python", "matplotlib", "plot", "physics", "axes" ]
plot a fuction in the same graph with different arguments next to each other
39,334,057
<p>I have a matrix H, that can take 3 directional arguments. I want to plot the eigenvalues (just think of it as function) with one set of arguments &amp; next to it - still in the same graph - the function with another set of arguments. This is used in physics very often i.e. when plotting band structures. It looks like: </p> <p><a href="http://i.stack.imgur.com/gvJED.png" rel="nofollow"><img src="http://i.stack.imgur.com/gvJED.png" alt="enter image description here"></a></p> <p>This is not just changing 0 to Gamma and 2pi (lattice constant =1) to X, but really doing mutlipleplots next to each other in one plot. </p> <p>Edit:</p> <p>I have no measured data--> this is all calculated. I have a np.matrix (Hamiltonian - 8x8) that depends on 7 arguments, the only ones I change here are that of the directions. g=Gamma, X, ... are positions (I know the directions of them.) Each plot is generated like this:</p> <pre><code>fig4=plt.figure() LG=fig4.add_subplot(111) for val in np.linspace(-np.pi/a, 0, 1000): LG.scatter([val]*8, H(val, val , val, -15.2, -s*10.25, 19.60, -5.30)) plt.grid() plt.title(r"$L-\Gamma$") plt.xlabel(r"$k$ in high symmetry points") plt.xticks([-C*0.5, 0.], ["L", "$\Gamma$"]) plt.ylabel("energy/eV") plt.show() </code></pre> <p>I included the physics, so that physicians understand it easier. In case they are not many here:</p> <p>I have a function plot1 and plot2 &amp; I want to append plot2 horizontally in one graph with same y-axes but different x- axes. Like in the picture(from g-X is one function, from X to W another and so on).</p> <p>Edit2: The answer of TobyD &amp; pathoren made it possible to plot a function w/ several arguments next to each w/ free arguments. I think that my problem is in principle solveable by this, but since I don't have functions but a matrix and want to calculate eigenvalues and have more than one directional argument it's complicated. I manage to produce a plot I only want to cut horizontally together (but not like paint, but with one x-axes description).</p> <p>Edit3: Thank you pathoren &amp; TobyD for your help. The easiest way was just to change the argument x+something, x-something, now I have more than way, which can proof usefull eventually. </p> <p><a href="http://i.stack.imgur.com/KqMN9.png" rel="nofollow">final answer</a></p>
-1
2016-09-05T15:52:52Z
39,335,473
<p>Let me see if I'm understanding what you're after correctly.</p> <p>Try something like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec fig = plt.figure() gs = gridspec.GridSpec(1,n, width_ratios = [width_1,...,width_n]) axes = [plt.subplot(subplot) for subplot in gs] fig.subplots_adjust(wspace=0) </code></pre> <p>Where n is the number of differing argument sets you want to be plotting and width_n is the width of each in whatever units you choose based on your normalisation.</p> <p>The subplots_adjust sets the space between the subplots to 0. GridSpec gives you finer grained control over the sizes of each. The <code>sharey</code> flag doesnt work with gridspec so we have to fiddle with the y-ticks manually.</p> <p>You can then plot the function for each argument set, in an element of axes, with whatever ranges you want. Basically treat each element of axes as one of the graphs which you wish to concatonate together.</p> <p>Using the same example as @pathoren:</p> <pre><code>def f(x, a, b, c): return a*x**2 + b*x + c fig = plt.figure() gs = gridspec.GridSpec(1, 3, width_ratios = [3, 2, 1]) axes = [plt.subplot(subplot) for subplot in gs] fig.subplots_adjust(wspace=0) x = np.linspace(0, 10, 100) y = np.linspace(2, 5 ,100) z = np.linspace(0, 2*np.pi, 100) f1 = f(x, 1, 2, 3) f2 = f(y, 3, -2, 0) f3 = f(z, -1, 2, 1) axes[0].plot(x, f1, label='f1') axes[0].set_xticks([0, 10]) axes[0].set_xticklabels(["L", "X"]) axes[0].yaxis.tick_left() axes[1].plot(y, f2, label='f2') axes[1].set_xticks([5]) axes[1].set_xticklabels(["G"]) axes[1].yaxis.set_tick_params(size=0) plt.setp(axes[1].get_yticklabels(), visible=False) axes[2].plot(z, f3, label='f3') axes[2].set_xticks([2*np.pi]) axes[2].set_xticklabels(["Y"]) axes[2].yaxis.tick_right() axes[2].set_xlim([z[0],z[-1]]) plt.setp(axes[2].get_yticklabels(), visible=False) plt.show() </code></pre> <p>Note that the functions for changing subplot attributes like the xticks are slightly different. Using <code>axes[2].set_xlim</code> ensures the last graph cuts off nicely.</p> <p><a href="http://i.stack.imgur.com/nBtuA.png" rel="nofollow"><img src="http://i.stack.imgur.com/nBtuA.png" alt="Example Graph"></a></p>
0
2016-09-05T17:44:18Z
[ "python", "matplotlib", "plot", "physics", "axes" ]
Making queries ManyToMany relationships
39,334,071
<p>I have a model named <code>AffectedSegment</code> which is used for store a corporal segments selection.</p> <pre><code>class AffectedSegment(models.Model): SEGMENTO_ESCAPULA = 'Escápula' SEGMENTO_HOMBRO = 'Hombro' SEGMENTO_CODO = 'Codo' SEGMENTO_ANTEBRAZO = 'Antebrazo' SEGMENTO_CARPO_MUNECA = 'Carpo/Muñeca' SEGMENTO_MANO = 'Mano' SEGMENT_CHOICES = ( (SEGMENTO_ESCAPULA, u'Escápula'), (SEGMENTO_HOMBRO, u'Hombro'), (SEGMENTO_CODO, u'Codo'), (SEGMENTO_ANTEBRAZO, u'Antebrazo'), (SEGMENTO_CARPO_MUNECA, u'Carpo/Muñeca'), (SEGMENTO_MANO, u'Mano'), ) affected_segment = models.CharField( max_length=12, choices=SEGMENT_CHOICES, verbose_name='Affected Segment' ) def __str__(self): return "%s" % self.affected_segment </code></pre> <p>I have another model named <code>Movement</code>, which is used for store a movement asociated or related with the previous corporal segment entered. </p> <p>The idea is that one segment (<code>AffectedSegment</code> object) can have many movements, and one movement (<code>Movement</code> object) can be associated with one or many segments.</p> <pre><code>class Movement(models.Model): type = models.CharField( max_length=255, verbose_name='Movement type' ) corporal_segment_associated = models.ManyToManyField( AffectedSegment, blank=True, verbose_name='Affected segment associated') def __str__(self): return "%s" % self.type </code></pre> <p>This two models, I am referencing in this model</p> <pre><code>class RehabilitationSession(models.Model): affected_segment = models.ManyToManyField( AffectedSegment, verbose_name='Segmento afectado', #related_name='affectedsegment' ) movement = models.ManyToManyField( Movement, # Chained Model verbose_name='Movement', #related_name = 'movement' ) </code></pre> <p>My main doubt is How to can I lookup the content of <code>affected_segment</code> and <code>movement</code> fields from <code>RehabilitationSession</code> model in my html templates.</p> <p>I am trying pass these data of this way:</p> <p>My views.py file</p> <pre><code>class RehabilitationSessionList(ListView): queryset = RehabilitationSession.objects.all() context_object_name = 'rehabilitationsessions' template_name = 'finals_list.html' </code></pre> <p>And my finals_list.html template is:</p> <pre><code>&lt;thead&gt; &lt;tr&gt; &lt;th&gt;Affected Segment&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {% for a in rehabilitationsessions %} &lt;tr&gt; &lt;td&gt;{{ a.affected_segment }}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; {% endfor %} </code></pre> <p>But when I access to my template via url, I get this:</p> <p><a href="http://i.stack.imgur.com/4HHYH.png" rel="nofollow"><img src="http://i.stack.imgur.com/4HHYH.png" alt="enter image description here"></a></p> <p>Of course, the <code>RehabilitationSession</code> model does not have the <code>affected_segment</code> and <code>movement</code> fields explicitly declared, due to that the ManyToMany relationships create another intermediate models/tables of this way:</p> <p><a href="http://i.stack.imgur.com/qFuVz.png" rel="nofollow"><img src="http://i.stack.imgur.com/qFuVz.png" alt="enter image description here"></a></p> <p>Via Django Shell, I can make the queries, navigating through of some of this tables/models</p> <pre><code>In [21]: RehabilitationSession.objects.filter(movement__type='Extensión') Out[21]: &lt;QuerySet [&lt;RehabilitationSession: Andrea Vermaelen&gt;]&gt; In [24]: RehabilitationSession.objects.filter(affected_segment__affected_segment='Codo ...: ') Out[24]: &lt;QuerySet [&lt;RehabilitationSession: Andrea Vermaelen&gt;]&gt; </code></pre> <p>My question is how to can I make the queries in my views for the data appear in the templates, </p> <p>Is possible that my models are not defined correctly? ...</p> <p>I know that this should not be complex, but I would like receive some orientation about it for I retrieve the segments and movements of a person in a rehabilitation session.</p> <p>Any orientation is welcome</p> <p><strong>UPDATE</strong></p> <p>In relation to the support that @Daniel-Roseman gave me, I extract also the movement field for attach it in the table.</p> <pre><code>{% for a in rehabilitationsessions %} {% for r in a.affected_segment.all %} {% for l in a.movement.all %} &lt;tr&gt; &lt;td&gt;{{ a.id }}&lt;/td&gt; &lt;td&gt;{{ a.patient.full_name }}&lt;/td&gt; &lt;td&gt;{{ a.patient.user.birth_date }}&lt;/td&gt; &lt;td&gt;{{ a.patient.user.age }}&lt;/td&gt; &lt;td&gt;{{ a.patient.user.sex }}&lt;/td&gt; &lt;td&gt;{{ a.upper_extremity }} &lt;br/&gt;&lt;br/&gt; &lt;strong&gt;{{ a.pain_extremity }}&lt;/strong&gt; &lt;/td&gt; &lt;td&gt;{{ a.patient.dominant_superior_member }}&lt;/td&gt; &lt;td&gt;{{ r.get_affected_segment_display }}&lt;/td&gt; &lt;td&gt;{{ l }}&lt;/td&gt; &lt;td&gt; &lt;button type="button" class="btn btn-xs btn-info"&gt;&lt;a href="{% url 'rehabilitationsessions:detail' a.id %}"&gt;Ver&lt;/a&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="{% url 'rehabilitationsessions:edit' a.id %}"&gt;Editar&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; {% endfor %} {% endfor %} {% endfor %} </code></pre> <p>And the movement it's showed. Works. But when I edit the register for add some additional <code>movement</code> or additional <code>affected_segment</code>, the behavior is that is showed one new record of the this additional segment or movement, although it's not a new record in the database, is a new line of the same record ...</p> <p>I think that this happened due to my three for loops ... It's something like this <a href="https://cldup.com/JRKuSRFPuD.png" rel="nofollow">https://cldup.com/JRKuSRFPuD.png</a> </p>
0
2016-09-05T15:53:36Z
39,336,045
<p>As you've said, <code>affected_segment</code> is a many-to-many field. That means it refers to <em>many</em> segments (and the name seems wrong, it should be plural). So you can't just output it, you need to iterate through it:</p> <pre><code>{% for a in rehabilitationsessions %} {% for r in a.affected_segment.all %} {{ r.get_affected_segment_display }} {% endfor %} {% endfor %} </code></pre> <p>See that since the field you're interested in on AffectedSegment, itself called <code>affected_segment</code>, has choices assigned, you can use <code>get_affected_segment_display</code> to display the readable value of the choice.</p>
1
2016-09-05T18:35:56Z
[ "python", "django", "orm", "models" ]
Speech recognition streaming delay before start to recording on python
39,334,172
<p>I have a delay while trying to stream audio to speech recognition service.</p> <p>I have two functions that handles this task, the first one that using alsaaudio and "yield" to return the data to the calling function. and the second function that using requests that I passing to it the url the headers and the recording function.</p> <p>the problem that I have a delay from the moment that I call to the requests function and until it starts to record the audio about half a second</p> <p>here is a pseudo code:</p> <pre><code>def listen(): stream = audiostream() while user_speak: yield stream.read(chunksize) def stream_speech(): response = requests.post(url, data=listen(), headers, stream=true) if response.status_code == 200: print(response) </code></pre> <p>I think the problem is in the delay when the requests is opening the connection to the server and only then calls to the listen function.</p> <p>so I thought maybe to open a thread that will record the chunks into an queue and the main thread will call the requests function with the queue. but I don't know how to implement this, maybe someone here can help me out.</p>
0
2016-09-05T16:01:23Z
39,349,665
<p>Well, there are many lower-level APIs, including async ones like <a href="https://pymotw.com/2/asyncore/" rel="nofollow">asyncore</a> which allows you to interact without using threads at all.</p> <p>I would simply increase the buffer size in alsaaudio with <a href="https://larsimmisch.github.io/pyalsaaudio/libalsaaudio.html#alsaaudio.PCM.setperiodsize" rel="nofollow">setperiodsize</a> to something like 0.5 seconds and use bigger buffer. Then you can start recording first and then wait for the connection while alsa will prepare the first buffer.</p>
1
2016-09-06T13:00:55Z
[ "python", "linux", "multithreading", "speech-recognition" ]
De-Serializing msg_container objects returned from the telegram.org server
39,334,196
<p>I'm having trouble de-serializing a <code>msg_container</code> object. The issue seems to be my understanding of where the <code>flags</code> field is located in the <code>message</code> as it doesn't make sense to me. My assumptions below come from reading this page: <a href="https://core.telegram.org/mtproto/TL" rel="nofollow">https://core.telegram.org/mtproto/TL</a></p> <p>Here is what I am seeing, I'm hoping someone can clarify.</p> <p>A response from the telegram server looks like this:</p> <pre><code> ('server_answer: ', '\xdc\xf8\xf1s\x02\x00\x00\x00\x018\xcb\x8cCu\xcdW\x01\x00\x00\x00\x1c\x00\x00\x00\x08\t\xc2\x9e\x00t\xbe?Cu\xcdW\x82\x0e:\x11\xe0\xda\xed\x05\xd7\xbezI4\x05Tf\x01\xdc\xcb\x8cCu\xcdW\x02\x00\x00\x00\x14\x00\x00\x00Y\xb4\xd6b\x15\xc4\xb5\x1c\x01\x00\x00\x00\x00t\xbe?Cu\xcdW') 0 | DC F8 F1 73 02 00 00 00 8 | 01 38 CB 8C 43 75 CD 57 16 | 01 00 00 00 1C 00 00 00 24 | 08 09 C2 9E 00 74 BE 3F 32 | 43 75 CD 57 82 0E 3A 11 40 | E0 DA ED 05 D7 BE 7A 49 48 | 34 05 54 66 01 DC CB 8C 56 | 43 75 CD 57 02 00 00 00 64 | 14 00 00 00 59 B4 D6 62 72 | 15 C4 B5 1C 01 00 00 00 80 | 00 74 BE 3F 43 75 CD 57 </code></pre> <p>Which indicates a <code>MessageContainer</code> object, which looks like this:</p> <pre><code>msg_container#73f1f8dc messages:vector&lt;message&gt; = MessageContainer; </code></pre> <p>(Note: 73f1f8dc is the first four bytes returned, in little-endian order)</p> <p>Since a <code>msg_container</code> is a <code>vector</code> of <code>messages</code> the next integer is the <code>message</code> count, which is <code>00 00 00 02</code>, so there are two messages in this vector.</p> <p>A <code>message</code> looks like this:</p> <pre><code>message#c09be45f flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true id:int from_id:flags.8?int to_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to_msg_id:flags.3?int date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector&lt;MessageEntity&gt; views:flags.10?int edit_date:flags.15?int = Message; messageService#9e19a1f6 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true id:int from_id:flags.8?int to_id:Peer reply_to_msg_id:flags.3?int date:int action:MessageAction = Message; </code></pre> <p>So I am assuming the next four bytes will be the first parameter in the first message, which is the <code>flags</code> field. But the value of that four bytes is <code>8c cb 38 01</code> which is 2362128385L as an unsigned integer, which is suspiciously large for a simple bit mask. Plus, if I use this value to de-serialize the optional parameters from the rest of the byte stream they don't make sense and eventually fail with a type mismatch. I've tried the <code>flags</code> field as a signed integer as well with similar results.</p> <p>What is incorrect about my understanding of how the telegram server responds with msg_container objects?</p>
1
2016-09-05T16:03:09Z
39,335,056
<p>Here is a simple approach to use in handling messages packed in a container:</p> <pre><code>Container_type_header Content_count [messages] </code></pre> <p>Each message is packed like so:</p> <pre><code>msgs_id seq_no mgs_len msg_body </code></pre> <p>given your sample data:</p> <pre><code>DCF8F173 --&gt; container_type_header 02000000 --&gt; message_count_in_container 0138CB8C4375CD57 --&gt; msg_id of first message 01000000 --&gt; seq_no of first message 1C000000 --&gt; length of first message; 1C == 28 bytes 0809C29E0074BE3F4375CD57820E3A11E0DAED05D7BE7A4934055466 --&gt; 28 byte msg_body 01DCCB8C4375CD57 --&gt; msg_id of second message 02000000 --&gt; seq_number of second message 14000000 --&gt; lenght of second message; 14 == 20 bytes 59B4D66215C4B51C010000000074BE3F4375CD57 --&gt; 20 byte msg_body </code></pre> <p>when decoded first message gives:</p> <pre><code>0809C29E0074BE3F4375CD57820E3A11E0DAED05D7BE7A4934055466 New_Session_Created{first_msg_id: 6326841983218119680, server_salt: 7373524212041563863, unique_id: 427238195566612098} </code></pre> <p>when decoded second message gives:</p> <pre><code>0x59B4D66215C4B51C010000000074BE3F4375CD57 Msgs_Ack{msg_ids: [6326841983218119680]} </code></pre>
1
2016-09-05T17:06:40Z
[ "python", "api", "telegram" ]
Use else in dict comprehension
39,334,201
<p>From two dictionaries:</p> <pre><code>d1 = {a:a for a in 'abcdefg'} d2 = {n:n for n in range(10)} </code></pre> <p>How can I create a third one like:</p> <pre><code>new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' } </code></pre> <p>It's throwing a syntax Error, but with list comprehension seems to be fine:</p> <pre><code>[a if a else 2 for a in [0,1,0,3]] out[]: [2, 1, 2, 3] </code></pre> <p>Moreover, why this works:</p> <pre><code>{k:d1[k] for k in 'abc123' if k in d1.keys() } </code></pre> <p>and this doesn't:</p> <pre><code>{k:d1[k] if k in d1.keys() for k in 'abc123' } </code></pre>
-1
2016-09-05T16:03:23Z
39,334,330
<p>You can't use the <em>key-value</em> pair in the <code>else</code> part of ternary conditional like so. </p> <p>Do this instead:</p> <pre><code>new_dict = {k: d1[k] if k in d1 else d2[int(k)] for k in 'abc123'} # ^^&lt;- make value d2[int(k)] on else print(new_dict) #{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3} </code></pre> <p>Note that <code>if k in d1</code> checks if <code>k</code> is a key in the dictionary <code>d1</code>. No need to call the <code>keys</code> method.</p>
1
2016-09-05T16:12:34Z
[ "python", "dictionary", "list-comprehension" ]
Use else in dict comprehension
39,334,201
<p>From two dictionaries:</p> <pre><code>d1 = {a:a for a in 'abcdefg'} d2 = {n:n for n in range(10)} </code></pre> <p>How can I create a third one like:</p> <pre><code>new_dict = {k:d1[k] if k in d1.keys() else k:d2[k] for k in 'abc123' } </code></pre> <p>It's throwing a syntax Error, but with list comprehension seems to be fine:</p> <pre><code>[a if a else 2 for a in [0,1,0,3]] out[]: [2, 1, 2, 3] </code></pre> <p>Moreover, why this works:</p> <pre><code>{k:d1[k] for k in 'abc123' if k in d1.keys() } </code></pre> <p>and this doesn't:</p> <pre><code>{k:d1[k] if k in d1.keys() for k in 'abc123' } </code></pre>
-1
2016-09-05T16:03:23Z
39,335,377
<p>As described, it seems like both your <code>d1</code> and <code>d2</code> are artifacts of how you envision solving the problem and aren't essential. How about simply:</p> <pre><code>&gt;&gt;&gt; dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'} &gt;&gt;&gt; dictionary {'b': 'b', '3': 3, '2': 2, '1': 1, 'a': 'a', 'c': 'c'} &gt;&gt;&gt; </code></pre> <p>Or is there more to the problem you're trying to solve?</p>
1
2016-09-05T17:35:35Z
[ "python", "dictionary", "list-comprehension" ]
Python_Flask_Webapp Select menu doesn't work
39,334,235
<p>I'm learning Flask Web Development this book, I have a function on my page that in the "account" there is a select menu , I can choose the function inside , i.e. change password , or log out. But it's strange that the select menu doesn't work in the index page, no response when I click the "account" , in others page , for example , below /user/AllenXu page , it works normally .</p> <pre><code>http://localhost:5000/user/AllenXu </code></pre> <p><a href="http://i.stack.imgur.com/tvSay.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/tvSay.jpg" alt="other pages"></a> </p> <p><strong>But in my index page, u can see it doesn't work.</strong></p> <p><a href="http://i.stack.imgur.com/LmyCm.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/LmyCm.jpg" alt="index page"></a></p> <p>What is confusing me is that the select menu code was setting in the base.html which is extends from <strong>bootstrap</strong> template , and other pages extends from the base.html , so actually it should work in every page which extends from base.html.</p> <p>And actually it does work in <code>http://localhost:5000/user/AllenXu</code></p> <p>But why it does not work in index page ?</p> <p>Below is my code information </p> <p><strong>base.html</strong></p> <pre><code>{% extends "bootstrap/base.html" %} {% block title %}Flasky{% endblock %} {% block head %} {{ super() }} &lt;link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"&gt; &lt;link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"&gt; &lt;link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}"&gt; {% endblock %} {% block navbar %} &lt;div class="navbar navbar-inverse" role="navigation"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle"data-toggle="collapse" data-target=".navbar-collapse"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="{{url_for('main.index')}}"&gt;Flasky&lt;/a&gt; &lt;/div&gt; &lt;div class="navbar-collapse collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="{{url_for('main.index')}}"&gt;Home&lt;/a&gt;&lt;/li&gt; {% if current_user.is_authenticated %} &lt;li&gt;&lt;a href="{{ url_for('main.user', username=current_user.username) }}"&gt;Profile&lt;/a&gt; &lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; {% if current_user.is_authenticated %} &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt; &lt;img src="{{ current_user.gravatar(size=18) }}"&gt; Account &lt;b class="caret"&gt;&lt;/b&gt; &lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="{{ url_for('auth.change_password') }}"&gt;Change Password&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ url_for('auth.change_email_request') }}"&gt;Change Email&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ url_for('auth.logout') }}"&gt;Log Out&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="{{ url_for('auth.login') }}"&gt;Log In&lt;/a&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {%endblock%} {%block content%} &lt;div class="container"&gt; {% for message in get_flashed_messages() %} &lt;div class="alert alert-warning"&gt; &lt;button type="button" class="close" data-dismiss="alert"&gt;&amp;times;&lt;/button&gt; {{ message }} &lt;/div&gt; {% endfor %} {% block page_content %}{% endblock %} &lt;/div&gt; {%endblock%} </code></pre> <p><strong>My views.py</strong></p> <pre><code>from datetime import datetime from flask import render_template,session,redirect,url_for,flash from . import main from .forms import NameForm,EditProfileForm,EditProfileAdminForm,PostForm from .. import db from ..models import User,Role,Permission,Post from flask.ext.login import login_required,current_user from ..decorators import admin_required @main.route('/',methods=['GET','POST']) def index(): form = PostForm() if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit(): post = Post(body = form.body.data,author = current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) posts = Post.query.order_by(Post.timestamp.desc()).all() return render_template('index.html',form = form, posts = posts) @main.route('/user/&lt;username&gt;') def user(username): user = User.query.filter_by(username = username).first() if user is None: abort (404) return render_template('user.html',user = user) enter code here </code></pre> <p><strong>my index.html file</strong></p> <pre><code>{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {% block page_content %} {% block scripts %} {{ super() }} {{ moment.include_moment() }} {% endblock %} &lt;div class="page-header"&gt; &lt;h1&gt;Hello, {% if current_user.is_authenticated%} {{ current_user.username }} {% else %} Stranger! {% endif %} &lt;/h1&gt; &lt;/div&gt; &lt;div&gt; {% if current_user.can(Permission.WRITE_ARTICLES) %} {{ wtf.quick_form(form) }} {% endif %} &lt;/div&gt; &lt;ul class = "posts"&gt; {% for post in posts %} &lt;li class = "post"&gt; &lt;div class="profile-thumbnail"&gt; &lt;a href = "{{ url_for('.user',username = post.author.username) }}"&gt; &lt;img class = "img-rounded profile-thumbnail" src = "{{ post.author.gravatar(size = 40) }}"&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="post-date"&gt;{{ moment(post.timestamp).fromNow() }}&lt;/div&gt; &lt;div class="post-author"&gt; &lt;a href = "{{ url_for('.user',username = post.author.username) }}"&gt; {{ post.author.username }} &lt;/a&gt; &lt;/div&gt; &lt;div class = "post-body"&gt;{{ post.body }}&lt;/div&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endblock %} </code></pre> <p>Thanks in advance for helping me !! If any more information needed , please let me know</p>
0
2016-09-05T16:06:14Z
39,375,088
<p>Finally , I found the problem which caused this...</p> <p>because ...in my index.html , I insert the {%block scripts%} inside the {%block page_content%}....</p> <p>the "block" should be seprarte...if block A is inside block B, the A is useless</p> <pre><code>{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {% block page_content %} {% block scripts %} {{ super() }} {{ moment.include_moment() }} {% endblock %} &lt;div class="page-header"&gt; &lt;h1&gt;Hello, {% if current_user.is_authenticated%} {{ current_user.username }} {% else %} Stranger! {% endif %} &lt;/h1&gt; &lt;/div&gt; </code></pre>
0
2016-09-07T16:26:50Z
[ "javascript", "jquery", "python", "html", "flask" ]
Capitalizing hyphenated name
39,334,291
<p>I have a script looking like this:</p> <pre><code>firstn = input('Please enter your first name: ') lastn = input('Please enter Your last name: ') print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn)+ '!') </code></pre> <p>It will work nicely with simple names like jack black or morgan meeman but when I input hyphenated name like <code>jordan-bellfort image</code> then I'd expect <code>"Jordan-Bellfort Image"</code> but I receive <code>"Jordan-bellfort Image"</code>.</p> <p>How can I get python to capitalize the character right after hyphen?</p>
2
2016-09-05T16:09:40Z
39,334,331
<p>You can use <a href="https://docs.python.org/2/library/stdtypes.html#str.title" rel="nofollow">title()</a>:</p> <pre><code>print('Good day,', firstn.title(), lastn.title(), '!') </code></pre> <p>Example from the console:</p> <pre><code>&gt;&gt;&gt; 'jordan-bellfort image'.title() 'Jordan-Bellfort Image' </code></pre>
6
2016-09-05T16:12:45Z
[ "python", "capitalize" ]
Capitalizing hyphenated name
39,334,291
<p>I have a script looking like this:</p> <pre><code>firstn = input('Please enter your first name: ') lastn = input('Please enter Your last name: ') print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn)+ '!') </code></pre> <p>It will work nicely with simple names like jack black or morgan meeman but when I input hyphenated name like <code>jordan-bellfort image</code> then I'd expect <code>"Jordan-Bellfort Image"</code> but I receive <code>"Jordan-bellfort Image"</code>.</p> <p>How can I get python to capitalize the character right after hyphen?</p>
2
2016-09-05T16:09:40Z
39,334,332
<p>Use <a href="https://docs.python.org/2/library/string.html" rel="nofollow"><code>string.capwords()</code></a>instead</p> <blockquote> <p>Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join()</p> </blockquote> <pre><code>import string string.capwords(firstn, "-") </code></pre>
1
2016-09-05T16:12:49Z
[ "python", "capitalize" ]
Capitalizing hyphenated name
39,334,291
<p>I have a script looking like this:</p> <pre><code>firstn = input('Please enter your first name: ') lastn = input('Please enter Your last name: ') print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn)+ '!') </code></pre> <p>It will work nicely with simple names like jack black or morgan meeman but when I input hyphenated name like <code>jordan-bellfort image</code> then I'd expect <code>"Jordan-Bellfort Image"</code> but I receive <code>"Jordan-bellfort Image"</code>.</p> <p>How can I get python to capitalize the character right after hyphen?</p>
2
2016-09-05T16:09:40Z
39,334,405
<p>I'd suggest just using <a href="https://docs.python.org/2/library/stdtypes.html#str.title" rel="nofollow">str.title</a>, here's a working example comparing your version and the one using str.title method:</p> <pre><code>import string tests = [ ["jack", "black"], ["morgan", "meeman"], ["jordan-bellfort", "image"] ] for t in tests: firstn, lastn = t print('Good day, ' + str.capitalize(firstn) + ' ' + str.capitalize(lastn) + '!') print('Good day, ' + firstn.title() + ' ' + lastn.title() + '!') print('-'*80) </code></pre> <p>Resulting into this:</p> <pre><code>Good day, Jack Black! Good day, Jack Black! -------------------------------------------------------------------------------- Good day, Morgan Meeman! Good day, Morgan Meeman! -------------------------------------------------------------------------------- Good day, Jordan-bellfort Image! Good day, Jordan-Bellfort Image! -------------------------------------------------------------------------------- </code></pre>
1
2016-09-05T16:17:41Z
[ "python", "capitalize" ]
Convert Pandas tseries object to a DataFrame
39,334,343
<p>I wish to convert the following <code>&lt;'pandas.tseries.resample.DatetimeIndexResampler'&gt;</code> type object into a pandas DataFrame object (<code>&lt;'pandas.core.frame.DataFrame'&gt;</code>). However I cannot find the relevant function in the pandas documentation to allow me to do this. </p> <p>The data takes the following form:</p> <pre><code> M30 Date 2016-02-29 -61.187699 2016-03-31 -60.869565 2016-04-30 -61.717922 2016-05-31 -61.823966 2016-06-30 -62.142100 ... </code></pre> <p>Can anyone provide an alternative solution?</p>
2
2016-09-05T16:13:22Z
39,334,363
<p>You need some aggregate function like <code>sum</code> or <code>mean</code>.</p> <p>Sample with your data:</p> <pre><code>print (df) M30 Date 2016-02-29 -61.187699 2016-03-31 -60.869565 2016-04-30 -61.717922 2016-05-31 -61.823966 2016-06-30 -62.142100 #resample by 2 months r = df.resample('2M') print (r) DatetimeIndexResampler [freq=&lt;2 * MonthEnds&gt;, axis=0, closed=right, label=right, convention=start, base=0] </code></pre> <pre><code>#aggregate sum print (r.sum()) M30 Date 2016-02-29 -61.187699 2016-04-30 -122.587487 2016-06-30 -123.966066 #aggregate mean print (r.mean()) M30 Date 2016-02-29 -61.187699 2016-04-30 -61.293743 2016-06-30 -61.983033 #aggregate first print (r.first()) M30 Date 2016-02-29 -61.187699 2016-04-30 -60.869565 2016-06-30 -61.823966 </code></pre>
3
2016-09-05T16:14:43Z
[ "python", "pandas", "dataframe", "time-series", "resampling" ]
Possible to pass a function into a object's method as an argument, which can refer to that object?
39,334,408
<pre><code>def my_func(): stuff return something my_object.my_method(my_func) </code></pre> <p>I want my_func to be able to refer to <code>my_object</code>. Essentially like deferred <code>self</code>, which means "whatever object I am in, refer to that"</p>
1
2016-09-05T16:17:56Z
39,334,573
<p>You could use the <strong><a href="https://docs.python.org/2/library/inspect.html" rel="nofollow"><code>inspect</code></a></strong> module</p> <pre><code>import inspect def my_func(): stuff my_object = inspect.stack()[1][0].f_locals["self"] return something </code></pre> <p>However, I guess a simpler approach would be to pass the instance as argument, such as </p> <pre><code>def my_func(): stuff return something my_object.my_method(my_func, caller=my_object) </code></pre>
1
2016-09-05T16:29:58Z
[ "python", "python-2.7", "functional-programming", "self", "function-object" ]
Possible to pass a function into a object's method as an argument, which can refer to that object?
39,334,408
<pre><code>def my_func(): stuff return something my_object.my_method(my_func) </code></pre> <p>I want my_func to be able to refer to <code>my_object</code>. Essentially like deferred <code>self</code>, which means "whatever object I am in, refer to that"</p>
1
2016-09-05T16:17:56Z
39,369,488
<p>You want to make a <a href="http://code-maven.com/function-or-callback-in-python" rel="nofollow">callback</a>. </p> <p>And <a href="http://stackoverflow.com/questions/4689984/implementing-a-callback-in-python-passing-a-callable-reference-to-the-current">here</a> is a usage of callback in a design pattern. </p>
0
2016-09-07T12:05:07Z
[ "python", "python-2.7", "functional-programming", "self", "function-object" ]
WxPython zooming technique
39,334,441
<p>I am developing a wxpython project where I am drawing a diagram on to a panel that I need to be able to zoom in/out to this diagram(a directed acyclic graph in my case). I will achieve this by mouse scroll when the cursor is on the panel, however that is not a part of my question. I need an advice from an experienced person about the method I am using for zooming. So far I thought as doing,</p> <ul> <li>There are lines, rectangles and texts inside rectangles within this diagram. So maybe I could increase/decrease their length/size with the chosen mouse event. But it is hard to keep it balanced because rectangles are connected with lines their angles should not change, and texts inside the rectanges should stay in the middle of them.</li> <li>Other method I thought of doing is to search for a built-in zoom method. Which I heard about something like <code>Scale</code>. However I have some questions about this method. Will this work on vector drawings(like mine) rather than images. And will it be scaling only the panel I chose and not the whole screen ? After I hear your advice about this, I will look deeper into this, but now I am a bit clueless.</li> </ul> <p>Sorry if my question is too <em>theoretical</em>. But I felt I needed help in the area. Thanks in advance.</p> <p><strong>Note:</strong> Zooming not necessarily applied by scrolling.</p> <p><strong>Note2:</strong> My research also led me to <code>FloatCanvas</code>. Is this suitable to my needs ?</p>
0
2016-09-05T16:20:57Z
39,335,812
<p>Yes, from your description <code>FloatCanvas</code> would certainly meet your needs. </p> <p>Another possibility to consider would be the <code>wx.GraphicsContext</code> and related classes. It is vector-based (instead of raster) and supports the use of a transformation matrix which would make zooming, rotating, etc. very easy. However, the actual drawing and management of the shapes and such would probably require more work for you than using <code>FloatCanvas</code>.</p>
0
2016-09-05T18:13:08Z
[ "python", "wxpython", "zooming" ]
Output dictionary data dynamically from a python for loop
39,334,464
<p>here, I am trying to spell check a txt file. first half of my code outputs original (var word) and corrected, if any, (var spell(word)). my replacement code uses a data structure like <code>{'zero':'0', 'temp':'bob', 'garbage':'nothing', 'garnvsh': 'garnish'}</code>. Now I would like to produce the same data structure from the loop dynamically. Can you, please, help me figure it out how to output similar data structure with <code>var word</code> and <code>var spell(word)</code> with first half of the code?</p> <pre><code>import os, os.path from textblob import TextBlob from autocorrect import spell import fileinput import json data = [] with open("input.txt", "r") as my_file: for line in my_file.readlines(): zen = TextBlob(line) for word in zen.words: word, spell(word) replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing', 'garnvsh': 'garnish'} with open('../input.txt') as infile, open('../output.txt', 'w') as outfile: for line in infile: for src, target in replacements.iteritems(): line = line.replace(src, target) outfile.write(line) </code></pre>
0
2016-09-05T16:22:11Z
39,334,526
<p>I suppose you want to <a href="http://stackoverflow.com/a/14507637/1040597">create dictionary</a> which its keys are <code>word</code> and values are <code>spell(word)</code>.</p> <pre><code>my_dict = { word: spell(word) for word in zen.words } </code></pre>
1
2016-09-05T16:26:40Z
[ "python" ]
Find all substrings of a really long string - Memory error
39,334,480
<p>I was solving a problem in hackerrank and it required me to create a list that can store millions of values.<br> And when I created a list in the normal way, but it is giving me "Memory Error" </p> <p><a href="http://stackoverflow.com/questions/4800858/filtering-iterating-thru-very-large-lists-in-python">I have read this question and it didn't help</a><br> So, please, don't mark this question as a duplicate</p> <p>Here is the code: </p> <pre><code>def find_all_substrings(string): list3=[] length=len(string) list1=[] for i in range(length): for j in range(i,length): list1.append(string[i:j+1]) for x in range(len(list1)): if (list1[x] not in list3): list3.append(list1[x]) return list3 S=str(input()) list1=(find_all_substrings(S)) </code></pre> <p>This is the error I get: </p> <pre><code>Traceback (most recent call last): File "solution.py", line 36, in &lt;module&gt; File "solution.py", line 7, in find_all_substrings MemoryError </code></pre> <p>When the test case input is: </p> <blockquote> <p>NANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANAN</p> </blockquote>
1
2016-09-05T16:23:02Z
39,334,627
<p>As far as I can tell, <code>list3</code> is completely unnecessary. You are likely running out of memory because if all elements in the first list are unique, you've doubled the required storage space to solve the problem. </p> <p>Option 1) You can check if the substring is already in the list in the first loop</p> <p>Option 2) if you want to prevent duplicates, don't use a list, use a <code>set()</code>, and just add to it, no need to check if something exists already. Then convert that back to a <code>list()</code> when you return. </p>
1
2016-09-05T16:33:43Z
[ "python", "python-3.x" ]
string(array) vs string(list) in python
39,334,498
<p>I was constructing a database for a deep learning algorithm. The points I'm interested in are these:</p> <pre><code>with open(fname, 'a+') as f: f.write("intens: " + str(mean_intensity_this_object) + "," + "\n") f.write("distances: " + str(dists_this_object) + "," + "\n") </code></pre> <p>Where <code>mean_intensity_this_object</code> is a list and <code>dists_this_object</code> is a <code>numpy.array</code>, something I didn't pay enough attention to to begin with. After I opened the file, I found out that the second variable, <code>distances</code>, looks very different to <code>intens</code>: The former is </p> <pre><code>distances: [430.17802963 315.2197058 380.33997833 387.46190951 41.93648858 221.5210474 488.99452579], </code></pre> <p>and the latter </p> <pre><code>intens: [0.15381262,..., 0.13638344], </code></pre> <p>The important bit is that the latter is a standard list, while the former is very hard to read: multiple lines without delimiters and unclear rules for starting a new line. Essentially as a result I had to rerun the whole tracking algorithm and change <code>str(dists_this_object)</code> to <code>str(dists_this_object.tolist())</code> which increased the file size. </p> <p>So, my question is: why does this happen? Is it possible to save <code>np.array</code> objects in a more readable format, like lists? </p>
-1
2016-09-05T16:24:04Z
39,336,261
<p>In an interactive Python session:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.arange(10)/.33 # make an array of floats &gt;&gt;&gt; x array([ 0. , 3.03030303, 6.06060606, 9.09090909, 12.12121212, 15.15151515, 18.18181818, 21.21212121, 24.24242424, 27.27272727]) &gt;&gt;&gt; print(x) [ 0. 3.03030303 6.06060606 9.09090909 12.12121212 15.15151515 18.18181818 21.21212121 24.24242424 27.27272727] &gt;&gt;&gt; print(x.tolist()) [0.0, 3.0303030303030303, 6.0606060606060606, 9.09090909090909, 12.121212121212121, 15.15151515151515, 18.18181818181818, 21.21212121212121, 24.242424242424242, 27.27272727272727] </code></pre> <p>The standard display for a list is with <code>[]</code> and <code>,</code>. The display for an array is without <code>,</code>. If there are over 1000 items, the array display employs an ellipsis</p> <pre><code>&gt;&gt;&gt; print(x) [ 0. 3.03030303 6.06060606 ..., 3024.24242424 3027.27272727 3030.3030303 ] </code></pre> <p>while the list display continues to show every value.</p> <p>In this line, did you add the <code>...</code>, or is that part of the print? </p> <pre><code>intens: [0.15381262,..., 0.13638344], </code></pre> <p>Or doing the same with a file write:</p> <pre><code>In [299]: with open('test.txt', 'w') as f: ...: f.write('array:'+str(x)+'\n') ...: f.write('list:'+str(x.tolist())+'\n') In [300]: cat test.txt array:[ 0. 3.33333333 6.66666667 10. 13.33333333 16.66666667 20. 23.33333333 26.66666667 30. ] list:[0.0, 3.3333333333333335, 6.666666666666667, 10.0, 13.333333333333334, 16.666666666666668, 20.0, 23.333333333333336, 26.666666666666668, 30.0] </code></pre> <p><code>np.savetxt</code> gives more control over the formatting of an array, for example:</p> <pre><code>In [312]: np.savetxt('test.txt',[x], fmt='%10.6f',delimiter=',') In [313]: cat test.txt 0.000000, 3.333333, 6.666667, 10.000000, 13.333333, 16.666667, 20.000000, 23.333333, 26.666667, 30.000000 </code></pre> <p>The default array print is aimed mainly at interactive work, where you want to see enough of the values to see whether they are right or not, but you don't intend to reload them. The <code>savetxt/loadtxt</code> pair are better for that.</p> <p>The <code>savetxt</code> does, roughly:</p> <pre><code>for row in x: f.write(fmt%tuple(row)) </code></pre> <p>where <code>fmt</code> is constructed from your input paramater and the number of items in the <code>row</code>, e.g. <code>', '.join(['%10.6f']*10)+'\n'</code></p> <pre><code>In [320]: print('[%s]'%', '.join(['%10.6f']*10)%tuple(x)) [ 0.000000, 3.333333, 6.666667, 10.000000, 13.333333, 16.666667, 20.000000, 23.333333, 26.666667, 30.000000] </code></pre>
0
2016-09-05T18:55:11Z
[ "python", "arrays", "string", "list", "numpy" ]
string(array) vs string(list) in python
39,334,498
<p>I was constructing a database for a deep learning algorithm. The points I'm interested in are these:</p> <pre><code>with open(fname, 'a+') as f: f.write("intens: " + str(mean_intensity_this_object) + "," + "\n") f.write("distances: " + str(dists_this_object) + "," + "\n") </code></pre> <p>Where <code>mean_intensity_this_object</code> is a list and <code>dists_this_object</code> is a <code>numpy.array</code>, something I didn't pay enough attention to to begin with. After I opened the file, I found out that the second variable, <code>distances</code>, looks very different to <code>intens</code>: The former is </p> <pre><code>distances: [430.17802963 315.2197058 380.33997833 387.46190951 41.93648858 221.5210474 488.99452579], </code></pre> <p>and the latter </p> <pre><code>intens: [0.15381262,..., 0.13638344], </code></pre> <p>The important bit is that the latter is a standard list, while the former is very hard to read: multiple lines without delimiters and unclear rules for starting a new line. Essentially as a result I had to rerun the whole tracking algorithm and change <code>str(dists_this_object)</code> to <code>str(dists_this_object.tolist())</code> which increased the file size. </p> <p>So, my question is: why does this happen? Is it possible to save <code>np.array</code> objects in a more readable format, like lists? </p>
-1
2016-09-05T16:24:04Z
39,352,837
<p>Actually python converts both in the same way: <code>str(object)</code> calls <code>object.__str__()</code> or <code>object.__repr__()</code> if the former does not exist. From that point it is the responsibility of <code>object</code> to provide its string representation.</p> <p>Python lists and numpy arrays are different objects, designed and implemented by different people to serve different needs so it is to be expected that their <code>__str__</code> and <code>__repr__</code> methods do not behave the same.</p>
0
2016-09-06T15:34:54Z
[ "python", "arrays", "string", "list", "numpy" ]
Python && And Conditional Not Working
39,334,518
<p>I'm looking to extract lines of a CSV file that meet BOTH conditions.</p> <p>For example, I want to extract a line which features a certain unique code AND a specific date.</p> <p>Currently, my code is only extracting lines which meet ONE of the conditions:</p> <p>for line in log:</p> <pre><code>with open("log.csv", 'a') as csvfile: if ("code123" and "29/07/2016") in line: print(line) </code></pre> <p>I've also tried</p> <pre><code>with open("log.csv", 'a') as csvfile: if ("code123") and ("29/07/2016 ") in line: print(line) </code></pre> <p>But it seems extract lines that match that date but not also the unique code.</p> <p>The format of the log file is a bit like this:</p> <p>code123, 1001, 29/07/2016 14:01, 100</p> <p>I've tried the code with and without a space after the date:</p> <pre><code> if ("code123") and ("29/07/2016") in line: </code></pre> <p>and</p> <pre><code> if ("code123") and ("29/07/2016 ") in line: </code></pre> <p>Incase the fact that there is a time in the same cell as the date is a problem.</p> <p>But it just seems to extract lines that only match the date (and print any unique code that has a reading from the date, rather than the specified one).</p> <p>Can anybody help? </p> <p>The reason I am trying to do this is so I can separate a log file into separate files based on dates and unique ID's. So I want all the readings from a certain date for a certain key to be in one file.</p>
1
2016-09-05T16:25:43Z
39,334,547
<p>try</p> <pre><code>if "code123" in line and "29/07/2016" in line: </code></pre> <p>Since <code>and</code> returns <code>False</code> or the last operand, ie.</p> <pre><code>x and y == y # iff bool(x) is True and bool(y) is True </code></pre> <p>this part</p> <pre><code>("code123" and "29/07/2016") </code></pre> <p>always evaluates to "29/07/2016" and you're left with </p> <pre><code>if "29/07/2016" in line: </code></pre> <p>The reason </p> <pre><code>a and b in c == (a and b) in c </code></pre> <p>and not <code>(a) and (b in c)</code>, is due to the operator precedence rules: <a href="http://www.tutorialspoint.com/python/operators_precedence_example.htm" rel="nofollow">http://www.tutorialspoint.com/python/operators_precedence_example.htm</a></p> <p>The precedence rules are also responsible for</p> <pre><code>a in c and b in c == (a in c) and (b in c) </code></pre> <p>since <code>in</code> has higher precedence than <code>and</code>. It might be better to add parenthesis for clarity in this case anyway though.</p>
0
2016-09-05T16:28:07Z
[ "python", "conditional", "extraction", "conditional-operator", "data-extraction" ]
Python Pandas read_excel doesn't recognize null cell
39,334,543
<p>My excel sheet:</p> <pre><code> A B 1 first second 2 3 4 x y 5 z j </code></pre> <p>Python code:</p> <pre><code>df = pd.read_excel (filename, parse_cols=1) </code></pre> <p>return a correct output:</p> <pre><code> first second 0 NaN NaN 1 NaN NaN 2 x y 3 z j </code></pre> <p>If i want work only with second column</p> <pre><code>df = pd.read_excel (filename, parse_cols=[1]) </code></pre> <p>return:</p> <pre><code> second 0 y 1 j </code></pre> <p>I'd have information about empty excel rows (NaN in my df) even if I work only with a specific column. If output loose NaN information it's not ok, for example, for skiprows paramater, etc</p> <p>Thanks</p>
3
2016-09-05T16:27:47Z
39,334,616
<p>For me works parameter <code>skip_blank_lines=False</code>:</p> <pre><code>df = pd.read_excel ('test.xlsx', parse_cols=1, skip_blank_lines=False) print (df) A B 0 first second 1 NaN NaN 2 NaN NaN 3 x y 4 z j </code></pre> <p>Or if need omit first row:</p> <pre><code>df = pd.read_excel ('test.xlsx', parse_cols=1, skiprows=1, skip_blank_lines=False) print (df) first second 0 NaN NaN 1 NaN NaN 2 x y 3 z j </code></pre>
4
2016-09-05T16:33:03Z
[ "python", "excel", "pandas", null ]
Pass Python object directly to C++ program without using subprocess
39,334,586
<p>I have a C++ program that, through the terminal, takes a text file as input and produces another text file. I'm executing this program from a Python script which first produces said text string, stores it to a file, runs the C++ program as a subprocess with the created file as input and parses the output text file back into a Python object.</p> <p>Is it possible to do this without using a subprocess call? In other words: is it possible to avoid the reading and writing and just run the C++ program inside the Python environment with the text-string as input and then capture the output, again inside the Python environment?</p> <p>For code I refer to the function <code>community_detection_multiplex</code> in <a href="https://github.com/ulfaslak/InfomapSensibleDTU/blob/master/preproc.ipynb" rel="nofollow">this IPython notebook</a>.</p>
0
2016-09-05T16:30:40Z
39,334,642
<p>You can use <a href="https://docs.python.org/3.5/library/ctypes.html" rel="nofollow">ctypes</a>.<br> It requires the C++ function to be wrapped with <code>extern "c"</code> and compiled as C code.</p> <p>Say your C++ function looks like that:</p> <pre><code>char* changeString(char* someString) { // do something with your string return someString; } </code></pre> <p>You can call it from python like that:</p> <pre><code>import ctypes as ct yourString = "somestring" yourDLL = ct.CDLL("path/to/dll") # assign the dll to a variable cppFunc = yourDLL.changeString # assign the cpp func to a variable cppFunc.restype = ct.c_char_p # set the return type to a string returnedString = cppfunc(yourString.encode('ascii')).decode() </code></pre> <p>Now <code>returnedString</code> will have the processed string. </p>
2
2016-09-05T16:34:23Z
[ "python", "c++" ]
Why is this Django URL resolution not working
39,334,609
<p>I have the following Django url configuration in /urls.py file </p> <pre><code>from django.conf.urls import url from django.conf.urls import include, url from django.contrib import admin import core import core.views as coreviews urlpatterns = [ #url(r'^admin/', admin.site.urls), #url(r'^create/$', coreviews.handleFile), #Uncommenting this works url(r'^create/$', include('core.urls')), #This doesn't work url(r'^$', include('core.urls')),#Make msg app the the default one #url(r'^upload/', include('core.urls')), ] </code></pre> <p>My core/urls.py file is defined as follows</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin import core.views as coreviews from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'my$', coreviews.handleFile), url(r'^$', coreviews.index), ] </code></pre> <p>Finally, core/views.py file is defined as follows</p> <pre><code>def index(request): return render_to_response('AudioRecorder/index.html', context_instance=RequestContext(request)) def handleFile(request): return render_to_response('AudioRecorder/index.html', context_instance=RequestContext(request)) </code></pre> <p>show_urls output is as follows</p> <pre><code>/ core.views.index /create/ core.views.index /create/my core.views.handleFile /my core.views.handleFile </code></pre> <p><strong>Question:</strong> I am running on localhost. When I send get request to url <a href="http://localhost:8000/" rel="nofollow">http://localhost:8000/</a>, I get proper response with 200 code. But when I send get request to url <a href="http://localhost:8000/create/my" rel="nofollow">http://localhost:8000/create/my</a>, I get 404 not found error. Why is it happening like this? Shouldn't second URL also return 200 code?</p>
0
2016-09-05T16:32:33Z
39,334,634
<p>Because you're terminating the including url pattern with a $, which means the end of the pattern. Nothing can match past that. Remove those characters:</p> <pre><code>url(r'^create/', include('core.urls')), url(r'', include('core.urls')), </code></pre>
2
2016-09-05T16:34:08Z
[ "python", "django", "django-views" ]
Print the structure of large nested dictionaries in a compact way without printing all elements
39,334,638
<p>I have a large nested dictionary and I want to print its structure and one sample element in each level. </p> <p>For example:</p> <pre><code>from collections import defaultdict nested = defaultdict(dict) for i in range(10): for j in range(20): nested['key'+str(i)]['subkey'+str(j)] = {'var1': 'value1', 'var2': 'value2'} </code></pre> <p>If I pretty print this using <code>pprint</code>, I'll get all the elements which is very long, part of the output will be like the following:</p> <pre><code>from pprint import pprint pprint(nested) {'key0': {'subkey0': {'var1': 'value1', 'var2': 'value2'}, 'subkey1': {'var1': 'value1', 'var2': 'value2'}, 'subkey10': {'var1': 'value1', 'var2': 'value2'}, 'subkey11': {'var1': 'value1', 'var2': 'value2'}, 'subkey12': {'var1': 'value1', 'var2': 'value2'}, 'subkey13': {'var1': 'value1', 'var2': 'value2'}, 'subkey14': {'var1': 'value1', 'var2': 'value2'}, </code></pre> <p>Is there a built-in way or a library to show only few top elements in each level and represent the rest with <code>'...'</code> to show the whole dictionary in a compact way? Something like the following (the <code>'...'</code> is also to be printed):</p> <p>Desired output with only 1 example at each level:</p> <pre><code>{'key0': { 'subkey0': { 'var1: 'value1', '...' }, '...' }, '...' } </code></pre> <p>For lists, I found <a href="http://stackoverflow.com/questions/38533282/python-pretty-print-dictionary-of-lists-abbreviate-long-lists">this solution</a>, but I did not find anything for nested dictionaries.</p>
3
2016-09-05T16:34:16Z
39,334,848
<p>A basic solution is to just set up your own nested function that will loop through and detect values to print only the first item it finds from each. Since dictionaries aren't ordered, this does mean it will randomly pick one. So your goal is inherently complicated if you want it to intelligently separate different types of example.</p> <p>But here's how the basic function could work:</p> <pre><code>def compact_print(d, indent=''): items = d.items() key, value = items[0] if not indent: print("{") if isinstance(value, dict): print(indent + "'{}': {{".format(key)) compact_print(value, indent + ' ') print(indent + "'...'") else: print(indent + "'{}': '{}',".format(key, value)) print(indent + "'...'") print(indent + "}") </code></pre> <p>This nested function just iterates down through any dicts it finds and continues ignoring past the first item it grabs. You could add handling for lists with an <code>elif isinstance(value, list)</code>, and likewise for other types.</p> <p>For your sample input, it generates this:</p> <pre><code>{ 'key9': { 'subkey10': { 'var1': 'value1', '...' } '...' } '...' } </code></pre>
1
2016-09-05T16:51:45Z
[ "python", "dictionary", "printing" ]
How to solve this equation with SciPy
39,334,656
<p>In MathCad it looks like this:</p> <p><a href="http://i.stack.imgur.com/8rWer.png" rel="nofollow"><img src="http://i.stack.imgur.com/8rWer.png" alt="enter image description here"></a></p> <p>How to solve it using python (scipy or sympy)?</p> <p>Maybe something like this?</p> <pre><code>def fun(n): x, y, z = n return -0.7353 + 3.306 * np.absolute(0.706 - x) + 1.247 * np.absolute(0.7210 - y) - (0.89072 - 1.4829*x + 0.23239*y - z) scipy.optimize.fsolve(fun, [1,1,1]) </code></pre>
-2
2016-09-05T16:36:14Z
39,336,017
<h3>Code</h3> <p>The important thing (for this scipy.minimize based approach) is the quadratic penalization of the error (which is the difference of both sides). Of course there are other approaches, but be careful to bound the objective.</p> <pre><code>from scipy.optimize import minimize fun = lambda x: ((-0.7353 + 3.306 * (abs(0.706 - x[0])) + 1.247 * (abs(0.721 - x[1]))) - \ (0.89072 - 1.4829 * x[0] + 0.23239 * x[1] - x[2]))**2 x0 = [1, 1, 1] res = minimize(fun, x0, tol=1e-6) print(res) </code></pre> <h3>Result</h3> <pre><code>fun: 1.180300596982825e-18 hess_inv: array([[ 0.01850105, -0.02426119, -0.04300235], [-0.02426119, 0.23287182, 0.24090596], [-0.04300235, 0.24090596, 0.61570727]]) jac: array([ 5.34881862e-08, 3.58270711e-08, 1.27283284e-08]) message: 'Optimization terminated successfully.' nfev: 50 nit: 6 njev: 10 status: 0 success: True x: array([ 0.69247018, -0.38146035, -0.90898925]) </code></pre> <p>As mentioned in the comments, there is <strong>no unique solution</strong>. Your start-point and chosen algorithm decides what kind of solution you get.</p> <p>The only relevant part is the <strong>objective, which should approach zero!</strong></p>
2
2016-09-05T18:33:33Z
[ "python", "numpy", "scipy", "sympy" ]
Output of a Python input into C program
39,334,694
<p>Is it possible to do this? Output of a Python as input into C program.</p> <p>You believe me if I say that this code before works? Now it doesn't work. How can I make it work?</p> <pre><code>python -c 'print "a" ' | ./myProgram </code></pre> <p>Simple example for myProgram:</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char *argv[]){ int i = 0; if(argc &gt; 0){ for(i; i&lt;argc; i++){ printf("%s\n", argv[i]); } printf("Done."); } return 0; } </code></pre>
0
2016-09-05T16:40:13Z
39,336,745
<p>The input to your <code>C</code> code should be taken by <code>scanf</code>.</p> <p>C code: <code>[test.c]</code></p> <pre><code>#include &lt;stdio.h&gt; int main() { int x; scanf("%d",&amp;x); printf("Value is %d\n",x); } </code></pre> <p>Compile:</p> <p><code>gcc test.c -o foo</code></p> <p>Python code:<code>[test.py]</code></p> <pre><code>print (3) </code></pre> <p>Command :</p> <p><code>python test.py | ./foo</code></p> <p>Output:</p> <p><code>Value is 3</code></p> <p>Here standard input of <code>C code</code> gets changed from <code>keyboard</code> to the end of pipe. And standard output of <code>python code</code> gets changed from <code>monitor</code> to <code>beginning of pipe</code>.</p> <p>In <code>C</code> there are kernel level calls to perform this operation. Read about <code>close()</code> , <code>dup()</code> calls. I hope your concept will be cleared then. Good Luck :)</p> <p>And you are actually trying to print command line arguments. But look at your command. You are not passing any arguments to <code>myprogram</code>. So, <code>argc = 0</code>.</p>
1
2016-09-05T19:40:28Z
[ "python", "terminal", "pipe" ]
wxPython listctrl: allowing sorting for only some columns
39,334,696
<p>I have a table displayed using <code>wx.ListCtrl</code>. I want all the columns to be sortable upon clicking the column headers except for the first column which stores the row index (e.g., 0,1,2,3,...). So that means, if a user clicks on the first column's header, the table should not be sorted. But <code>ColumnSorterMixin</code> seems to only let me specify the number of sortable columns. Since the row id column is the first column, this does not allow me to exclude the row id column from one of the sortable ones. Any suggestion would be much appreciated!</p> <pre><code>import wx import wx.lib.mixins.listctrl as listmix musicdata = { 0 : ("Bad English", "The Price Of Love", "Rock"), 1 : ("DNA featuring Suzanne Vega", "Tom's Diner", "Rock"), 2 : ("George Michael", "Praying For Time", "Rock"), 3 : ("Gloria Estefan", "Here We Are", "Rock"), 4 : ("Linda Ronstadt", "Don't Know Much", "Rock"), 5 : ("Michael Bolton", "How Am I Supposed To Live Without You", "Blues"), 6 : ("Paul Young", "Oh Girl", "Rock"), } ######################################################################## class TestListCtrl(wx.ListCtrl): #---------------------------------------------------------------------- def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): wx.ListCtrl.__init__(self, parent, ID, pos, size, style) ######################################################################## class TestListCtrlPanel(wx.Panel, listmix.ColumnSorterMixin): #---------------------------------------------------------------------- def __init__(self, parent): wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS) self.index = 0 self.list_ctrl = TestListCtrl(self, size=(-1,100), style=wx.LC_REPORT |wx.BORDER_SUNKEN |wx.LC_SORT_ASCENDING ) self.list_ctrl.InsertColumn(0, "RowID") self.list_ctrl.InsertColumn(1, "Artist") self.list_ctrl.InsertColumn(2, "Title", wx.LIST_FORMAT_RIGHT) self.list_ctrl.InsertColumn(3, "Genre") items = musicdata.items() self.itemDataMap = dict() index = 0 for key, data in items: self.list_ctrl.InsertStringItem(index, str(index+1)) self.list_ctrl.SetStringItem(index, 1, data[0]) self.list_ctrl.SetStringItem(index, 2, data[1]) self.list_ctrl.SetStringItem(index, 3, data[2]) self.list_ctrl.SetItemData(index, key) self.itemDataMap[index] = (str(index), data[0], data[1], data[2]) index += 1 # Now that the list exists we can init the other base class, # see wx/lib/mixins/listctrl.py #self.itemDataMap = musicdata listmix.ColumnSorterMixin.__init__(self, 4) self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list_ctrl) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5) self.SetSizer(sizer) #---------------------------------------------------------------------- # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py def GetListCtrl(self): return self.list_ctrl #---------------------------------------------------------------------- def OnColClick(self, event): print "column clicked" event.Skip() ######################################################################## class MyForm(wx.Frame): #---------------------------------------------------------------------- def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "List Control Tutorial") # Add a panel so it looks the correct on all platforms panel = TestListCtrlPanel(self) #---------------------------------------------------------------------- # Run the program if __name__ == "__main__": app = wx.App(False) frame = MyForm() frame.Show() app.MainLoop() </code></pre>
0
2016-09-05T16:40:16Z
39,343,280
<p>I don't know if there is a prettier way of handling this. Anyway, following is my approach:</p> <pre><code>class MyColumnSorterMixin(listmix.ColumnSorterMixin): def GetColumnSorter(self): if self._col &lt;&gt; 0: return listmix.ColumnSorterMixin.GetColumnSorter(self) </code></pre> <p>Remember to use the new class, that is <code>MyColumnSorterMixin</code> as in <code>MyColumnSorterMixin.__init__(self, 4)</code></p>
1
2016-09-06T07:42:31Z
[ "python", "wxpython", "listctrl" ]
How to make return do the same as print in python string
39,334,704
<pre><code>b = 'abbaab' count = 0 width = 2 for k in range(0, len(b), width): print b[k:k + width] </code></pre> <p>gives me</p> <pre><code> ab ba ab </code></pre> <p>but I need to use return instead of print. I don't know how to store each line into something, the things I tried said index out of range.</p>
-2
2016-09-05T16:40:52Z
39,334,884
<p><code>print</code> and <code>return</code> are very different.</p> <p>Print is a function that will just print out something to the screen. return is a command that basically tells what value a function should return. For example:</p> <pre><code>def func1(): print 1 def func2() return 2 </code></pre> <p>if you do</p> <pre><code>first_result = func1() second_result = func2() </code></pre> <p>you will see that</p> <pre><code>first_result = None second_result = 2 </code></pre> <p>but if you run them</p> <pre><code>func1() func2() </code></pre> <p>you'll see that only <code>1</code> will be printed to the screen. In order to print the return of a function, you have to explictly ask for it</p> <pre><code>print func2() </code></pre> <p>With that in mind, and heading to your problem, you can store your things and return that to the function, and just then ask for python to print everything out</p> <pre><code>def func3(): b = 'abbaab' count = 0 width = 2 things = [] for k in range(0, len(b), width): things.append(b[k:k + width]) return things print func3() </code></pre> <p>Of course in this csae, you will print all values at once. In order to print each line separately, iterate the result and print each element</p> <pre><code>value_returned = func3() for element in value_returned: print element </code></pre>
0
2016-09-05T16:54:19Z
[ "python" ]
How to make return do the same as print in python string
39,334,704
<pre><code>b = 'abbaab' count = 0 width = 2 for k in range(0, len(b), width): print b[k:k + width] </code></pre> <p>gives me</p> <pre><code> ab ba ab </code></pre> <p>but I need to use return instead of print. I don't know how to store each line into something, the things I tried said index out of range.</p>
-2
2016-09-05T16:40:52Z
39,334,911
<p>I think this will work , Solution in Python 2.7.6: </p> <pre><code>def print_list(b): count = 0 width = 2 for k in range(0, len(b), width): yield b[k:k + width] b = 'abbaab' l = list(print_list(b)) for i in l: print i </code></pre> <p><strong>Output</strong>:</p> <pre><code>ab ba ab </code></pre> <p>Here I am using <code>yield</code> statement to instead of <code>return</code> to return the every line element and trying to convert all into <code>list</code> and every element in list represent each line Or else it is not necessary to convert it into <code>list</code> you can use this:</p> <pre><code> for i in print_list(b): print i </code></pre> <p>If you want to use <code>return</code> then Solution :</p> <pre><code>def print_list(b): count = 0 width = 2 ans = [] for k in range(0, len(b), width): ans.append(b[k:k + width]) return ans b = 'abbaab' for i in print_list(b): print i </code></pre> <p>Hope this helps.</p>
1
2016-09-05T16:56:01Z
[ "python" ]
How to make return do the same as print in python string
39,334,704
<pre><code>b = 'abbaab' count = 0 width = 2 for k in range(0, len(b), width): print b[k:k + width] </code></pre> <p>gives me</p> <pre><code> ab ba ab </code></pre> <p>but I need to use return instead of print. I don't know how to store each line into something, the things I tried said index out of range.</p>
-2
2016-09-05T16:40:52Z
39,334,945
<p>You want <code>return</code> to be same as <code>print</code>, <code>return</code> switches context from <code>callee</code> to <code>caller</code> function, with some value or none. Whereas <code>print</code> is used to send some output to <code>console</code></p> <p>They both cannot be same.</p> <p>In your case, assuming that you want to write this code snippet as a function and return values that are being printed, it should be done as follows:</p> <pre><code>def foo(): b = 'abbaab' stack = [] count = 0 width = 2 for k in range(0, len(b), width): stack.append(b[k:k + width]); return stack; </code></pre>
0
2016-09-05T16:58:47Z
[ "python" ]
pydbg 64 bit enumerate_processes() returning empty list
39,334,795
<p>I'm using pydbg binaries downloaded here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg</a> as recommended in previous answers.</p> <p>I can get the 32-bit version to work with a 32-bit Python interpreter, but I can't get the 64-bit version to work with 64-bit Python. <code>enumerate_processes()</code> always returns an empty list.. Am I doing something wrong?</p> <p>Test code:</p> <pre><code>import pydbg if __name__ == "__main__": print(pydbg.pydbg().enumerate_processes()) </code></pre> <p>32-bit working:</p> <pre><code>&gt;C:\Python27-32\python-32bit.exe Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32 ... &gt;C:\Python27-32\python-32bit.exe pydbg_test.py [(0L, '[System Process]'), (4L, 'System'), &lt;redacted for brevity&gt;] </code></pre> <p>64-bit gives an empty list:</p> <pre><code>&gt;python Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32 ... &gt;python pydbg_test.py [] </code></pre>
0
2016-09-05T16:47:08Z
39,338,165
<p>Pydbg defines the PROCESSENTRY32 structure wrong.</p> <p>Better use a maintained package such as <a href="https://pythonhosted.org/psutil/#psutil.process_iter" rel="nofollow">psutil</a> or use ctypes directly, e.g.:</p> <pre><code>from ctypes import windll, Structure, c_char, sizeof from ctypes.wintypes import BOOL, HANDLE, DWORD, LONG, ULONG, POINTER class PROCESSENTRY32(Structure): _fields_ = [ ('dwSize', DWORD), ('cntUsage', DWORD), ('th32ProcessID', DWORD), ('th32DefaultHeapID', POINTER(ULONG)), ('th32ModuleID', DWORD), ('cntThreads', DWORD), ('th32ParentProcessID', DWORD), ('pcPriClassBase', LONG), ('dwFlags', DWORD), ('szExeFile', c_char * 260), ] windll.kernel32.CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD] windll.kernel32.CreateToolhelp32Snapshot.restype = HANDLE windll.kernel32.Process32First.argtypes = [HANDLE, POINTER(PROCESSENTRY32)] windll.kernel32.Process32First.restype = BOOL windll.kernel32.Process32Next.argtypes = [HANDLE, POINTER(PROCESSENTRY32)] windll.kernel32.Process32Next.restype = BOOL windll.kernel32.CloseHandle.argtypes = [HANDLE] windll.kernel32.CloseHandle.restype = BOOL pe = PROCESSENTRY32() pe.dwSize = sizeof(PROCESSENTRY32) snapshot = windll.kernel32.CreateToolhelp32Snapshot(2, 0) found_proc = windll.kernel32.Process32First(snapshot, pe) while found_proc: print(pe.th32ProcessID, pe.szExeFile) found_proc = windll.kernel32.Process32Next(snapshot, pe) windll.kernel32.CloseHandle(snapshot) </code></pre>
0
2016-09-05T22:00:53Z
[ "python", "pydbg" ]
Why is my python programme running correctly in my virtual environment despite not having the packages installed in that environment?
39,334,854
<p>Hi all I hope I can get some help with this. I am on Windows XP, using Python 2.7.12 and command prompt.</p> <p>I have written a programme balances.py which uses <code>prettytable</code> package. This is installed in my main <code>C:\Python27\Lib\site-packages</code> folder.</p> <p>I just created a virtual environment:</p> <pre><code>C:\Environments\virtualenv p1_env </code></pre> <p>and activate the environment:</p> <pre><code>C:\Environments\p1_env\Scripts\activate </code></pre> <p>Now I am in p1_env:</p> <pre><code>(p1_env)C:\ </code></pre> <p>and navigate to <code>&lt;p1_env&gt;C:\Python Projects\balances.py</code></p> <p>and it runs the script even though I have not installed <code>prettytable</code> in <code>p1_env</code></p> <p><code>pip list</code> for main python installation is </p> <pre><code>virtualenv, setuptools, pip, prettytable </code></pre> <p>and the <code>pip list</code> for p1_env is </p> <pre><code>pip, setuptools, wheel </code></pre> <p>When i run the script balances.py in <code>p1_env</code> it still runs with <code>prettytable</code>. </p> <p>My question is why is balances.py running in <code>p1_env</code> even though <code>prettytable</code> is not installed in <code>p1_env</code>? </p>
2
2016-09-05T16:51:54Z
39,334,909
<p>You have installed prettytables globally. When you create a virtual environment it will include the globally installed packages hence the reason why your program is running. </p>
0
2016-09-05T16:55:47Z
[ "python", "virtualenv" ]
Why is my python programme running correctly in my virtual environment despite not having the packages installed in that environment?
39,334,854
<p>Hi all I hope I can get some help with this. I am on Windows XP, using Python 2.7.12 and command prompt.</p> <p>I have written a programme balances.py which uses <code>prettytable</code> package. This is installed in my main <code>C:\Python27\Lib\site-packages</code> folder.</p> <p>I just created a virtual environment:</p> <pre><code>C:\Environments\virtualenv p1_env </code></pre> <p>and activate the environment:</p> <pre><code>C:\Environments\p1_env\Scripts\activate </code></pre> <p>Now I am in p1_env:</p> <pre><code>(p1_env)C:\ </code></pre> <p>and navigate to <code>&lt;p1_env&gt;C:\Python Projects\balances.py</code></p> <p>and it runs the script even though I have not installed <code>prettytable</code> in <code>p1_env</code></p> <p><code>pip list</code> for main python installation is </p> <pre><code>virtualenv, setuptools, pip, prettytable </code></pre> <p>and the <code>pip list</code> for p1_env is </p> <pre><code>pip, setuptools, wheel </code></pre> <p>When i run the script balances.py in <code>p1_env</code> it still runs with <code>prettytable</code>. </p> <p>My question is why is balances.py running in <code>p1_env</code> even though <code>prettytable</code> is not installed in <code>p1_env</code>? </p>
2
2016-09-05T16:51:54Z
39,381,743
<p>Someone has written an answer I found : </p> <p>odie5533 answer on <a href="http://stackoverflow.com/questions/1382925/virtualenv-no-site-packages-and-pip-still-finding-global-packages">virtualenv --no-site-packages and pip still finding global packages?</a></p> <p><strong>A similar problem can occur on Windows if you call scripts directly as script.py which then uses the Windows default opener and opens Python outside the virtual environment. Calling it with python script.py will use Python with the virtual environment.</strong></p> <p>So All I had to do was write "python balances.py" instead of just "balances.py". Still want it to work when I just type balances.py but nothing to get worked up over.</p> <p>Thanks for your help everyone.</p>
0
2016-09-08T02:34:33Z
[ "python", "virtualenv" ]
Parse only given values to command line via Python
39,334,861
<p>I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.</p> <p>The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.</p> <p>The easiest would be if I knew all the variables that would come through and do something like this:</p> <pre><code>data = json.loads(msg.payload) os.system("'command +f ' + data[arg1] + ' +g ' + data[arg2]") </code></pre> <p>But as mentioned previously, I don't know if they are being passed through, and as such, how can I break it down so that the command line command is build up?</p> <p>Maybe:</p> <pre><code> if 'arg1' in data: command = "+f " + data[arg1] else: pass if 'arg2' in data: command + "+g " + data[arg2] else: pass </code></pre> <p>Would this work? Is there a better idea?</p>
0
2016-09-05T16:52:41Z
39,351,556
<p>You can use a for loop to iterate over the json, and construct the command string.</p> <pre><code> commandArgs = ["+f ","+g "] commandCount=0 for element in data: command= command + commandArgs[commandCount] + element commandCount = commandCount +1 </code></pre>
1
2016-09-06T14:29:03Z
[ "python", "json", "mqtt" ]
Parse only given values to command line via Python
39,334,861
<p>I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.</p> <p>The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.</p> <p>The easiest would be if I knew all the variables that would come through and do something like this:</p> <pre><code>data = json.loads(msg.payload) os.system("'command +f ' + data[arg1] + ' +g ' + data[arg2]") </code></pre> <p>But as mentioned previously, I don't know if they are being passed through, and as such, how can I break it down so that the command line command is build up?</p> <p>Maybe:</p> <pre><code> if 'arg1' in data: command = "+f " + data[arg1] else: pass if 'arg2' in data: command + "+g " + data[arg2] else: pass </code></pre> <p>Would this work? Is there a better idea?</p>
0
2016-09-05T16:52:41Z
39,443,122
<p>Although you <em>could</em> do this as described it's not something you <em>should</em> do. Running user-inputted commands is one of the most unsecure things a program can do. Scrubbing the commands thoroughly is possible but quite difficult to do comprehensively. The usual approach is to have a table of acceptable commands, match against the table, and then use the entries <em>from that table</em> to populate the command line. Nothing typed by the user ever makes it into the command line with that method. </p> <p>If you do wish to take user input directly, be extremely careful about scrubbing <em>all</em> special characters, characters outside your preferred locale, double-byte characters, path delimiter characters, etc. Perhaps you could start with the snippet Jeff provided and add a lot of data scrubbing code.</p> <p>Also, be aware that the probability that whatever you do not code for will eventually be submitted for processing corresponds roughly to the risk of that command. For example, if you fail to catch and remove <code>cat ~/.ssh/*</code> there's a moderately good chance one of your users will execute it or someone will break in and do so. But if you do not catch and remove <code>rm -r /*</code> the chance someone will submit <em>that</em> command approaches certainty.</p>
1
2016-09-12T03:51:51Z
[ "python", "json", "mqtt" ]
Regex ('foo'|'bar') notation
39,334,868
<p>I'm using regex to parse some time data, but my attempt is not matching as I would expect. Here's my code:</p> <pre><code>import re print re.findall("\d+:\d+ (am|pm)", "11:30 am - 2:20 pm") </code></pre> <p>This produces <code>['am', 'pm']</code>, not <code>['11:30 am', '2:20 pm']</code>, which is what I want.</p> <p>I can produce the result that I want with <code>\d+:\d+ am|\d+:\d+ pm</code>, but that is a little blunt and I want to know why the other is not working?</p>
2
2016-09-05T16:53:29Z
39,334,914
<p>Your problem relates to capturing groups. If you want to have non-capturing alternation use the regex <code>\d+:\d+ (?:am|pm)</code>.</p>
4
2016-09-05T16:56:07Z
[ "python", "regex" ]
Regex ('foo'|'bar') notation
39,334,868
<p>I'm using regex to parse some time data, but my attempt is not matching as I would expect. Here's my code:</p> <pre><code>import re print re.findall("\d+:\d+ (am|pm)", "11:30 am - 2:20 pm") </code></pre> <p>This produces <code>['am', 'pm']</code>, not <code>['11:30 am', '2:20 pm']</code>, which is what I want.</p> <p>I can produce the result that I want with <code>\d+:\d+ am|\d+:\d+ pm</code>, but that is a little blunt and I want to know why the other is not working?</p>
2
2016-09-05T16:53:29Z
39,335,000
<p><a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow">Quoting docs</a> (<strong>emphasis mine</strong>):</p> <blockquote> <p><code>re.findall(pattern, string, flags=0)</code></p> <p>Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. <strong>If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.</strong> Empty matches are included in the result unless they touch the beginning of another match.</p> </blockquote> <p>You may use <code>re.finditer</code>:</p> <pre><code>seq = [m.string[m.start():m.end()] for m in re.finditer("\d+:\d+ (am|pm)", "11:30 am - 2:20 pm")] # ['11:30 am', '2:20 pm'] </code></pre>
0
2016-09-05T17:02:34Z
[ "python", "regex" ]
Regex ('foo'|'bar') notation
39,334,868
<p>I'm using regex to parse some time data, but my attempt is not matching as I would expect. Here's my code:</p> <pre><code>import re print re.findall("\d+:\d+ (am|pm)", "11:30 am - 2:20 pm") </code></pre> <p>This produces <code>['am', 'pm']</code>, not <code>['11:30 am', '2:20 pm']</code>, which is what I want.</p> <p>I can produce the result that I want with <code>\d+:\d+ am|\d+:\d+ pm</code>, but that is a little blunt and I want to know why the other is not working?</p>
2
2016-09-05T16:53:29Z
39,335,091
<p>You probably don't even need regular expressions to split this particular string. If applicable, you can use the regular <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a>:</p> <pre><code>&gt;&gt;&gt; s = "11:30 am - 2:20 pm" &gt;&gt;&gt; s.split(" - ") ['11:30 am', '2:20 pm'] </code></pre> <p>This, of course, does not enforce items to be "time"-like strings.</p>
1
2016-09-05T17:10:20Z
[ "python", "regex" ]
In Matplotlib, upon mouse click event, fill the plot on the right of the mouse click
39,334,874
<p>I am new to programming and was wondering if I could get some expert assistance from the very helpful community on here.</p> <p>I am trying to create a mouse click event upon which the entire area of the plot to the right of the mouse click gets shaded. So, I want the mouse click to register the x-value, create a vertical line over that x-value, and shade the entire plot to the right of the vertical line.</p> <p>I have 5 subplots showing distributions. I would like this mouse click event to trigger only on the 4th (PDF plot) and 5th (CDF plot) subplot. The purpose of this is to set margins and analyze the distributions.</p> <p>See pic below</p> <p><a href="http://i.stack.imgur.com/spwOw.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/spwOw.jpg" alt="enter image description here"></a></p> <p>I managed to write a code to perform this action but it is not updating (shading the area) the plot upon mouse click. Here's my code</p> <pre><code>import numpy as np from scipy.stats import norm, lognorm, uniform import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons, CheckButtons from matplotlib.patches import Polygon #####Mean and standard deviation##### mu_a1 = 1 mu_b1 = 10 mu_c1 = -13 sigma_a1 = 0.14 sigma_b1 = 1.16 sigma_c1 = 2.87 mu_x01 = -11 sigma_x01 = 1.9 #####_____##### #####Generating random data##### a1 = 0.75*mu_a1 + (1.25 - 0.75)*sigma_a1*np.random.sample(10000) b1 = 8*mu_b1 + (12 - 8)*sigma_b1*np.random.sample(10000) c1 = -12*mu_c1 + 2*sigma_c1*np.random.sample(10000) x01 = (-b1 - np.sqrt(b1**2 - (4*a1*c1)))/(2*a1) #####_____##### #####Creating Subplots##### fig = plt.figure() plt.subplots_adjust(left=0.13,right=0.99,bottom=0.05) ax1 = fig.add_subplot(331) #Subplot 1 ax1.set_xlabel('a' , fontsize = 14) ax1.grid(True) ax2 = fig.add_subplot(334) #Subplot 2 ax2.set_xlabel('b', fontsize = 14) ax2.grid(True) ax3 = fig.add_subplot(337) #Subplot 3 ax3.set_xlabel('c', fontsize = 14) ax3.grid(True) ax4 = fig.add_subplot(132) #Subplot 4 ax4.set_xlabel('x0', fontsize = 14) ax4.set_ylabel('PDF', fontsize = 14) ax4.grid(True) ax5 = fig.add_subplot(133) #Subplot 5 ax5.set_xlabel('x0', fontsize = 14) ax5.set_ylabel('CDF', fontsize = 14) ax5.grid(True) #####_____##### #####Plotting Distributions##### [n1,bins1,patches] = ax1.hist(a1, bins=50, color = 'red',alpha = 0.5, normed = True) [n2,bins2,patches] = ax2.hist(b1, bins=50, color = 'red',alpha = 0.5, normed = True) [n3,bins3,patches] = ax3.hist(c1, bins=50, color = 'red',alpha = 0.5, normed = True) [n4,bins4,patches] = ax4.hist(x01, bins=50, color = 'red',alpha = 0.5, normed = True) ax4.axvline(np.mean(x01), color = 'black', linestyle = 'dashed', lw = 2) dx = bins4[1] - bins4[0] CDF = np.cumsum(n4)*dx ax5.plot(bins4[1:], CDF, color = 'red') #####_____##### #####Event handler for button_press_event##### def onclick(event): ''' Event handler for button_press_event @param event MouseEvent ''' global ix ix = event.xdata if ix is not None: print 'x = %f' %(ix) ax4.clear() ax5.clear() ax4.grid(True) ax5.grid(True) [n4,bins4,patches] = ax4.hist(x01, bins=50, color = 'red',alpha = 0.5, normed = True) ax4.axvline(np.mean(x01), color = 'black', linestyle = 'dashed', lw = 2) ax4.axvspan(ix, -90, facecolor='0.9', alpha=0.5) dx = bins4[1] - bins4[0] CDF = np.cumsum(n4)*dx ax5.plot(bins4[1:], CDF, color = 'red') ax5.axvspan(ix, -75, facecolor='0.9', alpha=0.5) return ix cid = fig.canvas.mpl_connect('button_press_event', onclick) plt.show() #####_____##### </code></pre> <p>Also, since I am using <code>axvspan</code>, it asks me to input xmin and xmax value. The xmin = mouse_click_value, and the xmax, I would like it to be till the end of the plot, what ever the end value may be. Currently, I am using a fixed value (-90 or -75 from the pic). This doesn't seem to work as the value of the variables change.</p>
2
2016-09-05T16:53:40Z
39,335,287
<h1>For your main question:</h1> <p>Just add:</p> <pre><code>plt.draw() </code></pre> <p>after all the updates you do (i.e before the <code>return</code> of <code>onClick</code>).</p> <h1>For your seconed question:</h1> <p>You can use (on <code>ax5</code> for example):</p> <pre><code>ax5.get_xlim()[1] </code></pre> <p>to get the <code>xmax</code> of <code>ax5</code></p>
1
2016-09-05T17:28:11Z
[ "python", "matplotlib", "mouseclick-event" ]
paramiko - How can I refresh the modified date of a file on the SFTP server automatically?
39,334,889
<p>I have a file on the SFTP server that should be imported with <strong>paramiko</strong> package on certain conditions. Until these conditions aren't fulfilled, this file should stay on the server unimported, but its modified date shoud be updated, so that this date should be always bigger than the time, at which file was checked by my import program. </p> <p>I read the <a href="http://docs.paramiko.org/en/2.0/api/sftp.html" rel="nofollow">documentation</a> for the package but didn't found any function that could do this.</p>
0
2016-09-05T16:54:48Z
39,334,890
<p>This can be done with copying the file from the SFTP to the local host, removing the file from the SFTP and copying it again to the SFTP.</p> <p>So,</p> <ol> <li><code>get(remotepath, localpath, callback=None)</code></li> <li><code>remove(path)</code></li> <li><code>put(localpath, remotepath, callback=None, confirm=True)</code></li> </ol> <p>If anyone has another idea, please share your knowledge!</p>
0
2016-09-05T16:54:48Z
[ "python", "sftp", "paramiko", "last-modified" ]
paramiko - How can I refresh the modified date of a file on the SFTP server automatically?
39,334,889
<p>I have a file on the SFTP server that should be imported with <strong>paramiko</strong> package on certain conditions. Until these conditions aren't fulfilled, this file should stay on the server unimported, but its modified date shoud be updated, so that this date should be always bigger than the time, at which file was checked by my import program. </p> <p>I read the <a href="http://docs.paramiko.org/en/2.0/api/sftp.html" rel="nofollow">documentation</a> for the package but didn't found any function that could do this.</p>
0
2016-09-05T16:54:48Z
39,334,953
<p>I would try opening the file in append mode ("a") and closing it immediately.</p>
0
2016-09-05T16:59:30Z
[ "python", "sftp", "paramiko", "last-modified" ]
paramiko - How can I refresh the modified date of a file on the SFTP server automatically?
39,334,889
<p>I have a file on the SFTP server that should be imported with <strong>paramiko</strong> package on certain conditions. Until these conditions aren't fulfilled, this file should stay on the server unimported, but its modified date shoud be updated, so that this date should be always bigger than the time, at which file was checked by my import program. </p> <p>I read the <a href="http://docs.paramiko.org/en/2.0/api/sftp.html" rel="nofollow">documentation</a> for the package but didn't found any function that could do this.</p>
0
2016-09-05T16:54:48Z
39,342,187
<p>There's the <a href="http://docs.paramiko.org/en/2.0/api/sftp.html#paramiko.sftp_client.SFTPClient.utime" rel="nofollow"><code>utime</code> method</a>:</p> <pre><code> utime(path, times) </code></pre> <blockquote> <p>Set the access and modified times of the file specified by <code>path</code>. If <code>times</code> is <code>None</code>, then the file’s access and modified times are set to the current time. Otherwise, <code>times</code> must be a 2-tuple of numbers, of the form <code>(atime, mtime)</code>, which is used to set the access and modified times, respectively.</p> </blockquote>
1
2016-09-06T06:43:43Z
[ "python", "sftp", "paramiko", "last-modified" ]
How to make triangle x in python from source code below
39,334,916
<p>Hello I want to ask everybody... Like this... I want to make a triangle X or *, like below:</p> <pre><code> * *** ***** ******* ********* </code></pre> <p>My Algorithm is like this:</p> <pre><code>for y:=1 to i do for x:=1 to j do for j-x to 1 do write(' '); for i to 2*(x-1)+1 do write('*'); </code></pre> <p>Can anybody tell me how is the source code for python like pascal in above? Thanks for your answer</p>
-3
2016-09-05T16:56:17Z
39,334,947
<p>I have some code to do that lying around here, maybe this can help you :)</p> <pre><code>def pascals_triangle(order): """ :brief: Compute the line of pascal's triangle with order 'order' | line | order | |---------------------|-------| | 1 | 0 | | 1 1 | 1 | | 1 2 1 | 2 | | 1 3 3 1 | 3 | | 1 4 6 4 1 | 4 | :param order: order of the line in pascal's triangle (starting with 0, which returns just [1]) :return: a list of the pascal's triangle line of order 'order' """ line = [1] for k in xrange(order): line.append(line[k] * (order - k) / (k + 1)) return line </code></pre>
1
2016-09-05T16:59:05Z
[ "python", "algorithm", "pascal" ]
How to make triangle x in python from source code below
39,334,916
<p>Hello I want to ask everybody... Like this... I want to make a triangle X or *, like below:</p> <pre><code> * *** ***** ******* ********* </code></pre> <p>My Algorithm is like this:</p> <pre><code>for y:=1 to i do for x:=1 to j do for j-x to 1 do write(' '); for i to 2*(x-1)+1 do write('*'); </code></pre> <p>Can anybody tell me how is the source code for python like pascal in above? Thanks for your answer</p>
-3
2016-09-05T16:56:17Z
39,335,077
<p>You can simply do this like that:</p> <pre><code>def triangle(lines): for i in range(lines): print(' '*(lines-i) + '*'*(i*2+1)) triangle(5) </code></pre> <p>Output as expected</p> <pre><code> * *** ***** ******* ********* </code></pre>
3
2016-09-05T17:09:10Z
[ "python", "algorithm", "pascal" ]
How to make triangle x in python from source code below
39,334,916
<p>Hello I want to ask everybody... Like this... I want to make a triangle X or *, like below:</p> <pre><code> * *** ***** ******* ********* </code></pre> <p>My Algorithm is like this:</p> <pre><code>for y:=1 to i do for x:=1 to j do for j-x to 1 do write(' '); for i to 2*(x-1)+1 do write('*'); </code></pre> <p>Can anybody tell me how is the source code for python like pascal in above? Thanks for your answer</p>
-3
2016-09-05T16:56:17Z
39,335,164
<p>Here's a possible solution:</p> <pre><code>def print_pascals_triangle(levels, debug_char=None): triangle = [] for order in range(levels): line = [debug_char] if debug_char is not None else [1] for k in range(order): if debug_char is None: value = line[k] * (order - k) / (k + 1) line.append(value) else: line.append(debug_char) triangle.append(line) def format_row(row): return ' '.join(map(str, row)) triangle_width = len(format_row(triangle[-1])) for row in triangle: print(format_row(row).center(triangle_width)) </code></pre> <p>If you want the real pascal triangle you can use it like this:</p> <pre><code>for level in range(1, 8): print_pascals_triangle(level) print('-' * 80) </code></pre> <p>And you'll get:</p> <pre><code>1 -------------------------------------------------------------------------------- 1 1 1 -------------------------------------------------------------------------------- 1 1 1 1 2 1 -------------------------------------------------------------------------------- 1 1 1 1 2 1 1 3 3 1 -------------------------------------------------------------------------------- 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 -------------------------------------------------------------------------------- 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 -------------------------------------------------------------------------------- 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 -------------------------------------------------------------------------------- </code></pre> <p>Otherwise, you can fake the numbers with another character, like this:</p> <pre><code>for level in range(1, 8): print_pascals_triangle(level, debug_char='*') print('-' * 80) </code></pre> <p>And you'll get this:</p> <pre><code>* -------------------------------------------------------------------------------- * * * -------------------------------------------------------------------------------- * * * * * * -------------------------------------------------------------------------------- * * * * * * * * * * -------------------------------------------------------------------------------- * * * * * * * * * * * * * * * -------------------------------------------------------------------------------- * * * * * * * * * * * * * * * * * * * * * -------------------------------------------------------------------------------- * * * * * * * * * * * * * * * * * * * * * * * * * * * * -------------------------------------------------------------------------------- </code></pre>
1
2016-09-05T17:17:45Z
[ "python", "algorithm", "pascal" ]
How do I organise a nested list representing coordinate-values to a coordinate-list
39,334,935
<p>I would like to change my data-structure that get from my data-files in such a way that I get a list of all coordinate-values for every coordinates (so a list for all coordinates filled with values)</p> <p>e.g. for i in range (files):</p> <h3>open file</h3> <pre><code>file_output = [[0,4,6],[9,4,1],[2,5,3]] </code></pre> <h3>second loop</h3> <pre><code>file_output = [[6,1,8],[4,7,3],[3,7,0]] </code></pre> <p>to </p> <pre><code>coordinates = [[0,6],[4,1],[6,8],[9,4],[4,7],[1,3],[2,3],[5,7],[3,0]] </code></pre> <p>It should be noted that I use over 1000 files of this format, which I should merge.</p>
0
2016-09-05T16:57:48Z
39,334,970
<pre><code>&gt;&gt;&gt; a = [[0,4,6],[9,4,1],[2,5,3]] &gt;&gt;&gt; b = [[6,1,8],[4,7,3],[3,7,0]] &gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; zip(chain(*a),chain(*b)) [(0, 6), (4, 1), (6, 8), (9, 4), (4, 7), (1, 3), (2, 3), (5, 7), (3, 0)] &gt;&gt;&gt; </code></pre>
0
2016-09-05T17:00:45Z
[ "python", "list", "structure", "coordinates" ]
How do I organise a nested list representing coordinate-values to a coordinate-list
39,334,935
<p>I would like to change my data-structure that get from my data-files in such a way that I get a list of all coordinate-values for every coordinates (so a list for all coordinates filled with values)</p> <p>e.g. for i in range (files):</p> <h3>open file</h3> <pre><code>file_output = [[0,4,6],[9,4,1],[2,5,3]] </code></pre> <h3>second loop</h3> <pre><code>file_output = [[6,1,8],[4,7,3],[3,7,0]] </code></pre> <p>to </p> <pre><code>coordinates = [[0,6],[4,1],[6,8],[9,4],[4,7],[1,3],[2,3],[5,7],[3,0]] </code></pre> <p>It should be noted that I use over 1000 files of this format, which I should merge.</p>
0
2016-09-05T16:57:48Z
39,334,976
<p>This should be useful.</p> <pre><code>[zip(i,j) for i in a for j in b] </code></pre> <p>However it provides list of tuples, which should satisfy your needs.</p> <p>If there will only be two lists, you can use this as well.</p> <pre><code>[[i, j] for i in a for j in b] </code></pre>
0
2016-09-05T17:00:58Z
[ "python", "list", "structure", "coordinates" ]
How do I organise a nested list representing coordinate-values to a coordinate-list
39,334,935
<p>I would like to change my data-structure that get from my data-files in such a way that I get a list of all coordinate-values for every coordinates (so a list for all coordinates filled with values)</p> <p>e.g. for i in range (files):</p> <h3>open file</h3> <pre><code>file_output = [[0,4,6],[9,4,1],[2,5,3]] </code></pre> <h3>second loop</h3> <pre><code>file_output = [[6,1,8],[4,7,3],[3,7,0]] </code></pre> <p>to </p> <pre><code>coordinates = [[0,6],[4,1],[6,8],[9,4],[4,7],[1,3],[2,3],[5,7],[3,0]] </code></pre> <p>It should be noted that I use over 1000 files of this format, which I should merge.</p>
0
2016-09-05T16:57:48Z
39,334,994
<p>You could also explore the built-in <strong><a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip()</code></a></strong> function</p> <pre><code>&gt;&gt;&gt; l = [] &gt;&gt;&gt; for k,v in zip(a,b): l.append(zip(k,v)) &gt;&gt;&gt; print l [[0,6],[4,1],[6,8],[9,4],[4,7],[1,3],[2,3],[5,7],[3,0]] </code></pre>
1
2016-09-05T17:01:52Z
[ "python", "list", "structure", "coordinates" ]
Tkinter: How to add kwargs to a class you inherit from?
39,335,013
<p>How do I add keyword arguments (<a href="http://effbot.org/tkinterbook/frame.htm" rel="nofollow">**options</a>) to a Tkinter class that inherits from <code>tk.Frame</code>? For example, all I want to do is set the frame's <code>width</code> and <code>height</code> (or any other options).</p> <p>The broader question is: how do I add **kwargs to the object the class itself inherits from?</p> <pre><code>class profiles(tk.Frame): def __init__(self, parent, *args, **kwargs): self.parent = parent kwargs['width'] = 900 kwargs['height'] = 600 super(profiles, self).__init__(parent, *args, **kwargs) </code></pre> <p><strong>Edit</strong>:</p> <p>Here's a complete code example of what I'm trying to understand. This is the entire code:</p> <pre><code>import tkinter as tk class profiles(tk.Frame): def __init__(self, parent, *args, **kwargs): self.parent = parent kwargs['width'] = 900 kwargs['height'] = 600 kwargs['background'] = 'red' #tk.Frame.__init__(self, parent, *args, **kwargs) super(profiles, self).__init__(parent, *args, **kwargs) #self.parent.geometry('900x600') self.profile_name_label = tk.Label(self.parent, text='Profile name:') self.profile_name_label.grid(row=0, column=0, padx=(20), pady=20) self.ProfileNameVar = tk.StringVar() self.profile_name_entry = tk.Entry(self.parent, textvariable=self.ProfileNameVar) self.profile_name_entry.grid(row=0, column=1, pady=(20)) root = tk.Tk() profiles(root) root.mainloop() </code></pre> <p>Questions about this code:</p> <ol> <li><p><code>self.parent.geometry('900x600')</code> does what I expect which is resizing the window. <strong>Should kwargs['width'] = 900 and kwargs['height'] = 600 do the same thing Since <code>tk.Frame</code> sits inside its parent <code>root</code>?</strong> It seems like none of the <code>kwargs</code> I add do anything.</p></li> <li><p>Even if I add <code>kwargs['background'] = 'red'</code>, I see no effect. I've seen examples of people using this syntax: <a href="https://mail.python.org/pipermail/tutor/2006-August/048394.html" rel="nofollow">here</a>, <a href="http://stackoverflow.com/questions/14459993/tkinter-listbox-drag-and-drop-with-python/25023944#25023944">here</a>. <strong>Why doesn't the background color turn red?</strong></p></li> </ol> <p><a href="http://i.stack.imgur.com/WQ8wz.png" rel="nofollow"><img src="http://i.stack.imgur.com/WQ8wz.png" alt="picture of tkinter window"></a></p>
0
2016-09-05T17:03:22Z
39,335,053
<p>Just add what you want to add directly, without adding it to <code>kwargs</code>:</p> <pre><code>class profiles(tk.Frame): def __init__(self, master, *args, **kwargs): tk.Frame.__init__(self, master, width=900, height=800, *args, **kwargs) </code></pre>
0
2016-09-05T17:06:07Z
[ "python", "class", "tkinter" ]
Tkinter: How to add kwargs to a class you inherit from?
39,335,013
<p>How do I add keyword arguments (<a href="http://effbot.org/tkinterbook/frame.htm" rel="nofollow">**options</a>) to a Tkinter class that inherits from <code>tk.Frame</code>? For example, all I want to do is set the frame's <code>width</code> and <code>height</code> (or any other options).</p> <p>The broader question is: how do I add **kwargs to the object the class itself inherits from?</p> <pre><code>class profiles(tk.Frame): def __init__(self, parent, *args, **kwargs): self.parent = parent kwargs['width'] = 900 kwargs['height'] = 600 super(profiles, self).__init__(parent, *args, **kwargs) </code></pre> <p><strong>Edit</strong>:</p> <p>Here's a complete code example of what I'm trying to understand. This is the entire code:</p> <pre><code>import tkinter as tk class profiles(tk.Frame): def __init__(self, parent, *args, **kwargs): self.parent = parent kwargs['width'] = 900 kwargs['height'] = 600 kwargs['background'] = 'red' #tk.Frame.__init__(self, parent, *args, **kwargs) super(profiles, self).__init__(parent, *args, **kwargs) #self.parent.geometry('900x600') self.profile_name_label = tk.Label(self.parent, text='Profile name:') self.profile_name_label.grid(row=0, column=0, padx=(20), pady=20) self.ProfileNameVar = tk.StringVar() self.profile_name_entry = tk.Entry(self.parent, textvariable=self.ProfileNameVar) self.profile_name_entry.grid(row=0, column=1, pady=(20)) root = tk.Tk() profiles(root) root.mainloop() </code></pre> <p>Questions about this code:</p> <ol> <li><p><code>self.parent.geometry('900x600')</code> does what I expect which is resizing the window. <strong>Should kwargs['width'] = 900 and kwargs['height'] = 600 do the same thing Since <code>tk.Frame</code> sits inside its parent <code>root</code>?</strong> It seems like none of the <code>kwargs</code> I add do anything.</p></li> <li><p>Even if I add <code>kwargs['background'] = 'red'</code>, I see no effect. I've seen examples of people using this syntax: <a href="https://mail.python.org/pipermail/tutor/2006-August/048394.html" rel="nofollow">here</a>, <a href="http://stackoverflow.com/questions/14459993/tkinter-listbox-drag-and-drop-with-python/25023944#25023944">here</a>. <strong>Why doesn't the background color turn red?</strong></p></li> </ol> <p><a href="http://i.stack.imgur.com/WQ8wz.png" rel="nofollow"><img src="http://i.stack.imgur.com/WQ8wz.png" alt="picture of tkinter window"></a></p>
0
2016-09-05T17:03:22Z
39,335,119
<p>You would do it like this:</p> <pre><code>class Profiles(tk.Frame): def __init__(self, parent, *args, **kwargs): self.parent = parent kwargs.update(width=900, height=600) super(profiles, self).__init__(parent, *args, **kwargs) </code></pre> <p>This will override the keywords if they were passed in the call to <code>Profiles()</code>. Additional logic would be required to avoid that.</p>
0
2016-09-05T17:13:16Z
[ "python", "class", "tkinter" ]
How do I make all elements of a webpage appear in the source?
39,335,106
<p>When I press "view-source" (in chrome) of certain webpages, I get some thinned-version of an html, opposed to the more rich version I get when I press "inspect". </p> <p>I think some content (maybe the scripts) are hidden when you view the source code, and all you get is the script code and not what it translates into.</p> <p>Is there a way to get the more rich version as an html? (And obviously - if there is - how do you get it?)</p> <p>Either for download manually, or for when you open a url to read in some program (python urlopen, for example)</p>
-2
2016-09-05T17:11:33Z
39,343,908
<p>What "Show Source" does is give you the actual raw original source file that the browser received from the server. What you see in your browser and what the <em>Element Inspector</em> shows you is the current state of the DOM, these days often heavily modified at runtime by Javascript. </p> <p>source = what the page started with<br> current DOM = what the page looks like now after dynamic modification</p> <p>Nothing is being "thinned".</p> <p>I don't know about your browser, but mine allows me to copy the current DOM as HTML, I just need to select the topmost element:</p> <p><a href="http://i.stack.imgur.com/y2gHd.png" rel="nofollow"><img src="http://i.stack.imgur.com/y2gHd.png" alt="enter image description here"></a></p>
3
2016-09-06T08:15:05Z
[ "javascript", "python", "html", "element", "inspect" ]
if negative then with weighted average
39,335,149
<p>I have a DataFrame:</p> <pre><code>a = {'Price': [10, 15, 20, 25, 30], 'Total': [10000, 12000, 15000, 14000, 10000], 'Previous Quarter': [0, 10000, 12000, 15000, 14000]} a = pd.DataFrame(a) print (a) </code></pre> <p>With this raw data, i have added a number of additional columns including a weighted average price (WAP)</p> <pre><code>a['Change'] = a['Total'] - a['Previous Quarter'] a['Amount'] = a['Price']*a['Change'] a['Cum Sum Amount'] = np.cumsum(a['Amount']) a['WAP'] = a['Cum Sum Amount'] / a['Total'] </code></pre> <p>This is fine, however as the total starts to decrease this brings down the weighted average price.</p> <p>my question is, if Total decreases how would i get WAP to reflect the row above? For instance in row 3, Total is 1000, which is lower than in row 2. This brings WAP down from 12.6 to 11.78, but i would like it to say 12.6 instead of 11.78. </p> <p>I have tried looping through a['Total'] &lt; 0 then a['WAP'] = 0 but this impacts the whole column. </p> <p>Ultimately i am looking for a WAP column which reads: 10, 10.83, 12.6, 12.6, 12.6</p>
2
2016-09-05T17:16:04Z
39,335,417
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cummax.html" rel="nofollow"><code>cummax</code></a>: </p> <pre><code>a['WAP'] = (a['Cum Sum Amount'] / a['Total']).cummax() print (a['WAP']) 0 10.000000 1 10.833333 2 12.666667 3 12.666667 4 12.666667 Name: WAP, dtype: float64 </code></pre>
3
2016-09-05T17:39:12Z
[ "python", "pandas" ]
if negative then with weighted average
39,335,149
<p>I have a DataFrame:</p> <pre><code>a = {'Price': [10, 15, 20, 25, 30], 'Total': [10000, 12000, 15000, 14000, 10000], 'Previous Quarter': [0, 10000, 12000, 15000, 14000]} a = pd.DataFrame(a) print (a) </code></pre> <p>With this raw data, i have added a number of additional columns including a weighted average price (WAP)</p> <pre><code>a['Change'] = a['Total'] - a['Previous Quarter'] a['Amount'] = a['Price']*a['Change'] a['Cum Sum Amount'] = np.cumsum(a['Amount']) a['WAP'] = a['Cum Sum Amount'] / a['Total'] </code></pre> <p>This is fine, however as the total starts to decrease this brings down the weighted average price.</p> <p>my question is, if Total decreases how would i get WAP to reflect the row above? For instance in row 3, Total is 1000, which is lower than in row 2. This brings WAP down from 12.6 to 11.78, but i would like it to say 12.6 instead of 11.78. </p> <p>I have tried looping through a['Total'] &lt; 0 then a['WAP'] = 0 but this impacts the whole column. </p> <p>Ultimately i am looking for a WAP column which reads: 10, 10.83, 12.6, 12.6, 12.6</p>
2
2016-09-05T17:16:04Z
39,335,542
<p>As a total Python beginner, here are two options I could think of</p> <p>Either</p> <pre><code>a['WAP'] = np.maximum.accumulate(a['Cum Sum Amount'] / a['Total']) </code></pre> <p>Or after you've already created <code>WAP</code> you could modify only the subset using the <code>diff</code> method (thanks to @ayhan for the <code>loc</code> which will modify <code>a</code> in place)</p> <pre><code>a.loc[a['WAP'].diff() &lt; 0, 'WAP'] = max(a['WAP']) </code></pre>
1
2016-09-05T17:51:47Z
[ "python", "pandas" ]
Counting repeated (duplicated) in a list using dictionary
39,335,188
<p>I'm writing a program to identify repeated values and their count in a particular column (named 'StrId') in an Excel spreadsheet. Besides finding repetitions, I need to know how many times each value is repeated.</p> <p>The Excel data was processed as a list of dictionaries (one dictionary per row) with headers as keys and data as values, like [{'StrId' : 1, 'ProjId' : 358}][{'StrId' : 2, 'ProjId' : 984...}] etc.</p> <p>My plan was to first identify the 'StrId' keys in each dictionary, put them in a list, and then create another dictionary within that list to pass values and separate when there is more than 1 value, counting those that show up more than once.</p> <p>Here is my code. Right now, it shows a 'KeyError' message with the fist value, and stops.</p> <p>I'd appreciate any help. Thanks in advance</p> <pre><code>from openpyxl import load_workbook workbook = load_workbook('./fullallreadyconversionxmlclean4.xlsx') sheet = workbook['Full-All'] headers = ["StrId", "ProjectId", "TweetText", "Label"] excel_data = [] for row_num, row in enumerate(sheet): if row_num is 0: continue row_data = {} for col_num, cell in enumerate(row): if col_num &gt; len(headers) - 1: continue key = headers[col_num] value = cell.value row_data[key] = value excel_data.append(row_data) for row in excel_data: for key in row: if key is 'StrId': value = row[key] list_ids = [] list_ids.append(value) dup_dic = {} for value in list_ids: if value in list_ids: dup_dic[value] +=1 else: dup_dic[value] =1 print dup_dic </code></pre>
-1
2016-09-05T17:19:21Z
39,335,273
<p>Here's a possible solution:</p> <pre><code>from collections import defaultdict excel_data = [ {'StrId': 2, 'ProjId': 984}, {'StrId': 2, 'ProjId': 984}, {'StrId': 2, 'ProjId': 984}, {'StrId': 2, 'ProjId': 984}, {'StrId': 1, 'ProjId': 358}, {'StrId': 1, 'ProjId': 358}, {'StrId': 1, 'ProjId': 358}, {'StrId': 2, 'ProjId': 984}, {'StrId': 1, 'ProjId': 358}, ] output = defaultdict(int) for row in excel_data: if 'StrId' in row: output[row['StrId']] += 1 print output </code></pre> <p>If you got some question about the above code, take a look to <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">collections.defaultdict</a></p>
0
2016-09-05T17:26:28Z
[ "python", "excel", "dictionary", "duplicates" ]
Counting repeated (duplicated) in a list using dictionary
39,335,188
<p>I'm writing a program to identify repeated values and their count in a particular column (named 'StrId') in an Excel spreadsheet. Besides finding repetitions, I need to know how many times each value is repeated.</p> <p>The Excel data was processed as a list of dictionaries (one dictionary per row) with headers as keys and data as values, like [{'StrId' : 1, 'ProjId' : 358}][{'StrId' : 2, 'ProjId' : 984...}] etc.</p> <p>My plan was to first identify the 'StrId' keys in each dictionary, put them in a list, and then create another dictionary within that list to pass values and separate when there is more than 1 value, counting those that show up more than once.</p> <p>Here is my code. Right now, it shows a 'KeyError' message with the fist value, and stops.</p> <p>I'd appreciate any help. Thanks in advance</p> <pre><code>from openpyxl import load_workbook workbook = load_workbook('./fullallreadyconversionxmlclean4.xlsx') sheet = workbook['Full-All'] headers = ["StrId", "ProjectId", "TweetText", "Label"] excel_data = [] for row_num, row in enumerate(sheet): if row_num is 0: continue row_data = {} for col_num, cell in enumerate(row): if col_num &gt; len(headers) - 1: continue key = headers[col_num] value = cell.value row_data[key] = value excel_data.append(row_data) for row in excel_data: for key in row: if key is 'StrId': value = row[key] list_ids = [] list_ids.append(value) dup_dic = {} for value in list_ids: if value in list_ids: dup_dic[value] +=1 else: dup_dic[value] =1 print dup_dic </code></pre>
-1
2016-09-05T17:19:21Z
39,335,320
<p>You can use Python's <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> for this. I'm assuming your <code>excel_data</code> is structured as a list of lists with one dictionary per list, but let me know if it's not the case.</p> <pre><code>from collections import Counter excel_data = [ [{'StrId': 1, 'ProjId': 358}], [{'StrId': 2, 'ProjId': 984}], [{'StrId': 2, 'ProjId': 984}], [{'StrId': 2, 'ProjId': 984}], ] # create a list of all values flattened_values = [list_dict[0]['StrId'] for list_dict in excel_data] # pass them to counter to get a dict of value to count counter = Counter(flattened_values) # Counter({2: 3, 1: 1}) # use dictionary comprehension to create a dict from this counter with only # values with count &gt; 1 to find duplicates repetitions = { val: count for val, count in counter.iteritems() if count &gt; 1 } # {2: 3} </code></pre>
1
2016-09-05T17:31:00Z
[ "python", "excel", "dictionary", "duplicates" ]
Counting repeated (duplicated) in a list using dictionary
39,335,188
<p>I'm writing a program to identify repeated values and their count in a particular column (named 'StrId') in an Excel spreadsheet. Besides finding repetitions, I need to know how many times each value is repeated.</p> <p>The Excel data was processed as a list of dictionaries (one dictionary per row) with headers as keys and data as values, like [{'StrId' : 1, 'ProjId' : 358}][{'StrId' : 2, 'ProjId' : 984...}] etc.</p> <p>My plan was to first identify the 'StrId' keys in each dictionary, put them in a list, and then create another dictionary within that list to pass values and separate when there is more than 1 value, counting those that show up more than once.</p> <p>Here is my code. Right now, it shows a 'KeyError' message with the fist value, and stops.</p> <p>I'd appreciate any help. Thanks in advance</p> <pre><code>from openpyxl import load_workbook workbook = load_workbook('./fullallreadyconversionxmlclean4.xlsx') sheet = workbook['Full-All'] headers = ["StrId", "ProjectId", "TweetText", "Label"] excel_data = [] for row_num, row in enumerate(sheet): if row_num is 0: continue row_data = {} for col_num, cell in enumerate(row): if col_num &gt; len(headers) - 1: continue key = headers[col_num] value = cell.value row_data[key] = value excel_data.append(row_data) for row in excel_data: for key in row: if key is 'StrId': value = row[key] list_ids = [] list_ids.append(value) dup_dic = {} for value in list_ids: if value in list_ids: dup_dic[value] +=1 else: dup_dic[value] =1 print dup_dic </code></pre>
-1
2016-09-05T17:19:21Z
39,339,385
<p>If the sublists can contain more than one dict you can flatten the sublists with <em>itertools.chain</em> :</p> <pre><code>from collections import Counter excel_data = [ [{'StrId': 1, 'ProjId': 358},{'StrId': 5, 'ProjId': 358}], [{'StrId': 2, 'ProjId': 984},{'StrId': 3, 'ProjId': 358}], [{'StrId': 2, 'ProjId': 984}], [{'StrId': 2, 'ProjId': 984}], ] from collections import Counter from itertools import chain print(Counter(map(itemgetter("StrId"), chain(*excel_data)))) </code></pre> <p>But you seem to have a list of dicts so you can remove the chain:</p> <pre><code>from collections import Counter print(Counter(map(itemgetter("StrId"), excel_data))) </code></pre> <p>Never use if <em>is</em> when comparing strings, is checks the identity of and object, use <code>==</code> i.e <code>if key == 'StrId'</code> but it would make a lot more sense to just do a lookup i.e <code>value = row["StrId"]</code>. Also give you variables better names, <code>row</code> is not a very good name for a <em>dict</em>.</p>
1
2016-09-06T01:20:51Z
[ "python", "excel", "dictionary", "duplicates" ]
Append new lines to the existing file in Pandas dataframe
39,335,303
<p>I have a python script that runs a query and stores it in a dataframe as below:</p> <pre><code> df = pd.read_gbq(queryString, project_id=PROJECT) out = df.to_json(orient='records')[1:-1].replace('},{', '}\n{') </code></pre> <p>After some processing, I current store it in a json file:</p> <pre><code>with open('/home/user/Downloads/Count1/Count.json', 'w') as f: f.write(out) </code></pre> <p>Every time when the program runs, it overwrites the existing file. I was just wondering whether there is a method in Python that appends only the new lines to the existing file rather than overwriting the entire file.</p> <p>Any help would be appreciated !!</p>
0
2016-09-05T17:29:36Z
39,335,368
<p>Try this: </p> <pre><code>with open('/home/user/Downloads/Count1/Count.json', 'ab') as f: f.write(out) </code></pre>
3
2016-09-05T17:34:33Z
[ "python", "file", "dataframe" ]
Remove several rows with zero values in a dataframe using python
39,335,350
<p>HI everybody i need some help with python. </p> <p>I'm working with an excel with several rows, some of this rows has zero value in all the columns, so i need to delete that rows. </p> <pre><code>In id a b c d a 0 1 5 0 b 0 0 0 0 c 0 0 0 0 d 0 0 0 1 e 1 0 0 1 Out id a b c d a 0 1 5 0 d 0 0 0 1 e 1 0 0 1 </code></pre> <p>I think in something like show the rows that do not contain zeros, but do not work because is deleting all the rows with zero and without zero </p> <pre><code>path = '/Users/arronteb/Desktop/excel/ejemplo1.xlsx' xlsx = pd.ExcelFile(path) df = pd.read_excel(xlsx,'Sheet1') df_zero = df[(df.OTC != 0) &amp; (df.TM != 0) &amp; (df.Lease != 0) &amp; (df.Maint != 0) &amp; (df.Support != 0) &amp; (df.Other != 0)] </code></pre> <p>Then i think like just show the columns with zero </p> <pre><code>In id a b c d a 0 1 5 0 b 0 0 0 0 c 0 0 0 0 d 0 0 0 1 e 1 0 0 1 Out id a b c d b 0 0 0 0 c 0 0 0 0 </code></pre> <p>So i make a little change and i have something like this </p> <pre><code>path = '/Users/arronteb/Desktop/excel/ejemplo1.xlsx' xlsx = pd.ExcelFile(path) df = pd.read_excel(xlsx,'Sheet1') df_zero = df[(df.OTC == 0) &amp; (df.TM == 0) &amp; (df.Lease == 0) &amp; (df.Maint == 0) &amp; (df.Support == 0) &amp; (df.Other == 0)] </code></pre> <p>In this way I just get the column with zeros. I need a way to remove this 2 rows from the original input, and receive the output without that rows. Thanks, and sorry for the bad English, I'm working on that too</p>
0
2016-09-05T17:33:13Z
39,335,433
<p>For this dataframe:</p> <pre><code>df Out: id a b c d e 0 a 2 0 2 0 1 1 b 1 0 1 1 1 2 c 1 0 0 0 1 3 d 2 0 2 0 2 4 e 0 0 0 0 2 5 f 0 0 0 0 0 6 g 0 2 1 0 2 7 h 0 0 0 0 0 8 i 1 2 2 0 2 9 j 2 2 1 2 1 </code></pre> <p>Temporarily set the index:</p> <pre><code>df = df.set_index('id') </code></pre> <p>Drop rows containing all zeros and reset the index:</p> <pre><code>df = df[~(df==0).all(axis=1)].reset_index() df Out: id a b c d e 0 a 2 0 2 0 1 1 b 1 0 1 1 1 2 c 1 0 0 0 1 3 d 2 0 2 0 2 4 e 0 0 0 0 2 5 g 0 2 1 0 2 6 i 1 2 2 0 2 7 j 2 2 1 2 1 </code></pre>
2
2016-09-05T17:40:53Z
[ "python", "excel", "dataframe" ]
Remove several rows with zero values in a dataframe using python
39,335,350
<p>HI everybody i need some help with python. </p> <p>I'm working with an excel with several rows, some of this rows has zero value in all the columns, so i need to delete that rows. </p> <pre><code>In id a b c d a 0 1 5 0 b 0 0 0 0 c 0 0 0 0 d 0 0 0 1 e 1 0 0 1 Out id a b c d a 0 1 5 0 d 0 0 0 1 e 1 0 0 1 </code></pre> <p>I think in something like show the rows that do not contain zeros, but do not work because is deleting all the rows with zero and without zero </p> <pre><code>path = '/Users/arronteb/Desktop/excel/ejemplo1.xlsx' xlsx = pd.ExcelFile(path) df = pd.read_excel(xlsx,'Sheet1') df_zero = df[(df.OTC != 0) &amp; (df.TM != 0) &amp; (df.Lease != 0) &amp; (df.Maint != 0) &amp; (df.Support != 0) &amp; (df.Other != 0)] </code></pre> <p>Then i think like just show the columns with zero </p> <pre><code>In id a b c d a 0 1 5 0 b 0 0 0 0 c 0 0 0 0 d 0 0 0 1 e 1 0 0 1 Out id a b c d b 0 0 0 0 c 0 0 0 0 </code></pre> <p>So i make a little change and i have something like this </p> <pre><code>path = '/Users/arronteb/Desktop/excel/ejemplo1.xlsx' xlsx = pd.ExcelFile(path) df = pd.read_excel(xlsx,'Sheet1') df_zero = df[(df.OTC == 0) &amp; (df.TM == 0) &amp; (df.Lease == 0) &amp; (df.Maint == 0) &amp; (df.Support == 0) &amp; (df.Other == 0)] </code></pre> <p>In this way I just get the column with zeros. I need a way to remove this 2 rows from the original input, and receive the output without that rows. Thanks, and sorry for the bad English, I'm working on that too</p>
0
2016-09-05T17:33:13Z
39,335,439
<p>Given your input you can group by whether all the columns are zero or not, then access them, eg:</p> <pre><code>groups = df.groupby((df.drop('id', axis= 1) == 0).all(axis=1)) all_zero = groups.get_group(True) non_all_zero = groups.get_group(False) </code></pre>
2
2016-09-05T17:41:18Z
[ "python", "excel", "dataframe" ]
Conversion of Strings to list
39,335,491
<p>Can someone please help me with a simple code that returns a list as an output to list converted to string? The list is NOT like this:</p> <pre><code>a = u"['a','b','c']" </code></pre> <p>but the variable is like this: </p> <pre><code>a = '[a,b,c]' </code></pre> <p>So,</p> <pre><code>list(a) </code></pre> <p>would yield the following output</p> <pre><code>['[', 'a', ',', 'b', ',', 'c', ']'] </code></pre> <p>instead I want the input to be like this:</p> <pre><code>['a', 'b', 'c'] </code></pre> <p>I have even tried using the <code>ast.literal_eval()</code> function - on using which I got a <code>ValueError</code> exception stating the argument is a malformed string.</p>
1
2016-09-05T17:46:09Z
39,335,514
<p>There is no standard library that'll load such a list. But you can trivially do this with string processing:</p> <pre><code>a.strip('[]').split(',') </code></pre> <p>would give you your list.</p> <p><code>str.strip()</code> will remove <em>any</em> of the given characters from the start and end; so it'll remove any and all <code>[</code> and <code>]</code> characters from the start until no such characters are found anymore, then remove the same characters from the end. That suffices nicely for your input sample.</p> <p><code>str.split()</code> then splits the remainder (minus the <code>[</code> and <code>]</code> characters at either end) into separate strings at any point there is a comma:</p> <pre><code>&gt;&gt;&gt; a = '[a,b,c]' &gt;&gt;&gt; a.strip('[]') 'a,b,c' &gt;&gt;&gt; a.strip('[]').split(',') ['a', 'b', 'c'] </code></pre>
2
2016-09-05T17:48:42Z
[ "python", "python-2.7" ]
Conversion of Strings to list
39,335,491
<p>Can someone please help me with a simple code that returns a list as an output to list converted to string? The list is NOT like this:</p> <pre><code>a = u"['a','b','c']" </code></pre> <p>but the variable is like this: </p> <pre><code>a = '[a,b,c]' </code></pre> <p>So,</p> <pre><code>list(a) </code></pre> <p>would yield the following output</p> <pre><code>['[', 'a', ',', 'b', ',', 'c', ']'] </code></pre> <p>instead I want the input to be like this:</p> <pre><code>['a', 'b', 'c'] </code></pre> <p>I have even tried using the <code>ast.literal_eval()</code> function - on using which I got a <code>ValueError</code> exception stating the argument is a malformed string.</p>
1
2016-09-05T17:46:09Z
39,335,772
<p>Let us use hack.</p> <pre><code>import string x = "[a,b,c]" for char in x: if char in string.ascii_lowercase: x = x.replace(char, "'%s'" % char) # Now x is "['a', 'b', 'c']" lst = eval(x) </code></pre> <p>This checks if a character is in the alphabet(lowercase) if it is, it replaces it with a character with single quotes around it.</p> <p><strong>Why not use this solution ?:</strong></p> <ul> <li>Fails for duplicate elements</li> <li>Fails for elements with more than single characters.</li> <li>You need to be careful about confusing single quote and double quotes</li> </ul> <p><strong>Why use this solution ?:</strong></p> <ul> <li>There are no reasons to use this solution rather than Martijn's. But it was fun coding it anyway.</li> </ul> <p>I wish you luck in your problem.</p>
0
2016-09-05T18:09:27Z
[ "python", "python-2.7" ]
ElasticSearch bulk update: organizing JSON using python script
39,335,493
<p>So I am trying to index some public Amazon data set (products) into my ElasticSearch.</p> <p>I have a very large JSON file for data (9.9 Gigabytes). I have splitted the file into various smaller files (for memory's sake), and now each file has the following structure:</p> <pre><code>{"asin": "0001048791", "salesRank": {"Books": 6334800}, "imUrl": "http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg", "categories": [["Books"]], "title": "The Crucible: Performed by Stuart Pankin, Jerome Dempsey &amp;amp; Cast"} {"asin": "0000143561", "categories": [["Movies &amp; TV", "Movies"]], "description": "3Pack DVD set - Italian Classics, Parties and Holidays.", "title": "Everyday Italian (with Giada de Laurentiis), Volume 1 (3 Pack): Italian Classics, Parties, Holidays", "price": 12.99, "salesRank": {"Movies &amp; TV": 376041}, "imUrl": "http://g-ecx.images-amazon.com/images/G/01/x-site/icons/no-img-sm._CB192198896_.gif", "related": {"also_viewed": ["B0036FO6SI", "B000KL8ODE", "000014357X", "B0037718RC", "B002I5GNVU", "B000RBU4BM"], "buy_after_viewing": ["B0036FO6SI", "B000KL8ODE", "000014357X", "B0037718RC"]}} {"asin": "0000037214", "related": {"also_viewed": ["B00JO8II76", "B00DGN4R1Q", "B00E1YRI4C"]}, "title": "Purple Sequin Tiny Dancer Tutu Ballet Dance Fairy Princess Costume Accessory", "price": 6.99, "salesRank": {"Clothing": 1233557}, "imUrl": "http://ecx.images-amazon.com/images/I/31mCncNuAZL.jpg", "brand": "Big Dreams", "categories": [["Clothing, Shoes &amp; Jewelry", "Girls"], ["Clothing, Shoes &amp; Jewelry", "Novelty, Costumes &amp; More", "Costumes &amp; Accessories", "More Accessories", "Kids &amp; Baby"]]} </code></pre> <p>Products are JSON objects, arranged one-in-a-line. </p> <p>Now I want to use ElasticSearch _bulk update to index all this data.</p> <p>Now since each document in ElasticSearch requires a header (Correct?), I have written a python script to create a new file with appropriate format.</p> <p>The shell script looks like this:</p> <pre><code>#!/bin/sh # 0. Some constants to re-define to match your environment ES_HOST=localhost:9200 JSON_FILE_IN=/home/aksarora/amazon-sample/parts/newaa JSON_FILE_OUT=/home/aksarora/amazon-sample/parts_parsed/newaa.json # 1. Python code to transform your JSON file PYTHON="import json,sys; out = open('$JSON_FILE_OUT', 'w'); with open('$JSON_FILE_IN', 'r') as json_in: docs = [json.loads(line) for line in json_in] for doc in docs: out.write('%s\n' % json.dumps({\"index\": {}})); out.write('%s\n' % json.dumps(doc, indent=0).replace('\n', '')); " # 2. run the Python script from step 1 python3 -c "$PYTHON" # 3. use the output file from step 2 in the curl command curl -s -XPOST $ES_HOST/amazon/products/_bulk --data-binary @$JSON_FILE_OUT </code></pre> <p>But when I run this, I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 4, in &lt;module&gt; File "&lt;string&gt;", line 4, in &lt;listcomp&gt; File "/usr/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/lib/python3.5/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 42 (char 41) {"error":{"root_cause":[{"type":"parse_exception","reason":"Failed to derive xcontent"}],"type":"parse_exception","reason":"Failed to derive xcontent"},"status":400} </code></pre> <p>Any idea what I am doing wrong? Thanks.</p>
0
2016-09-05T17:46:17Z
39,337,759
<p>I don't get the same results when I run the following which tries to reproduce the problem:</p> <pre><code>import json import sys json_in =( """{"asin": "0001048791", "salesRank": {"Books": 6334800}, "imUrl": "http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg", "categories": [["Books"]], "title": "The Crucible: Performed by Stuart Pankin, Jerome Dempsey &amp;amp; Cast"}""", """{"asin": "0000143561", "categories": [["Movies &amp; TV", "Movies"]], "description": "3Pack DVD set - Italian Classics, Parties and Holidays.", "title": "Everyday Italian (with Giada de Laurentiis), Volume 1 (3 Pack): Italian Classics, Parties, Holidays", "price": 12.99, "salesRank": {"Movies &amp; TV": 376041}, "imUrl": "http://g-ecx.images-amazon.com/images/G/01/x-site/icons/no-img-sm._CB192198896_.gif", "related": {"also_viewed": ["B0036FO6SI", "B000KL8ODE", "000014357X", "B0037718RC", "B002I5GNVU", "B000RBU4BM"], "buy_after_viewing": ["B0036FO6SI", "B000KL8ODE", "000014357X", "B0037718RC"]}}""", """{"asin": "0000037214", "related": {"also_viewed": ["B00JO8II76", "B00DGN4R1Q", "B00E1YRI4C"]}, "title": "Purple Sequin Tiny Dancer Tutu Ballet Dance Fairy Princess Costume Accessory", "price": 6.99, "salesRank": {"Clothing": 1233557}, "imUrl": "http://ecx.images-amazon.com/images/I/31mCncNuAZL.jpg", "brand": "Big Dreams", "categories": [["Clothing, Shoes &amp; Jewelry", "Girls"], ["Clothing, Shoes &amp; Jewelry", "Novelty, Costumes &amp; More", "Costumes &amp; Accessories", "More Accessories", "Kids &amp; Baby"]]}""", ) out = sys.stdout # send output to screen docs = [json.loads(line) for line in json_in] # assume one object per line for doc in docs: out.write('%s\n' % json.dumps({"index": {}})) out.write('%s\n' % json.dumps(doc)) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>{"index": {}} {"asin": "0001048791", "salesRank": {"Books": 6334800}, "imUrl": "http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg", "categories": [["Books"]], "title": "The Crucible: Performed by Stuart Pankin, Jerome Dempsey &amp;amp; Cast"} {"index": {}} {"asin": "0000143561", "description": "3Pack DVD set - Italian Classics, Parties and Holidays.", "title": "Everyday Italian (with Giada de Laurentiis), Volume 1 (3 Pack): Italian Classics, Parties, Holidays", "price": 12.99, "imUrl": "http://g-ecx.images-amazon.com/images/G/01/x-site/icons/no-img-sm._CB192198896_.gif", "related": {"also_viewed": ["B0036FO6SI", "B000KL8ODE", "000014357X", "B0037718RC", "B002I5GNVU", "B000RBU4BM"], "buy_after_viewing": ["B0036FO6SI", "B000KL8ODE", "000014357X", "B0037718RC"]}, "salesRank": {"Movies &amp; TV": 376041}, "categories": [["Movies &amp; TV", "Movies"]]} {"index": {}} {"asin": "0000037214", "title": "Purple Sequin Tiny Dancer Tutu Ballet Dance Fairy Princess Costume Accessory", "price": 6.99, "imUrl": "http://ecx.images-amazon.com/images/I/31mCncNuAZL.jpg", "related": {"also_viewed": ["B00JO8II76", "B00DGN4R1Q", "B00E1YRI4C"]}, "salesRank": {"Clothing": 1233557}, "brand": "Big Dreams", "categories": [["Clothing, Shoes &amp; Jewelry", "Girls"], ["Clothing, Shoes &amp; Jewelry", "Novelty, Costumes &amp; More", "Costumes &amp; Accessories", "More Accessories", "Kids &amp; Baby"]]} </code></pre>
0
2016-09-05T21:13:39Z
[ "python", "json", "elasticsearch" ]
Set up multiple session handlers on python webapp2
39,335,513
<p>I'm writing a simple web application in google appengine and python. In this application I need to handle two types of sessions: the "long term session" that stores information about users, current page ecc, with long max_age parameter and the "short term session" with max_age about 20 minutes that keep an access token for the autentication via API.</p> <p>I have implemented the following BaseHandler:</p> <p><pre>import webapp2 from webapp2_extras import sessions</p> <p>class BaseHandler(webapp2.RequestHandler):</p> <code>def dispatch(self): # Get a session store for this request. self.session_store = sessions.get_store(request=self.request) try: # Dispatch the request. webapp2.RequestHandler.dispatch(self) finally: # Save all sessions. self.session_store.save_sessions(self.response) @webapp2.cached_property def session(self): # Returns a session using the default cookie key. return self.session_store.get_session(backend='memcache') @webapp2.cached_property def session_auth(self): return self.session_store.get_session(backend='memcache', max_age=20*60)&lt;code&gt; </code></pre> <p>the problem is that all sessions have max_age=20*60 seconds (and not only the sessions accessible by self.session_auth).. How should I solve this?</p> <p>thanks</p>
0
2016-09-05T17:48:20Z
39,336,309
<p>Try setting your config params: </p> <pre><code>config = {} config['webapp2_extras.sessions'] = { 'session_max_age': 100000, # try None here also, though that is the default } app = webapp2.WSGIApplication([ ('/', HomeHandler), ], debug=True, config=config) </code></pre>
0
2016-09-05T18:59:36Z
[ "python", "google-app-engine", "session", "webapp2" ]
Label smoothing (soft targets) in Pandas
39,335,535
<p>In Pandas there is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>get_dummies</code></a> method that one-hot encodes categorical variable. Now I want to do label smoothing as described in section 7.5.1 of <a href="http://www.deeplearningbook.org/" rel="nofollow">Deep Learning</a> book:</p> <blockquote> <p>Label smoothing regularizes a model based on a softmax with <em>k</em> output values by replacing the hard <em>0</em> and <em>1</em> classification targets with targets of <code>eps / k</code> and <code>1 - (k - 1) / k * eps</code>, respectively. </p> </blockquote> <p>What would be the most efficient and/or elegant way to do label smothing in Pandas dataframe? </p>
0
2016-09-05T17:50:31Z
39,335,797
<p>First, lets use much simpler equation (<code>ϵ</code> denotes how much probability mass you move from "true label" and distribute to all remaining ones).</p> <pre><code>1 -&gt; 1 - ϵ 0 -&gt; ϵ / (k-1) </code></pre> <p>You can simply use nice mathematical property of the above, since all you have to do is</p> <pre><code>x -&gt; x * (1 - ϵ) + (1-x) * ϵ / (k-1) </code></pre> <p>thus if your dummy columns are <code>a, b, c, d</code> just do</p> <pre><code>indices = ['a', 'b', 'c', 'd'] eps = 0.1 df[indices] = df[indices] * (1 - eps) + (1-df[indices]) * eps / (len(indices) - 1) </code></pre> <p>which for</p> <pre><code>&gt;&gt;&gt; df a b c d 0 1 0 0 0 1 0 1 0 0 2 0 0 0 1 3 1 0 0 0 4 0 1 0 0 5 0 0 1 0 </code></pre> <p>returns</p> <pre><code> a b c d 0 0.900000 0.033333 0.033333 0.033333 1 0.033333 0.900000 0.033333 0.033333 2 0.033333 0.033333 0.033333 0.900000 3 0.900000 0.033333 0.033333 0.033333 4 0.033333 0.900000 0.033333 0.033333 5 0.033333 0.033333 0.900000 0.033333 </code></pre> <p>as expected.</p>
2
2016-09-05T18:11:33Z
[ "python", "pandas", "machine-learning" ]
I don't understand why i get difference answer by change put line if on in code
39,335,612
<p>I would write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example <code>s = 'azcbobobegghakl'</code> will print out <code>'beggh'</code>.</p> <pre><code>s = 'azcbobobegghakl' result = '' word ='a' sen = '' for alpha in s: if alpha &lt; word: word ='a' sen = '' if alpha &gt;= word: word = alpha sen += alpha if len(result) &lt;len(sen): result = sen print('Longest substring in alphabetical order is: '+ result) </code></pre> <p>Answer is </p> <pre><code>Logest substring in alphabetical order is: beggh </code></pre> <p>But just put code on different line. I got a wrong answer!!!</p> <pre><code>s = 'azcbobobegghakl' result = '' word ='a' sen = '' for alpha in s: if alpha &gt;= word: word = alpha sen += alpha if len(result) &lt;len(sen): result = sen if alpha &lt; word: word ='a' sen = '' print('Longest substring in alphabetical order is: '+ result) </code></pre> <p>Answer </p> <pre><code>Longest substring in alphabetical order is: eggh </code></pre> <p>The problem drive me mad!!!</p>
-1
2016-09-05T17:57:01Z
39,335,745
<p>You are discarding the first character of the new sequence</p> <pre><code>s = 'azcbobobegghakl' result = '' word ='a' sen = '' for alpha in s: print alpha,word,sen if alpha &gt;= word: word = alpha sen += alpha if len(result) &lt;len(sen): result = sen if alpha &lt; word: word = alpha sen = alpha print('Longest substring in alphabetical order is: '+ result) </code></pre> <p>notice the change:</p> <pre><code> if alpha &lt; word: word = alpha sen = alpha </code></pre> <p>you should save the first character of the new sequence</p>
0
2016-09-05T18:07:07Z
[ "python" ]
I don't understand why i get difference answer by change put line if on in code
39,335,612
<p>I would write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example <code>s = 'azcbobobegghakl'</code> will print out <code>'beggh'</code>.</p> <pre><code>s = 'azcbobobegghakl' result = '' word ='a' sen = '' for alpha in s: if alpha &lt; word: word ='a' sen = '' if alpha &gt;= word: word = alpha sen += alpha if len(result) &lt;len(sen): result = sen print('Longest substring in alphabetical order is: '+ result) </code></pre> <p>Answer is </p> <pre><code>Logest substring in alphabetical order is: beggh </code></pre> <p>But just put code on different line. I got a wrong answer!!!</p> <pre><code>s = 'azcbobobegghakl' result = '' word ='a' sen = '' for alpha in s: if alpha &gt;= word: word = alpha sen += alpha if len(result) &lt;len(sen): result = sen if alpha &lt; word: word ='a' sen = '' print('Longest substring in alphabetical order is: '+ result) </code></pre> <p>Answer </p> <pre><code>Longest substring in alphabetical order is: eggh </code></pre> <p>The problem drive me mad!!!</p>
-1
2016-09-05T17:57:01Z
39,335,751
<p>Ok, let's say you got a couple of functions f1 and f2 and you're tracking every iteration of your for loop like this:</p> <pre><code>def f1(s): result = '' word = 'a' sen = '' for index, alpha in enumerate(s): if alpha &lt; word: word = 'a' sen = '' if alpha &gt;= word: word = alpha sen += alpha if len(result) &lt; len(sen): result = sen print("{0}-{1} =&gt; {2}".format(index, alpha, result)) return result def f2(s): result = '' word = 'a' sen = '' for index, alpha in enumerate(s): if alpha &gt;= word: word = alpha sen += alpha if len(result) &lt; len(sen): result = sen if alpha &lt; word: word = 'a' sen = '' print("{0}-{1} =&gt; {2}".format(index, alpha, result)) return result s = 'azcbobobegghakl' print('-' * 80) print('f1: Longest substring in alphabetical order is: ' + f1(s)) print('-' * 80) print('f2: Longest substring in alphabetical order is: ' + f2(s)) </code></pre> <p>Now, running this script would produce:</p> <pre><code>-------------------------------------------------------------------------------- 0-a =&gt; a 1-z =&gt; az 2-c =&gt; az 3-b =&gt; az 4-o =&gt; az 5-b =&gt; az 6-o =&gt; az 7-b =&gt; az 8-e =&gt; az 9-g =&gt; beg 10-g =&gt; begg 11-h =&gt; beggh 12-a =&gt; beggh 13-k =&gt; beggh 14-l =&gt; beggh f1: Longest substring in alphabetical order is: beggh -------------------------------------------------------------------------------- 0-a =&gt; a 1-z =&gt; az 2-c =&gt; az 3-b =&gt; az 4-o =&gt; az 5-b =&gt; az 6-o =&gt; az 7-b =&gt; az 8-e =&gt; az 9-g =&gt; az 10-g =&gt; egg 11-h =&gt; eggh 12-a =&gt; eggh 13-k =&gt; eggh 14-l =&gt; eggh f2: Longest substring in alphabetical order is: eggh </code></pre> <p>As you can see, everything is the same till it reaches the iteration 9, with f1 result becomes <code>9-g =&gt; beg</code> while with f2 becomes <code>9-g =&gt; az</code>, that's how the change of order is affecting to the result, hope it makes sense now.</p>
0
2016-09-05T18:07:45Z
[ "python" ]
SQLAlchemy: Trigger not firing on INSERT
39,335,704
<p>I have a problem with a trigger that doesn't fire through a <code>.merge()</code> call in SQLAlchemy. <br> I have the following trigger:</p> <pre><code>CREATE TRIGGER trigger_update_comment_count BEFORE INSERT ON mediacomment FOR EACH ROW EXECUTE PROCEDURE update_comment_count(); </code></pre> <p>The trigger executes the following procedure:</p> <pre><code>CREATE OR REPLACE FUNCTION update_comment_count() RETURNS trigger AS $BODY$ BEGIN UPDATE channel_users SET comment_count = comment_count + 1, last_comment = NEW.created_time WHERE channel_id = (SELECT ch.channel_id FROM media m INNER JOIN channel ch ON ch.user_id = m.user_id WHERE m.media_id = NEW.media_id) AND user_id = NEW.user_id; RETURN NEW; END; $BODY$ LANGUAGE plpgsql; </code></pre> <p>The trigger works great if I do a SQL-based INSERT like this:</p> <pre><code>INSERT INTO medialike VALUES (999292999,'2016-01-01 00:00:00.000000',367668179,true,'770160534981089486_12336189'); </code></pre> <p><strong>However</strong>, when I use the SQLAlchemy's <code>.merge()</code> method, a row is inserted but the trigger is not fired:</p> <pre><code>com = MediaComment( is_follower=is_follower, comment_text=comment['txt'], comment_id_native=str(comment['id']), created_time=comment['time'], user_id=str(comment['id']), media_id=self.media_id ) self.session.merge(com) self.session.commit() </code></pre> <p>Any ideas of what could cause this problem? <br> I'm running PostgreSQL-9.4 and Python3</p>
1
2016-09-05T18:03:56Z
39,353,868
<p>I figured it out by enabling logging and examining the log files in <code>pg_log</code>. The reason was that the transaction with the <code>INSERT</code>, that should have fired the trigger, was being rolled back.</p>
0
2016-09-06T16:34:13Z
[ "python", "postgresql", "sqlalchemy" ]
how to use counter on dictonary values are list items
39,335,766
<p>My defaultdict is as follows:</p> <pre><code>defaultdict(&lt;class 'list'&gt;, {'DrJillStein': [18021496, 30576467, 35175054, 122130797, 227720229, 289019104, 441389311, 456794981, 774180818,763849988988211200], 'realDonaldTrump': [14669951, 22203756, 41634520, 50769180, 75541946, 245963716, 475802156, 2325495378, 720293443260456960, 729676086632656900], 'GovGaryJohnson': [15232635, 19089116, 22330739, 29255194, 44776017, 47490022, 51752944, 73206956, 90573676, 366743017], 'HillaryClinton': [15972271, 34782406, 113298560, 115740215, 325886383, 582037089, 802430450, 3044781131, 729761993461248000, 734768872625188864]}) </code></pre> <p>It contains <code>use_name</code> and then a list of ids, in short -> key = user and value = list of ids.</p> <p>I wanted first to find out common ids and then to find out the most 5 common ids in all dict, like: if id =14669951, 15513604, 22203756</p> <p>then there occurrences like:</p> <pre><code>{[14669951:2][15513604:4][22203756:7]} </code></pre> <p>Guide me how to do that on python 3.5 or on greater version.</p>
1
2016-09-05T18:08:57Z
39,335,907
<p>Initialize a <code>Counter</code> from <code>collections</code> and ask for the 5 <code>most_common</code>.</p> <p>In order to initialize the <code>Counter</code> just provide it with a comprehension:</p> <pre><code>c = Counter(v for sub in d.values() for v in sub) </code></pre> <p>I added an extra <code>id</code> to your <code>defaultdict</code> to get a count of <code>2</code> for one of them. The result can be obtained with <code>c.most_common(5)</code>:</p> <pre><code>c.most_common(5) [(14669951, 2), (720293443260456960, 1), (763849988988211200, 1), (366743017, 1), (245963716, 1)] </code></pre>
2
2016-09-05T18:23:26Z
[ "python", "list", "python-3.x", "dictionary", "counter" ]
NameError -- imported modules when script is broken down in multiple python files
39,335,948
<p>It is hard to find a title for this question and hopefully this thread is not a duplicate. </p> <p>I was writing that long script in Python 2.7 (using PyCharm 2016.2.2) for a project and decided to split it in different .py files which I could then import into a main file. </p> <p>Unfortunately, it seems that when importing a module (e.g. numpy) earlier in the code does not mean that the .py files that are imported below will have knowledge of that.</p> <p>I am new to python and I was wondering whether there is an easy workaround for that one. </p> <p>To be more clear, here is an example structure of my code:</p> <p><i>Main.py</i> (the file that is used to run the script):</p> <pre><code>import basic numpy.random.seed(7) import load_data </code></pre> <p><i>basic.py</i>:</p> <pre><code>import pandas import numpy etc... </code></pre> <p><i>load_data.py</i>:</p> <pre><code>raw_input = pandas.read_excel('April.xls', index_col = 'DateTime') etc... </code></pre> <p>The second line of <i>Main.py</i> would cause an error <b>"NameError: name 'numpy' is not defined"</b>, meaning the numpy that was imported in <i>basic.py</i> is not passed to the <i>Main.py</i>. </p> <p>I guess that a similar error would occur for the code in <i>load_data.py</i> since 'pandas' would not be a defined name. </p> <p>Any ideas?</p> <p>Thanks.</p>
0
2016-09-05T18:27:38Z
39,336,027
<p>The <code>numpy</code> module imported in <code>basic.py</code> has a reference defined only withing <code>basic.py</code> scope. You have to explictly import <code>numpy</code> everywhere you use it.</p> <pre><code>import basic.py import numpy numpy.random.seed(7) import load_data.py </code></pre>
0
2016-09-05T18:34:19Z
[ "python", "python-2.7" ]
QLabel font differs when inserting a short HTML text
39,335,955
<p>I have noticed that the font size of a <code>QLabel()</code> in a PyQt GUI is not very consistent. Let's take a look at the following example. I've written a complete python file for a quick test. It will pop up a Qt window with two labels:</p> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sys import os '''---------------------------------------------------------------------''' ''' ''' ''' T E S T I N G ''' ''' ''' '''---------------------------------------------------------------------''' class TestWindow(QMainWindow): def __init__(self): super(TestWindow, self).__init__() # 1. Set basic geometry and color. # -------------------------------- self.setGeometry(100, 100, 800, 600) self.setWindowTitle('Hello World') palette = QPalette() palette.setColor(QPalette.Window, QColor(200,200,200)) self.setPalette(palette) self.show() # 2. Create the central frame. # ---------------------------- self.centralFrame = QFrame(self) self.centralFrame.setFrameShape(QFrame.NoFrame) self.centralLayout = QVBoxLayout() self.centralFrame.setLayout(self.centralLayout) self.centralLayout.setSpacing(5) self.centralLayout.setContentsMargins(20,20,20,20) self.setCentralWidget(self.centralFrame) # 3. Do the test. # ---------------- # TEST CASE 1 # The label with html self.infoLbl = QLabel() self.infoLbl.setTextFormat(Qt.RichText) self.infoLbl.setFrameShape(QFrame.StyledPanel) self.infoTxt = \ '&lt;html&gt; \ &lt;head&gt; \ &lt;/head&gt; \ &lt;body&gt; \ &lt;font size="10"&gt; \ &lt;p style="margin-left:8px;"&gt;My html text, font = 10pt&lt;/p&gt; \ &lt;/font&gt; \ &lt;/body&gt; \ &lt;/html&gt; ' self.infoLbl.setText(self.infoTxt) self.infoLbl.setMaximumHeight(50) self.infoLbl.setMaximumWidth(500) # TEST CASE 2 # The label with a normal string self.normalLbl = QLabel() self.normalLbl.setFrameShape(QFrame.StyledPanel) self.normalLbl.setText('My normal text, font = 10pt') font = QFont() font.setFamily("Arial") font.setPointSize(10) self.normalLbl.setFont(font) self.normalLbl.setMaximumHeight(50) self.normalLbl.setMaximumWidth(500) # 4. Add both labels to the central layout. # ------------------------------------------ self.centralLayout.addWidget(self.infoLbl) # &lt;- The label with html snippet self.centralLayout.addWidget(self.normalLbl) # &lt;- The normal label self.centralLayout.addWidget(QLabel()) # &lt;- Just a spacer if __name__== '__main__': app = QApplication(sys.argv) QApplication.setStyle(QStyleFactory.create('Fusion')) testWindow = TestWindow() app.exec_() app = None </code></pre> <p>If you run this code, this is what you get:</p> <p><a href="http://i.stack.imgur.com/mjSbX.png" rel="nofollow"><img src="http://i.stack.imgur.com/mjSbX.png" alt="Font size issue in QLabel"></a></p> <p>Why are the font sizes in both labels not equal?</p> <p>For completeness, this is my system:</p> <ul> <li>Operating system: Windows 10, 64-bit</li> <li>Python version: v3 (anaconda package)</li> <li>Qt version: PyQt5</li> </ul>
1
2016-09-05T18:28:07Z
39,336,023
<p>I think I found the answer.</p> <p>Replace the html snippet by:</p> <pre><code> self.infoTxt = \ '&lt;html&gt; \ &lt;head&gt; \ &lt;/head&gt; \ &lt;body&gt; \ &lt;p style="margin-left:8px; font-size:10pt"&gt;My html text, font = 10pt&lt;/p&gt; \ &lt;/body&gt; \ &lt;/html&gt; ' </code></pre> <p>Apparently the html tag <code>&lt;font size="10"&gt;</code> doesn't work properly. But inserting it as a CSS-style attribute like <code>style="font-size:10pt"</code> does work. Nevertheless, the html tag should work properly. This smells like a Qt bug?</p> <p><strong>EDIT :</strong> Apparently this is <strong>not</strong> a Qt bug. See the answer of @ekhumoro for clarification.</p>
0
2016-09-05T18:33:53Z
[ "python", "html", "qt", "pyqt", "pyqt5" ]
QLabel font differs when inserting a short HTML text
39,335,955
<p>I have noticed that the font size of a <code>QLabel()</code> in a PyQt GUI is not very consistent. Let's take a look at the following example. I've written a complete python file for a quick test. It will pop up a Qt window with two labels:</p> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sys import os '''---------------------------------------------------------------------''' ''' ''' ''' T E S T I N G ''' ''' ''' '''---------------------------------------------------------------------''' class TestWindow(QMainWindow): def __init__(self): super(TestWindow, self).__init__() # 1. Set basic geometry and color. # -------------------------------- self.setGeometry(100, 100, 800, 600) self.setWindowTitle('Hello World') palette = QPalette() palette.setColor(QPalette.Window, QColor(200,200,200)) self.setPalette(palette) self.show() # 2. Create the central frame. # ---------------------------- self.centralFrame = QFrame(self) self.centralFrame.setFrameShape(QFrame.NoFrame) self.centralLayout = QVBoxLayout() self.centralFrame.setLayout(self.centralLayout) self.centralLayout.setSpacing(5) self.centralLayout.setContentsMargins(20,20,20,20) self.setCentralWidget(self.centralFrame) # 3. Do the test. # ---------------- # TEST CASE 1 # The label with html self.infoLbl = QLabel() self.infoLbl.setTextFormat(Qt.RichText) self.infoLbl.setFrameShape(QFrame.StyledPanel) self.infoTxt = \ '&lt;html&gt; \ &lt;head&gt; \ &lt;/head&gt; \ &lt;body&gt; \ &lt;font size="10"&gt; \ &lt;p style="margin-left:8px;"&gt;My html text, font = 10pt&lt;/p&gt; \ &lt;/font&gt; \ &lt;/body&gt; \ &lt;/html&gt; ' self.infoLbl.setText(self.infoTxt) self.infoLbl.setMaximumHeight(50) self.infoLbl.setMaximumWidth(500) # TEST CASE 2 # The label with a normal string self.normalLbl = QLabel() self.normalLbl.setFrameShape(QFrame.StyledPanel) self.normalLbl.setText('My normal text, font = 10pt') font = QFont() font.setFamily("Arial") font.setPointSize(10) self.normalLbl.setFont(font) self.normalLbl.setMaximumHeight(50) self.normalLbl.setMaximumWidth(500) # 4. Add both labels to the central layout. # ------------------------------------------ self.centralLayout.addWidget(self.infoLbl) # &lt;- The label with html snippet self.centralLayout.addWidget(self.normalLbl) # &lt;- The normal label self.centralLayout.addWidget(QLabel()) # &lt;- Just a spacer if __name__== '__main__': app = QApplication(sys.argv) QApplication.setStyle(QStyleFactory.create('Fusion')) testWindow = TestWindow() app.exec_() app = None </code></pre> <p>If you run this code, this is what you get:</p> <p><a href="http://i.stack.imgur.com/mjSbX.png" rel="nofollow"><img src="http://i.stack.imgur.com/mjSbX.png" alt="Font size issue in QLabel"></a></p> <p>Why are the font sizes in both labels not equal?</p> <p>For completeness, this is my system:</p> <ul> <li>Operating system: Windows 10, 64-bit</li> <li>Python version: v3 (anaconda package)</li> <li>Qt version: PyQt5</li> </ul>
1
2016-09-05T18:28:07Z
39,336,089
<p>As you've already discovered it seems you need to use style instead. More info about it here:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font</a></li> <li><a href="http://www.w3schools.com/tags/tag_font.asp" rel="nofollow">http://www.w3schools.com/tags/tag_font.asp</a></li> </ul> <p>It says:</p> <blockquote> <p>This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.</p> </blockquote> <p>and </p> <blockquote> <p>The tag is not supported in HTML5. Use CSS instead.</p> </blockquote>
1
2016-09-05T18:40:15Z
[ "python", "html", "qt", "pyqt", "pyqt5" ]
QLabel font differs when inserting a short HTML text
39,335,955
<p>I have noticed that the font size of a <code>QLabel()</code> in a PyQt GUI is not very consistent. Let's take a look at the following example. I've written a complete python file for a quick test. It will pop up a Qt window with two labels:</p> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sys import os '''---------------------------------------------------------------------''' ''' ''' ''' T E S T I N G ''' ''' ''' '''---------------------------------------------------------------------''' class TestWindow(QMainWindow): def __init__(self): super(TestWindow, self).__init__() # 1. Set basic geometry and color. # -------------------------------- self.setGeometry(100, 100, 800, 600) self.setWindowTitle('Hello World') palette = QPalette() palette.setColor(QPalette.Window, QColor(200,200,200)) self.setPalette(palette) self.show() # 2. Create the central frame. # ---------------------------- self.centralFrame = QFrame(self) self.centralFrame.setFrameShape(QFrame.NoFrame) self.centralLayout = QVBoxLayout() self.centralFrame.setLayout(self.centralLayout) self.centralLayout.setSpacing(5) self.centralLayout.setContentsMargins(20,20,20,20) self.setCentralWidget(self.centralFrame) # 3. Do the test. # ---------------- # TEST CASE 1 # The label with html self.infoLbl = QLabel() self.infoLbl.setTextFormat(Qt.RichText) self.infoLbl.setFrameShape(QFrame.StyledPanel) self.infoTxt = \ '&lt;html&gt; \ &lt;head&gt; \ &lt;/head&gt; \ &lt;body&gt; \ &lt;font size="10"&gt; \ &lt;p style="margin-left:8px;"&gt;My html text, font = 10pt&lt;/p&gt; \ &lt;/font&gt; \ &lt;/body&gt; \ &lt;/html&gt; ' self.infoLbl.setText(self.infoTxt) self.infoLbl.setMaximumHeight(50) self.infoLbl.setMaximumWidth(500) # TEST CASE 2 # The label with a normal string self.normalLbl = QLabel() self.normalLbl.setFrameShape(QFrame.StyledPanel) self.normalLbl.setText('My normal text, font = 10pt') font = QFont() font.setFamily("Arial") font.setPointSize(10) self.normalLbl.setFont(font) self.normalLbl.setMaximumHeight(50) self.normalLbl.setMaximumWidth(500) # 4. Add both labels to the central layout. # ------------------------------------------ self.centralLayout.addWidget(self.infoLbl) # &lt;- The label with html snippet self.centralLayout.addWidget(self.normalLbl) # &lt;- The normal label self.centralLayout.addWidget(QLabel()) # &lt;- Just a spacer if __name__== '__main__': app = QApplication(sys.argv) QApplication.setStyle(QStyleFactory.create('Fusion')) testWindow = TestWindow() app.exec_() app = None </code></pre> <p>If you run this code, this is what you get:</p> <p><a href="http://i.stack.imgur.com/mjSbX.png" rel="nofollow"><img src="http://i.stack.imgur.com/mjSbX.png" alt="Font size issue in QLabel"></a></p> <p>Why are the font sizes in both labels not equal?</p> <p>For completeness, this is my system:</p> <ul> <li>Operating system: Windows 10, 64-bit</li> <li>Python version: v3 (anaconda package)</li> <li>Qt version: PyQt5</li> </ul>
1
2016-09-05T18:28:07Z
39,336,933
<p>The <code>font</code> tag is still fully supported in both Qt4 and Qt5. The fact that it has been made obsolete by the current HTML standard is irrelevant, because Qt has only ever supported <a href="http://doc.qt.io/qt-5/richtext-html-subset.html" rel="nofollow">a limited subset of HTML4</a>.</p> <p>The real problem with the example is due to a misunderstanding of the <code>size</code> attribute. This does not specify a <em>point</em> size. Rather, it specifies either, (a) a fixed value in the range 1-7, or (b) a plus/minus value relative to the <code>basefont</code> size. So all it can ever do is make the font "smaller" or "larger", and the exact results will depend entirely on the rendering engine.</p> <p>To set an <em>exact</em> point-size, use the css <code>font-size</code> property:</p> <pre><code>&lt;p style="font-size:10pt"&gt;My html text, font = 10pt&lt;/p&gt; </code></pre> <hr> <p>NB: see the <a href="http://doc.qt.io/qt-5/richtext-html-subset.html#css-properties" rel="nofollow">CSS Properties Table</a> for a list of all the css properties supported by Qt's rich-text engine.</p>
2
2016-09-05T19:55:42Z
[ "python", "html", "qt", "pyqt", "pyqt5" ]
how to fix ImportError python
39,336,128
<p>I have a file beginning with <code>from moviepy.editor import *</code>. when I run this file I get the error: </p> <blockquote> <p>Traceback (most recent call last):<br> File "moviepy.py", line 2, in <br> from moviepy.editor import * <br>File "/home/debian/Videos/moviepy.py", line 2, in <br> from moviepy.editor import * <br>ImportError: No module named editor</p> </blockquote> <p>the strange thing is I am 100% sure moviepy is installed. I checked sys.path and in one of the paths is a folder called moviepy with multiple files inside including __init__.py __init__.pyc and editor.py so what am I doing wrong?</p>
0
2016-09-05T18:43:27Z
39,336,156
<p>Your filename <code>moviepy.py</code> shadows installed package. Rename your main file and everything should work fine (if moviepy is installed in used interpreter).</p>
2
2016-09-05T18:45:53Z
[ "python", "python-2.7", "python-import", "importerror" ]
Where does tkinter load his fonts from?
39,336,204
<p>I would like to know where does tkinter load his fonts from.</p> <p>Is it from <code>/usr/share/fonts</code> or does it have a specific folder ?</p> <p>thanks</p>
2
2016-09-05T18:50:24Z
39,337,845
<p>So as Bryan said, tkinter gets the fonts from the standard font locations of the OS. Putting fonts there will permit to tkinter to be able to load them.</p> <p>Thanks Bryan</p>
0
2016-09-05T21:23:08Z
[ "python", "python-3.x", "tkinter" ]
Best approach to create time difference variable by id
39,336,234
<p>I am working with a pandas df that looks like this:</p> <pre><code>ID time 34 43 2 99 2 20 34 8 2 90 </code></pre> <p>What would be the best approach to a create variable that represents the difference from the most recent time per ID?</p> <pre><code>ID time diff 34 43 35 2 99 9 2 20 NA 34 8 NA 2 90 70 </code></pre>
3
2016-09-05T18:53:16Z
39,336,395
<p>Here's one possibility</p> <pre><code>df["diff"] = df.sort_values("time").groupby("ID")["time"].diff() df ID time diff 0 34 43 35.0 1 2 99 9.0 2 2 20 NaN 3 34 8 NaN 4 2 90 70.0 </code></pre>
3
2016-09-05T19:07:23Z
[ "python", "pandas" ]
How to write data results into an output file in python
39,336,254
<p>I have wrote this code to analyze and search geological coordinates for proximity of data points. Since I had so many data points, the output in PyCharm was becoming overloaded and gave me a bunch of nonsense. Since then I have worked to try and solve this issue by writing the True/False results into separate documents on my computer. </p> <p>The point of this code is to analyze the proximity of coordinates in file1 to all elements in file2. Then return any resulting matches of coordinates which share proximity. As you will see below I wrote a nested for loop to do this which I understand may be a sort of brute force tactic so if anybody has a more elegant solution them I would be happy to learn more. </p> <pre><code>import numpy as np import math as ma filename1 = "C:\Users\Justin\Desktop\file1.data" data1 = np.genfromtxt(filename1, skip_header=1, usecols=(0, 1)) #dtype=[ #("x1", "f9"), #("y1", "f9")]) #print "data1", data1 filename2 = "C:\Users\Justin\Desktop\file2.data" data2 = np.genfromtxt(filename2, skip_header=1, usecols=(0, 1)) #dtype=[ #("x2", "f9"), #("y2", "f9")]) #print "data2",data2 def d(a,b): d = ma.acos(ma.sin(ma.radians(a[1]))*ma.sin(ma.radians(b[1])) +ma.cos(ma.radians(a[1]))*ma.cos(ma.radians(b[1]))* (ma.cos(ma.radians((a[0]-b[0]))))) return d results = open("results.txt", "w") for coor1 in data1: for coor2 in data2: n=0 a = [coor1[0], coor1[1]] b = [coor2[0], coor2[1]] #print "a", a #print "b", b if d(a, b) &lt; 0.07865: # if true what happens results.write("\t".join([str(coor1), str(coor2), "True", str(d)]) + "\n") else: results.write("\t".join([str(coor1), str(coor2), "False", str(d)]) + "\n") results.close() </code></pre> <p>This is the error message I get when I run the code: </p> <p><code>results.write("\t".join([str(coor1), str(coor2), "False", str(d)]) + "\n") ValueError: I/O operation on closed file</code></p> <p>I think my problem is that I don't understand how I am supposed to write, save and organize the files in a meaningful format into my computer. So, again if anybody has any advice or suggestions I would be very grateful for the support!</p>
-1
2016-09-05T18:54:39Z
39,347,955
<p>My suggestion: take your code that writes to the file and wrap it in a context manager. E.g. <a href="https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/" rel="nofollow">https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/</a></p>
0
2016-09-06T11:28:11Z
[ "python", "geolocation", "coordinates", "pycharm", "data-analysis" ]
Finding the Area of a Triangle using if else statements
39,336,283
<p>I am supposed to write a program that prompts the user for the lengths of three sides of a triangle, determines that the three lengths can form a triangle and if so uses Heron's formula to compute the area to 4 digits of precision.This is what I have so far I don't know where or how to put in the math</p> <pre><code>import math def main(): print() print("Triangle Area Program") print() a, b, c = eval(input("Enter three lengths separated by commas: ")) print() s = (a+b+c) / 2.0 area = sqrt(s*(s-a)*(s-b)*(s-c)) if a &gt; b: a, b = b, a if a &gt; c: a, c = c, a if b &gt; c: b, c = c, b else: a + b &gt; c print("A triangle cannot be formed.") main() </code></pre>
1
2016-09-05T18:57:06Z
39,336,500
<p>Here's a slightly modified version of your program that checks if the inputs are compatible in one compound conditional expression and replaces the use of <code>eval</code>:</p> <pre><code>import math def main(): print("\nTriangle Area Program\n") a, b, c = map(float, input("Enter three lengths separated by commas: ").split(',')) if a + b &gt; c and a + c &gt; b and b + c &gt; a: s = (a + b + c) / 2.0 area = math.sqrt(s*(s-a)*(s-b)*(s-c)) return round(area, 4) # round area to four decimal places else: raise ValueError("The inputs you entered cannot form a triangle") if __name__ == '__main__': print(main()) </code></pre> <p>More on avoiding <code>eval</code> when you can <a href="http://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided">Why should exec() and eval() be avoided?</a></p>
1
2016-09-05T19:18:03Z
[ "python", "python-3.x" ]
Finding the Area of a Triangle using if else statements
39,336,283
<p>I am supposed to write a program that prompts the user for the lengths of three sides of a triangle, determines that the three lengths can form a triangle and if so uses Heron's formula to compute the area to 4 digits of precision.This is what I have so far I don't know where or how to put in the math</p> <pre><code>import math def main(): print() print("Triangle Area Program") print() a, b, c = eval(input("Enter three lengths separated by commas: ")) print() s = (a+b+c) / 2.0 area = sqrt(s*(s-a)*(s-b)*(s-c)) if a &gt; b: a, b = b, a if a &gt; c: a, c = c, a if b &gt; c: b, c = c, b else: a + b &gt; c print("A triangle cannot be formed.") main() </code></pre>
1
2016-09-05T18:57:06Z
39,336,544
<p>Here's another possible version of your mathy problem:</p> <pre><code>import math def heron(a, b, c): return 0.25 * math.sqrt((a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c))) if __name__ == "__main__": print() print("Triangle Area Program") print() print() try: description = "Enter three lengths separated by commas: " sides = sorted(map(float, input(description).split(','))) if (sides[1] + sides[2]) &lt; sides[0]: print("A triangle cannot be formed.") else: a, b, c = sides print("Area of triangle {0}-{1}-{2} is {3:.4f}".format( sides[0], sides[1], sides[2], heron(a, b, c))) except Exception as e: print("Check your input!!!") print("--&gt; Error: {0}".format(e)) </code></pre> <p>Few notes about this version:</p> <ul> <li>It's parsing your floating-point input values and sorting at the same time, that way you can check directly whether a triangle can be formed or not</li> <li>It's not using the naive heron formula, instead is using another one which is <a href="https://en.wikipedia.org/wiki/Heron%27s_formula" rel="nofollow">numerically stable</a></li> </ul> <p>I've decided to give you another version because in the comments you'll find some good advices about yours</p>
1
2016-09-05T19:22:49Z
[ "python", "python-3.x" ]
How to fix "unsupported operand type(s)" in Python?
39,336,330
<pre><code>total=0 output=("enter next sales value") sales=input total_sales=total+sales </code></pre> <p>I keep getting this error:</p> <blockquote> <p>Traceback (most recent call last): File "python", line 4, in TypeError: unsupported operand type(s) for +: 'int' and 'builtin_function_or_method'</p> </blockquote>
-2
2016-09-05T19:01:26Z
39,336,434
<p>You must use input() instead of input. Moreover in python 3, the input() function returns a string, not an integer. So to use the return value in an addition, you must indicate it as an integer: </p> <pre><code> sales = input("Enter next sales value") total_sales = total + int(sales) </code></pre>
-1
2016-09-05T19:11:20Z
[ "python", "runtime-error" ]
Python 2.7 store duplicate string or not
39,336,347
<p>Wondering if my two cases, whether Python 2.7 stores duplicate string literal <code>Hello</code>, or store one string literal <code>Hello</code>, and store only address to the string literal for duplicate to save space? Thanks.</p> <p>My two cases shows using string literal, and using a string (<code>str</code>) variable.</p> <pre><code>from collections import defaultdict a = defaultdict(list) # case 1 a[1].append("Hello") a[2].append("Hello") # case 2 b = "Hello" a[3].append(b) a[4].append(b) </code></pre>
3
2016-09-05T19:03:14Z
39,336,534
<p>In case 2 you are safe to assume that the same object is being referenced twice, because that's what you explicitly do. Just keep in mind that you always toss around references in Python. At the same time, the first case is a bit more complicated. CPython does optimise memory usage by caching short strings (and small numbers, too), e.g. </p> <pre><code>In [1]: a = "Hello" In [2]: b = "Hello" In [3]: id(a) Out[3]: 4448951296 In [4]: id(b) Out[4]: 4448951296 </code></pre> <p>In other words <code>a is b</code> returns <code>True</code>. But this is not something you can rely on, because the size threshold may differ between different versions and builds. </p> <pre><code>In [8]: c = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks" In [9]: d = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks" In [10]: c is d Out[10]: False </code></pre>
4
2016-09-05T19:21:59Z
[ "python", "python-2.7" ]
Import a whole folder of python files
39,336,356
<p>I am making a bot in python 3 and wish it to be easily expanded so I have a central file and then one for each command. I wish to know if there is a way to import a sub-directory full of modules without importing each separately. For example:</p> <pre><code>example ├── commands │   ├── bar.py │   └── foo.py └── main.py </code></pre> <p>And the code in <code>main.py</code>would be something like:</p> <pre><code>import /commands/* </code></pre> <p>Thanks :D</p> <p><strong>Solution:</strong> Import each separately with: <code>from commands import foo, bar</code></p> <p><code>from commands import *</code> Does not work.</p>
0
2016-09-05T19:03:43Z
39,336,535
<p>If you're using python3, the <code>importlib</code> module can be used to dynamically import modules. On python2.x, there is the <code>__import__</code> function but I'm not very familiar with the semantics. As a quick example, </p> <p>I have 2 files in the current directory</p> <pre><code># a.py name = "a" </code></pre> <p>and</p> <pre><code># b.py name = "b" </code></pre> <p>In the same directory, I have this</p> <pre><code>import glob import importlib for f in glob.iglob("*.py"): if f.endswith("load.py"): continue mod_name = f.split(".")[0] print ("importing {}".format(mod_name)) mod = importlib.import_module(mod_name, "") print ("Imported {}. Name is {}".format(mod, mod.name)) </code></pre> <p>This will print</p> <pre><code>importing b Imported &lt;module 'b' from '/tmp/x/b.py'&gt;. Name is b importing a Imported &lt;module 'a' from '/tmp/x/a.py'&gt;. Name is a </code></pre>
0
2016-09-05T19:22:05Z
[ "python", "python-3.x" ]
Import a whole folder of python files
39,336,356
<p>I am making a bot in python 3 and wish it to be easily expanded so I have a central file and then one for each command. I wish to know if there is a way to import a sub-directory full of modules without importing each separately. For example:</p> <pre><code>example ├── commands │   ├── bar.py │   └── foo.py └── main.py </code></pre> <p>And the code in <code>main.py</code>would be something like:</p> <pre><code>import /commands/* </code></pre> <p>Thanks :D</p> <p><strong>Solution:</strong> Import each separately with: <code>from commands import foo, bar</code></p> <p><code>from commands import *</code> Does not work.</p>
0
2016-09-05T19:03:43Z
39,336,669
<p>Import each separately with: <code>from commands import bar</code> and <code>from commands import foo</code></p> <p><code>from commands import *</code> Does not work.</p>
-2
2016-09-05T19:33:56Z
[ "python", "python-3.x" ]
Python check if value in csv file
39,336,449
<p>i got list of URLs, for example: </p> <pre><code>urls_list = [ "http://yandex.ru", "http://google.ru", "http://rambler.ru", "http://google.ru", "http://gmail.ru", "http://mail.ru" ] </code></pre> <p>I need to open the csv file, check if each value from list in file - skip to next value, else (if value not in a list) add this value in list. </p> <p>Result: 1st run - add all lines (if file is empty), 2nd run - doing nothing, because all elements in already in file. </p> <p>A wrote code, but it's work completely incorrect:</p> <pre><code>import csv urls_list = [ "http://yandex.ru", "http://google.ru", "http://rambler.ru", "http://google.ru", "http://gmail.ru", "http://mail.ru" ] with open('urls_list.csv', 'r') as fp: for row in fp: for url in urls_list: if url in row: print "YEY!" with open('urls_list.csv', 'a+') as fp: wr = csv.writer(fp, dialect='excel') wr.writerow([url]) </code></pre>
-1
2016-09-05T19:13:21Z
39,336,687
<p>Read the file <em>into</em> a variable-</p> <pre><code>with open('urls_list.csv', 'r') as fp: s = fp.read() </code></pre> <p>Check to see if each list item is in the file, if not save it</p> <pre><code>missing = [] for url in urls_list: if url not in s: missing.append(url + '\n') </code></pre> <p>Write the missing url's to the file</p> <pre><code>if missing: with open('urls_list.csv', 'a+') as fp: fp.writelines(missing) </code></pre>
1
2016-09-05T19:35:31Z
[ "python", "loops", "csv", "if-statement" ]
Python check if value in csv file
39,336,449
<p>i got list of URLs, for example: </p> <pre><code>urls_list = [ "http://yandex.ru", "http://google.ru", "http://rambler.ru", "http://google.ru", "http://gmail.ru", "http://mail.ru" ] </code></pre> <p>I need to open the csv file, check if each value from list in file - skip to next value, else (if value not in a list) add this value in list. </p> <p>Result: 1st run - add all lines (if file is empty), 2nd run - doing nothing, because all elements in already in file. </p> <p>A wrote code, but it's work completely incorrect:</p> <pre><code>import csv urls_list = [ "http://yandex.ru", "http://google.ru", "http://rambler.ru", "http://google.ru", "http://gmail.ru", "http://mail.ru" ] with open('urls_list.csv', 'r') as fp: for row in fp: for url in urls_list: if url in row: print "YEY!" with open('urls_list.csv', 'a+') as fp: wr = csv.writer(fp, dialect='excel') wr.writerow([url]) </code></pre>
-1
2016-09-05T19:13:21Z
39,336,719
<p>Considering your file has only one column, the <code>csv</code> module might be an overkill. </p> <p>Here's a version that first reads all the lines from the file and reopens the file to write urls that are not already in the file:</p> <pre><code>lines = open('urls_list.csv', 'r').read() with open('urls_list.csv', 'a+') as fp: for url in urls_list: if url in lines: print "YEY!" else: fp.write(url+'\n') </code></pre>
1
2016-09-05T19:38:18Z
[ "python", "loops", "csv", "if-statement" ]
(Basic?) File compiles fine, doesn't execute as intended
39,336,459
<blockquote> <p>I'm running this on cygwin using atom as my editor. Python3.</p> </blockquote> <p>Hi,</p> <p>Basic Python question that really baffles me. I've looked around on SO and found a lot of questions regarding similiar issues, but can't find one that covers the issue I'm facing.</p> <p>Before I go into details; this is an assignment that I'm working on so if you don't want to spill "all the beans", then just give me some sort of guidance. </p> <p>I've been tasked with splitting a chat-bot into two files, one that handles the main() function and one that handles all the possible functions that the input-choices from main() uses.</p> <p>For some reason both files compile fine, but when I call main.py </p> <blockquote> <p>(either by >python main.py // // // // or by > ./main.py)</p> </blockquote> <p>I get no prompt at all. Neither do I get a prompt while trying the same with marvin.py.</p> <p>Both files are in the same directory.</p> <p>This is main():</p> <pre><code>#!/usr/bin/env python3 import marvin def main(): """ This is the main method, I call it main by convention. Its an eternal loop, until q is pressed. It should check the choice done by the user and call a appropriate function. """ while True: menu() choice = input("--&gt; ") if choice == "q": print("Bye, bye - and welcome back anytime!") return elif choice == "1": myNameIs() elif choice == "2": yearsToSec() elif choice == "3": weightOnMoon() elif choice == "4": minsToHours() elif choice == "5": celToFahr() elif choice == "6": multiplyWord() elif choice == "7": randNumber() elif choice == "8": sumAndAverage() elif choice == "9": gradeFromPoints() elif choice == "10": areaFromRadius() elif choice == "11": calcHypotenuse() elif choice == "12": checkNumber() else: print("That is not a valid choice. You can only choose from the menu.") input("\nPress enter to continue...") if __name__ == "__main__": main() </code></pre> <p>As you can see I do import marvin after the environment-variables have been loaded. There are no indentation errors or anything else when compiling either files (as mentioned above).</p> <p>Disclaimer: I don't think you need to read marvin, tbh...</p> <p>And this is marvin.py:</p> <pre><code>#!/usr/bin/env python3 from random import randint import math def meImage(): """ Store my ascii image in a separat variabel as a raw string """ return r""" _______ _/ \_ / | | \ / |__ __| \ |__/((o| |o))\__| | | | | |\ |_| /| | \ / | \| / ___ \ |/ \ | / _ \ | / \_________/ _|_____|_ ____|_________|____ / \ """ def menu(): """ Display the menu with the options that Marvin can do. """ print(chr(27) + "[2J" + chr(27) + "[;H") print(meImage()) print("Welcome.\nMy name is Ragnar.\nWhat can I do for you?\n") print("1) Present yourself to Ragnar.") print("2) Have Ragnar calculate your minimum age (in seconds).") print("3) Have Ragnar calculate weight on the moon.") print("4) Try Ragnar's abilities by having him calculate minutes to hour(s).") print("5) Have Ragnar calculate Fahrenheit from Celcius.") print("6) See if Ragnar can multiply a word of your liking by a factor of your choice.") print("7) Have Ragnar print 10 numbers within a range of your choice.") print("8) Keep entering numbers and have Ragnar print their sum and average.") print("9) Let Ragnar calculate your grade by entering your score!.") print("10) Let Ragnar calculate the area of a circle with the radius of your choice.") print("11) Let Ragnar calculate the hypotenuse of a triangle with the sides of your choice.") print("12) Have Ragnar compare a given number to your previous number.") print("q) Quit.") def myNameIs(): """ Read the users name and say hello to Marvin. """ name = input("What is your name? ") print("\nMarvin says:\n") print("Hello %s - your awesomeness!" % name) print("What can I do you for?!") def yearsToSec(): """ Calculate your age (years) to seconds """ years = input("How many years are you?\n") seconds = int(years) * (365 * 24 * 60 * 60) print(str(years) + " would give you " + str(seconds) + " seconds.") return def weightOnMoon(): """ Calculate your weight on the moon """ weight = input("What is your weight (in kiloes)?\n") moonGrav = float(weight) * .2 print(str(weight) + " kiloes would weigh be the same as " + str(moonGrav) + " kiloes on the moon.") def minsToHours(): """ Calculate hours from minutes """ minutes = input("How many minutes would you want to converted to hour(s)?\n") hours = float(format(float(minutes) / 60, '.2f')) print(str(minutes) + " hours is " + str(hours) + " hours") def celToFahr(): """ Calculate celcius to Fahrenheit """ cel = input("Please insert Celcius to be calculated to Fahrenheit.\n") fah = float(format(float(cel) * 1.8 + 32, '.2f')) print(str(cel) + " is " + str(fah) + " in Fahrenheit units.") def multiplyWord(): """ Multiply word n-times """ word = input("Please enter the word.\n") factor = input("And please give me the product to multiply it by!") word *= int(factor) print("The word is:\n" + str(word)) def randNumber(): """ Adds 10 random numbers (depending on user range) to a string. """ rangeMin = input("What is the lower number in your range?\n") rangeMax = input("What is the higher number in your range?\n") sequence = "" for num in range(0, 10): sequence += str(randint(int(rangeMin), int(rangeMax))) + ", " num = num print("The random sequence is:\n" + sequence[:-2]) def sumAndAverage(): """ Adds numbers to the sum and calculate the average value of the input(s) """ summa = 0 count = 0 temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n") while True: if temp == "q": print("The sum of your numbers are: " + str(summa) + "\nAnd the average is: " + str(summa/count)) return else: try: summa += int(temp) count += 1 temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n") except ValueError: print("That's not an int! \nPlease try again!") def gradeFromPoints(): """ Shows the user's grade based on his / her points """ points = input("How many points did you score?\n") if(float(points) &gt;= 1 and float(points) &lt;= 100): points = float(points) / 100 if float(points) &gt;= 0.9: print("You got an A!") elif float(points) &gt;= 0.8 and float(points) &lt; 0.9: print("You got a B!") elif float(points) &gt;= 0.7 and float(points) &lt; 0.8: print("You got a C!") elif float(points) &gt;= 0.6 and float(points) &lt; 0.7: print("You got a D!") else: print("You failed the class") def areaFromRadius(): """ Calculates a circles area based on it's radius """ radius = input("What is the circle's radius?\n") area = (float(radius) * float(radius)) * 3.1416 print("The area of the circle is: " + str(format(area, '.2f'))) print("This was calculated with this formula: (radius^2) * 3.1416") def calcHypotenuse(): """ Calculates a triangle's hypotenuse based on it's sides """ side1 = input("How long is the first side?\n") side2 = input("How long is the second side?\n") hypotenuse = math.sqrt((float(side1) * float(side1)) + (float(side2) * float(side2))) print("The hypotenuse is: " + str(hypotenuse)) def compareNumbers(a, b): """ Compares two numbers """ if (a &gt; b): print("Your previous number was larger!") return a elif (a &lt; b): print("Your new number was larger!") return b else: print("They were equal!") return a def validateInt(a): """ Validates that an input is an integer """ if a == 'q': return a else: flag = False while (flag == False): try: a = int(a) flag = True except ValueError: print("That's not an int! \nPlease try again!") a = input("Try again!\n") return a def checkNumber(prev="first"): """ Checks the number """ print("\n=================\n") if prev == "first": prev = validateInt(input("Please input a number. Press 'q' if you wish to end\n")) print("\n=================\n") new = validateInt(input("Please input a number. Press 'q' if you wish to end\n")) if new == 'q' or prev == 'q': print("You have exited the loop\n") return else: compareNumbers(int(prev), int(new)) checkNumber(str(new)) else: new = validateInt(input("Please input a number. Press 'q' if you wish to end\n")) if new == 'q': print("You have exited the loop!\n") return else: compareNumbers(int(prev), int(new)) checkNumber(str(new)) </code></pre> <blockquote> <p>FULL DISCLAIMER: I'm sure there are bunches of improvments I can do, but I'm only interested in understanding why the files won't execute even though they compile fine...</p> </blockquote>
-1
2016-09-05T19:14:20Z
39,336,532
<pre><code>if __name__ == "__main__": main() </code></pre> <p>should not be indented.</p> <p>In your current code, the <code>main()</code> method is run in the <code>else</code> block, but you never get there because the program won't start because you just <strong>define</strong> the <code>main()</code> method but never <strong>execute</strong> it.</p> <p>Unindent it and it will be executed as it won't be in a function definition anymore.</p>
0
2016-09-05T19:21:46Z
[ "python", "import", "atom" ]
(Basic?) File compiles fine, doesn't execute as intended
39,336,459
<blockquote> <p>I'm running this on cygwin using atom as my editor. Python3.</p> </blockquote> <p>Hi,</p> <p>Basic Python question that really baffles me. I've looked around on SO and found a lot of questions regarding similiar issues, but can't find one that covers the issue I'm facing.</p> <p>Before I go into details; this is an assignment that I'm working on so if you don't want to spill "all the beans", then just give me some sort of guidance. </p> <p>I've been tasked with splitting a chat-bot into two files, one that handles the main() function and one that handles all the possible functions that the input-choices from main() uses.</p> <p>For some reason both files compile fine, but when I call main.py </p> <blockquote> <p>(either by >python main.py // // // // or by > ./main.py)</p> </blockquote> <p>I get no prompt at all. Neither do I get a prompt while trying the same with marvin.py.</p> <p>Both files are in the same directory.</p> <p>This is main():</p> <pre><code>#!/usr/bin/env python3 import marvin def main(): """ This is the main method, I call it main by convention. Its an eternal loop, until q is pressed. It should check the choice done by the user and call a appropriate function. """ while True: menu() choice = input("--&gt; ") if choice == "q": print("Bye, bye - and welcome back anytime!") return elif choice == "1": myNameIs() elif choice == "2": yearsToSec() elif choice == "3": weightOnMoon() elif choice == "4": minsToHours() elif choice == "5": celToFahr() elif choice == "6": multiplyWord() elif choice == "7": randNumber() elif choice == "8": sumAndAverage() elif choice == "9": gradeFromPoints() elif choice == "10": areaFromRadius() elif choice == "11": calcHypotenuse() elif choice == "12": checkNumber() else: print("That is not a valid choice. You can only choose from the menu.") input("\nPress enter to continue...") if __name__ == "__main__": main() </code></pre> <p>As you can see I do import marvin after the environment-variables have been loaded. There are no indentation errors or anything else when compiling either files (as mentioned above).</p> <p>Disclaimer: I don't think you need to read marvin, tbh...</p> <p>And this is marvin.py:</p> <pre><code>#!/usr/bin/env python3 from random import randint import math def meImage(): """ Store my ascii image in a separat variabel as a raw string """ return r""" _______ _/ \_ / | | \ / |__ __| \ |__/((o| |o))\__| | | | | |\ |_| /| | \ / | \| / ___ \ |/ \ | / _ \ | / \_________/ _|_____|_ ____|_________|____ / \ """ def menu(): """ Display the menu with the options that Marvin can do. """ print(chr(27) + "[2J" + chr(27) + "[;H") print(meImage()) print("Welcome.\nMy name is Ragnar.\nWhat can I do for you?\n") print("1) Present yourself to Ragnar.") print("2) Have Ragnar calculate your minimum age (in seconds).") print("3) Have Ragnar calculate weight on the moon.") print("4) Try Ragnar's abilities by having him calculate minutes to hour(s).") print("5) Have Ragnar calculate Fahrenheit from Celcius.") print("6) See if Ragnar can multiply a word of your liking by a factor of your choice.") print("7) Have Ragnar print 10 numbers within a range of your choice.") print("8) Keep entering numbers and have Ragnar print their sum and average.") print("9) Let Ragnar calculate your grade by entering your score!.") print("10) Let Ragnar calculate the area of a circle with the radius of your choice.") print("11) Let Ragnar calculate the hypotenuse of a triangle with the sides of your choice.") print("12) Have Ragnar compare a given number to your previous number.") print("q) Quit.") def myNameIs(): """ Read the users name and say hello to Marvin. """ name = input("What is your name? ") print("\nMarvin says:\n") print("Hello %s - your awesomeness!" % name) print("What can I do you for?!") def yearsToSec(): """ Calculate your age (years) to seconds """ years = input("How many years are you?\n") seconds = int(years) * (365 * 24 * 60 * 60) print(str(years) + " would give you " + str(seconds) + " seconds.") return def weightOnMoon(): """ Calculate your weight on the moon """ weight = input("What is your weight (in kiloes)?\n") moonGrav = float(weight) * .2 print(str(weight) + " kiloes would weigh be the same as " + str(moonGrav) + " kiloes on the moon.") def minsToHours(): """ Calculate hours from minutes """ minutes = input("How many minutes would you want to converted to hour(s)?\n") hours = float(format(float(minutes) / 60, '.2f')) print(str(minutes) + " hours is " + str(hours) + " hours") def celToFahr(): """ Calculate celcius to Fahrenheit """ cel = input("Please insert Celcius to be calculated to Fahrenheit.\n") fah = float(format(float(cel) * 1.8 + 32, '.2f')) print(str(cel) + " is " + str(fah) + " in Fahrenheit units.") def multiplyWord(): """ Multiply word n-times """ word = input("Please enter the word.\n") factor = input("And please give me the product to multiply it by!") word *= int(factor) print("The word is:\n" + str(word)) def randNumber(): """ Adds 10 random numbers (depending on user range) to a string. """ rangeMin = input("What is the lower number in your range?\n") rangeMax = input("What is the higher number in your range?\n") sequence = "" for num in range(0, 10): sequence += str(randint(int(rangeMin), int(rangeMax))) + ", " num = num print("The random sequence is:\n" + sequence[:-2]) def sumAndAverage(): """ Adds numbers to the sum and calculate the average value of the input(s) """ summa = 0 count = 0 temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n") while True: if temp == "q": print("The sum of your numbers are: " + str(summa) + "\nAnd the average is: " + str(summa/count)) return else: try: summa += int(temp) count += 1 temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n") except ValueError: print("That's not an int! \nPlease try again!") def gradeFromPoints(): """ Shows the user's grade based on his / her points """ points = input("How many points did you score?\n") if(float(points) &gt;= 1 and float(points) &lt;= 100): points = float(points) / 100 if float(points) &gt;= 0.9: print("You got an A!") elif float(points) &gt;= 0.8 and float(points) &lt; 0.9: print("You got a B!") elif float(points) &gt;= 0.7 and float(points) &lt; 0.8: print("You got a C!") elif float(points) &gt;= 0.6 and float(points) &lt; 0.7: print("You got a D!") else: print("You failed the class") def areaFromRadius(): """ Calculates a circles area based on it's radius """ radius = input("What is the circle's radius?\n") area = (float(radius) * float(radius)) * 3.1416 print("The area of the circle is: " + str(format(area, '.2f'))) print("This was calculated with this formula: (radius^2) * 3.1416") def calcHypotenuse(): """ Calculates a triangle's hypotenuse based on it's sides """ side1 = input("How long is the first side?\n") side2 = input("How long is the second side?\n") hypotenuse = math.sqrt((float(side1) * float(side1)) + (float(side2) * float(side2))) print("The hypotenuse is: " + str(hypotenuse)) def compareNumbers(a, b): """ Compares two numbers """ if (a &gt; b): print("Your previous number was larger!") return a elif (a &lt; b): print("Your new number was larger!") return b else: print("They were equal!") return a def validateInt(a): """ Validates that an input is an integer """ if a == 'q': return a else: flag = False while (flag == False): try: a = int(a) flag = True except ValueError: print("That's not an int! \nPlease try again!") a = input("Try again!\n") return a def checkNumber(prev="first"): """ Checks the number """ print("\n=================\n") if prev == "first": prev = validateInt(input("Please input a number. Press 'q' if you wish to end\n")) print("\n=================\n") new = validateInt(input("Please input a number. Press 'q' if you wish to end\n")) if new == 'q' or prev == 'q': print("You have exited the loop\n") return else: compareNumbers(int(prev), int(new)) checkNumber(str(new)) else: new = validateInt(input("Please input a number. Press 'q' if you wish to end\n")) if new == 'q': print("You have exited the loop!\n") return else: compareNumbers(int(prev), int(new)) checkNumber(str(new)) </code></pre> <blockquote> <p>FULL DISCLAIMER: I'm sure there are bunches of improvments I can do, but I'm only interested in understanding why the files won't execute even though they compile fine...</p> </blockquote>
-1
2016-09-05T19:14:20Z
39,336,768
<p>The functions defined in marvin.py are not globals in main.py; they are members of the marvin module object. So, this:</p> <pre><code>elif choice == "1": myNameIs() </code></pre> <p>should be changed to this:</p> <pre><code>elif choice == "1": marvin.myNameIs() </code></pre> <p>The same goes for the rest of the places where main.py is using functions from marvin.py.</p>
0
2016-09-05T19:42:25Z
[ "python", "import", "atom" ]
Is it possible to upload multiple versions of the same package to pypiserver?
39,336,613
<p>Say you have two different versions of the same package and want to upload them to <code>pypiserver</code> and have clients install the version they want via <code>pip</code>. Is this possible?</p>
0
2016-09-05T19:29:10Z
39,336,706
<p>Yes it is possible.</p> <p>You just upload package twice setting different version (e.g. first <code>0.1</code> and second <code>0.2</code>) in <code>setup.py</code> of your package.</p> <p>Here is instruction how to upload: <a href="http://peterdowns.com/posts/first-time-with-pypi.html" rel="nofollow">http://peterdowns.com/posts/first-time-with-pypi.html</a></p> <p>Then user can install specific version using following command</p> <pre><code>pip install 'package_name==0.1' </code></pre> <p>or</p> <pre><code>pip install 'package_name&lt;=0.1' </code></pre>
0
2016-09-05T19:36:52Z
[ "python" ]
Reusing compiled regular expressions in python
39,336,664
<p>I have a program in Perl that uses a regular expression to store supported file extensions. It reuses this regex through the code. Each file extension has a description since the regular expression has the 'x' flag. I cannot figure out how to port this to python (2.7).</p> <h3>The original Perl</h3> <pre class="lang-perl prettyprint-override"><code>use strict; my @files = ('foo.abc','foo.ABC','foo.mi','foo.txt','foo.ma','foo.iff','foo.avi'); my $exts = qr/abc|mi|avi|ma|iff|tga/; foreach my $f (sort @files) { if ($f =~ m/^([^.]+\.$exts)/) { print "file matches: $f\n"; } else { print "file does not match: $f\n"; } } </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt </code></pre> <p>This works just as well when I add whitespace with the <code>/x</code> modifier</p> <pre class="lang-perl prettyprint-override"><code>$exts = qr/ abc (?# alembic ) |mi (?# mentalray ) |avi (?# windows video ) |ma (?# maya ascii ) |iff (?# amiga bitmap ) |tga (?# targa bitmap ) /ix; foreach my $f (sort @files) { if ( $f =~ m/^([^.]+\.$exts )/ ) { print "file matches: $f\n"; } else { print "file does not match: $f\n"; } } </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file matches: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt </code></pre> <p>Python supports compiled regular expressions, and you can use them as components of other regular expressions</p> <h3>Python</h3> <pre class="lang-python prettyprint-override"><code>import re files = [ 'foo.abc','foo.ABC','foo.mi','foo.txt','foo.ma','foo.iff','foo.avi' ] exts = re.compile(r'(?:abc|mi|avi|ma|iff|tga)') for f in sorted(files): m = re.search(r'^([^.]+\.{EXTS})'.format(EXTS=exts.pattern),f) if m: print 'file matches: {0}'.format(f) else: print 'file does not match: {0}'.format(f) </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt ''' </code></pre> <p>But as soon as I use <code>re.VERBOSE</code>, the regex fails</p> <pre class="lang-python prettyprint-override"><code>exts = re.compile(r'''(?: abc # alembic |mi # mentalray |avi # windows video |ma # maya ascii |iff # amiga bitmap |tga # targa bitmap )''', re.IGNORECASE + re.VERBOSE) for f in sorted(files): m = re.search(r'^([^.]+\.{EXTS})'.format(EXTS=exts.pattern),f) if m: print 'file matches: {0}'.format(f) else: print 'file does not match: {0}'.format(f) </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file does not match: foo.abc file does not match: foo.avi file does not match: foo.iff file does not match: foo.ma file does not match: foo.mi file does not match: foo.txt </code></pre> <p>My actual code has more than 50 extensions, with comments about what they are, so I would really like to support this.</p> <p>I've searched all the "nested regular expression" posts I could find, but all of them are string hacks. No <em>actual</em> regular expression nesting that I can find. </p> <p>Can Python do this?</p>
1
2016-09-05T19:33:01Z
39,336,738
<p>You are doing this completely wrong. First of all the <code>.pattern</code> attribute is just <strong>a string</strong>. So it's 100% useless calling <code>re.compile</code> and then extracting the initial string used to obtain the regex object to pass to <code>re.search</code>:</p> <pre><code>&gt;&gt;&gt; regex = re.compile(r'''( ... verbose #lol ... | pattern #rofl ... ) ... ''', re.VERBOSE) &gt;&gt;&gt; regex.match('verbose') # finds the match! &lt;_sre.SRE_Match object; span=(0, 7), match='verbose'&gt; &gt;&gt;&gt; re.search(regex.pattern, 'verbose') # does not find the match! &gt;&gt;&gt; </code></pre> <p>As you can see the <code>pattern</code> attribute is just the <strong>initial</strong> string used to build the regex object:</p> <pre><code>&gt;&gt;&gt; regex.pattern '(\n verbose #lol\n | pattern #rofl\n)\n' &gt;&gt;&gt; type(regex.pattern) &lt;class 'str'&gt; </code></pre> <p>So by passing this into <code>re.search</code> you make <code>re.search</code> <em>recompile</em> it, and since <code>re.search</code> doesn't have the <code>re.VERBOSE</code> flag it compiles it with a different meaning:</p> <pre><code>&gt;&gt;&gt; re.search(regex.pattern, 'verbose', re.VERBOSE) &lt;_sre.SRE_Match object; span=(0, 7), match='verbose'&gt; </code></pre> <p>Also, I'd do this instead:</p> <pre><code>exts = [ 'abc', # extension abc blah blah 'cde', # extension cde blah blah ] exts_pattern = '(?:{})'.format('|'.join(re.escape(extension) for extension in exts)) regex = re.compile(r'^([^.]+\.{}'.format(exts_pattern), re.IGNORECASE) </code></pre> <p>Or similar. I.e. you keep the various extensions as a <code>list</code> and put whatever python comments you want, and when you build the regex object using <code>compile</code> you iterate over those. This makes adding an extension easier, and also it's probably useful to have such list anyways.</p> <hr> <p>And to answer your final question: no python <code>re</code> module does not support "regex nesting" in any way. You must provide a <em>string</em> pattern which gets compiled into a regex object.</p>
4
2016-09-05T19:39:38Z
[ "python", "regex", "python-2.7", "perl" ]
Reusing compiled regular expressions in python
39,336,664
<p>I have a program in Perl that uses a regular expression to store supported file extensions. It reuses this regex through the code. Each file extension has a description since the regular expression has the 'x' flag. I cannot figure out how to port this to python (2.7).</p> <h3>The original Perl</h3> <pre class="lang-perl prettyprint-override"><code>use strict; my @files = ('foo.abc','foo.ABC','foo.mi','foo.txt','foo.ma','foo.iff','foo.avi'); my $exts = qr/abc|mi|avi|ma|iff|tga/; foreach my $f (sort @files) { if ($f =~ m/^([^.]+\.$exts)/) { print "file matches: $f\n"; } else { print "file does not match: $f\n"; } } </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt </code></pre> <p>This works just as well when I add whitespace with the <code>/x</code> modifier</p> <pre class="lang-perl prettyprint-override"><code>$exts = qr/ abc (?# alembic ) |mi (?# mentalray ) |avi (?# windows video ) |ma (?# maya ascii ) |iff (?# amiga bitmap ) |tga (?# targa bitmap ) /ix; foreach my $f (sort @files) { if ( $f =~ m/^([^.]+\.$exts )/ ) { print "file matches: $f\n"; } else { print "file does not match: $f\n"; } } </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file matches: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt </code></pre> <p>Python supports compiled regular expressions, and you can use them as components of other regular expressions</p> <h3>Python</h3> <pre class="lang-python prettyprint-override"><code>import re files = [ 'foo.abc','foo.ABC','foo.mi','foo.txt','foo.ma','foo.iff','foo.avi' ] exts = re.compile(r'(?:abc|mi|avi|ma|iff|tga)') for f in sorted(files): m = re.search(r'^([^.]+\.{EXTS})'.format(EXTS=exts.pattern),f) if m: print 'file matches: {0}'.format(f) else: print 'file does not match: {0}'.format(f) </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt ''' </code></pre> <p>But as soon as I use <code>re.VERBOSE</code>, the regex fails</p> <pre class="lang-python prettyprint-override"><code>exts = re.compile(r'''(?: abc # alembic |mi # mentalray |avi # windows video |ma # maya ascii |iff # amiga bitmap |tga # targa bitmap )''', re.IGNORECASE + re.VERBOSE) for f in sorted(files): m = re.search(r'^([^.]+\.{EXTS})'.format(EXTS=exts.pattern),f) if m: print 'file matches: {0}'.format(f) else: print 'file does not match: {0}'.format(f) </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file does not match: foo.abc file does not match: foo.avi file does not match: foo.iff file does not match: foo.ma file does not match: foo.mi file does not match: foo.txt </code></pre> <p>My actual code has more than 50 extensions, with comments about what they are, so I would really like to support this.</p> <p>I've searched all the "nested regular expression" posts I could find, but all of them are string hacks. No <em>actual</em> regular expression nesting that I can find. </p> <p>Can Python do this?</p>
1
2016-09-05T19:33:01Z
39,338,497
<p>It is a myth that Perl will interpolate one compiled regular expression into another. If you write this</p> <pre><code>my $exts = qr/ abc | mi | avi | ma | iff | tga /x; if ( $f =~ /^([^.]+\.$exts)/ ) { ... } </code></pre> <p>then within <code>$f =~ /^([^.]+\.$exts)/</code>, the contents of the regex pattern is evaluated in a <em>double-quote context</em>. That means Perl will <em>stringify</em> <code>$exts</code> to something like <code>(?^x: abc | mi | avi | ma | iff | tga )</code> (the exact result depends on what Perl pragma are in place) and <em>interpolate</em> that string before compiling the pattern</p> <p>So the regex match is actually doing this</p> <pre><code>$f =~ /^([^.]+\.(?^x: abc | mi | avi | ma | iff | tga ))/ </code></pre> <p>which is clearly correct, because the <code>/x</code> modifier is enabled within the expression</p> <p>The difference from Python is <strong><em>only</em></strong> that Python is not as careful about what an <code>re</code> object returns by its <code>pattern</code> or <code>__str__</code> methods, so they can't be injected as substrings into other patterns</p> <p>As far as I know, the <code>pattern</code> method just returns the original regex string that was compiled to create the object. That makes it much like using C <code>#define</code> symbols: you must be very careful with parentheses, either in the definition of the original or in its invocation</p>
1
2016-09-05T22:46:31Z
[ "python", "regex", "python-2.7", "perl" ]
Reusing compiled regular expressions in python
39,336,664
<p>I have a program in Perl that uses a regular expression to store supported file extensions. It reuses this regex through the code. Each file extension has a description since the regular expression has the 'x' flag. I cannot figure out how to port this to python (2.7).</p> <h3>The original Perl</h3> <pre class="lang-perl prettyprint-override"><code>use strict; my @files = ('foo.abc','foo.ABC','foo.mi','foo.txt','foo.ma','foo.iff','foo.avi'); my $exts = qr/abc|mi|avi|ma|iff|tga/; foreach my $f (sort @files) { if ($f =~ m/^([^.]+\.$exts)/) { print "file matches: $f\n"; } else { print "file does not match: $f\n"; } } </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt </code></pre> <p>This works just as well when I add whitespace with the <code>/x</code> modifier</p> <pre class="lang-perl prettyprint-override"><code>$exts = qr/ abc (?# alembic ) |mi (?# mentalray ) |avi (?# windows video ) |ma (?# maya ascii ) |iff (?# amiga bitmap ) |tga (?# targa bitmap ) /ix; foreach my $f (sort @files) { if ( $f =~ m/^([^.]+\.$exts )/ ) { print "file matches: $f\n"; } else { print "file does not match: $f\n"; } } </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file matches: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt </code></pre> <p>Python supports compiled regular expressions, and you can use them as components of other regular expressions</p> <h3>Python</h3> <pre class="lang-python prettyprint-override"><code>import re files = [ 'foo.abc','foo.ABC','foo.mi','foo.txt','foo.ma','foo.iff','foo.avi' ] exts = re.compile(r'(?:abc|mi|avi|ma|iff|tga)') for f in sorted(files): m = re.search(r'^([^.]+\.{EXTS})'.format(EXTS=exts.pattern),f) if m: print 'file matches: {0}'.format(f) else: print 'file does not match: {0}'.format(f) </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file matches: foo.abc file matches: foo.avi file matches: foo.iff file matches: foo.ma file matches: foo.mi file does not match: foo.txt ''' </code></pre> <p>But as soon as I use <code>re.VERBOSE</code>, the regex fails</p> <pre class="lang-python prettyprint-override"><code>exts = re.compile(r'''(?: abc # alembic |mi # mentalray |avi # windows video |ma # maya ascii |iff # amiga bitmap |tga # targa bitmap )''', re.IGNORECASE + re.VERBOSE) for f in sorted(files): m = re.search(r'^([^.]+\.{EXTS})'.format(EXTS=exts.pattern),f) if m: print 'file matches: {0}'.format(f) else: print 'file does not match: {0}'.format(f) </code></pre> <h3>output</h3> <pre class="lang-none prettyprint-override"><code>file does not match: foo.ABC file does not match: foo.abc file does not match: foo.avi file does not match: foo.iff file does not match: foo.ma file does not match: foo.mi file does not match: foo.txt </code></pre> <p>My actual code has more than 50 extensions, with comments about what they are, so I would really like to support this.</p> <p>I've searched all the "nested regular expression" posts I could find, but all of them are string hacks. No <em>actual</em> regular expression nesting that I can find. </p> <p>Can Python do this?</p>
1
2016-09-05T19:33:01Z
39,352,721
<p>Yes, it can! In the Python documentation on re I found that you can specify any re flag in the expression itself - similar to how Perl prints the re flag inline. By adding the flag to the string hack you can achieve the result:</p> <pre><code>exts = '''(?ix)(?: abc # alembic |mi # mentalray |avi # windows video |ma # maya ascii |iff # amiga bitmap |tga # targa bitmap )''' for f in sorted(files): m = re.search(r'^([^.]+\.{EXTS})'.format(EXTS=exts),f) if m: print 'file matches: {0}'.format(f) else: print 'file does not match: {0}'.format(f) </code></pre> <p>The <code>(?ix)</code> is non-grouping, but sets the re.IGNORECASE and re.VERBOSE.</p>
0
2016-09-06T15:26:58Z
[ "python", "regex", "python-2.7", "perl" ]
Get lag with cross-correlation?
39,336,727
<p>Let's say have have two signals:</p> <pre><code>import numpy dt = 0.001 t_steps = np.arange(0, 1, dt) a_sig = np.sin(2*np.pi*t_steps*4+5) b_sig = np.sin(2*np.pi*t_steps*4) </code></pre> <p>I want to shift the first signal to match the second signal. I know this can be completed using cross-correlation, as evidenced by Matlab, but how do I accomplish this with SciPy.</p>
0
2016-09-05T19:38:57Z
39,336,728
<p>As defined in <a href="https://en.wikipedia.org/wiki/Cross-correlation#Time_delay_analysis" rel="nofollow">this Wikipedia article</a>, the lag between signals is given by the argmax of the cross-correlation. Consequently, the following code will shift the <code>b_sig</code> to be in phased with <code>a_sig</code> to minimize the error.</p> <pre><code>from scipy.signal import correlate lag = np.argmax(correlate(a_sig, b_sig)) c_sig = np.roll(b_sig, shift=int(np.ceil(lag))) </code></pre>
0
2016-09-05T19:38:57Z
[ "python", "numpy", "scipy", "signal-processing" ]
child_process spawnSync iterate python stdout results using for loop
39,336,754
<p>First I will post my code,</p> <p>I will give an example of what I am facing problem: </p> <pre><code> for(var i=0;i&lt;arrayleng.length;i++){ var oneScript = spawnSync('python',["/home/demo/mypython.py",arrayleng[i].path]); //console.log(String(oneScript.stdout)); fs.readFile('/home/demo/' + arrayleng[i].filename + '.json','utf8',function(err,data){ if(err){ console.log(err); }else{ console.log(data); } }) }; </code></pre> <p>I want spawn child to synchronous only because, my python scripts will return some files, it has to read after each time it executes python script. But now it is reading once after it completes execution of python.And printing it on console at once.Instead of printing after each time it executes python script.</p>
3
2016-09-05T19:41:05Z
39,336,906
<p>Here is a nodejs example:</p> <pre><code>var fs = require('fs') var checkThese = ['/Users/jmunsch/Desktop/code_scraps/1.json', '/Users/jmunsch/Desktop/code_scraps/2.json'] checkThese.forEach(function(checkThisPath){ // Both of these will log first console.log(`run first: ${checkThisPath}`) var data = fs.readFileSync(checkThisPath, 'utf8') var theJson = data console.log(`run first: ${theJson}`) // it might make sense that this would execute next // but it doesn't fs.readFile(checkThisPath, 'utf8', function(err, data){ // this callback executes later console.log(`run second: ${checkThisPath}`) console.log(`run second: ${data}`) }) }) </code></pre> <p>Here is an example of a python script and a nodejs script and how they might work.</p> <p>The python script <code>listdir.py</code>:</p> <pre><code>import os import sys for x in os.listdir(sys.argv[1]): print(x) </code></pre> <p>Notes on the above script, I used <code>print</code> which appends a <code>\n</code> character after each line. If you plan to <code>write</code> a file to <code>stdout</code> using python's <code>sys.stdout.write</code> it will not add a newline character. </p> <p>The nodejs code:</p> <pre><code>var child_process = require('child_process'); var spawnSync = child_process.spawnSync var checkThese = ['/Users', '/Users/jmunsch'] for (var i=0; i &lt; checkThese.length;i++){ var checkThisPath = checkThese[i] console.log(`Checking: ${checkThisPath}`) var oneScript = spawnSync('python',["listdir.py", checkThisPath]); oneScript.output.forEach(function(buffer){ if (buffer){ // convert to string var x = buffer.toString('utf8') console.log(`typeof x: ${typeof x}`) // split by new line character var y = x.split('\n') console.log(`typeof y: ${typeof y}`) // turn it into an array var z = Array.prototype.slice.call(y) // iterate each line in the array z.forEach(function(pythonOutput){ console.log(`One python print(): ${pythonOutput}`) }) } }) } </code></pre> <p>The output from from the nodejs code:</p> <pre><code>Checking: /Users typeof x: string typeof y: object One python print(): .localized One python print(): administrator One python print(): casperadministrator One python print(): jmunsch One python print(): Shared One python print(): typeof x: string typeof y: object One python print(): Checking: /Users/jmunsch typeof x: string typeof y: object One python print(): .account One python print(): .ansible One python print(): .bash_sessions One python print(): .cache One python print(): .CFUserTextEncoding One python print(): .config One python print(): .cups One python print(): .DS_Store One python print(): .eclipse One python print(): .gitconfig One python print(): .ipython One python print(): .lesshst One python print(): .lldb One python print(): .local One python print(): .m2 One python print(): .netrc One python print(): .node-gyp One python print(): .node_repl_history One python print(): .npm One python print(): .nvm One python print(): .oh-my-zsh One python print(): .oracle_jre_usage One python print(): .p2 One python print(): .profile One python print(): .putty One python print(): .python-eggs One python print(): .rediscli_history One python print(): .RSA One python print(): .sh_history One python print(): .ssh One python print(): .swift One python print(): .tooling One python print(): .Trash One python print(): .vagrant.d One python print(): .viminfo One python print(): .wget-hsts One python print(): .zcompdump-LM-SFA-11003286-5.0.8 One python print(): .zsh-update One python print(): .zsh_history One python print(): .zshrc One python print(): Applications One python print(): Desktop One python print(): Documents One python print(): Downloads One python print(): eclipse One python print(): git One python print(): Library One python print(): Movies One python print(): Music One python print(): Pictures One python print(): Public One python print(): synced One python print(): THEBIGPIN One python print(): VirtualBox VMs One python print(): typeof x: string typeof y: object One python print(): </code></pre>
1
2016-09-05T19:53:18Z
[ "javascript", "python", "node.js" ]