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
How to use css styling in html with multiple directories?
39,282,466
<p>I'm trying to make a simple webapp using Google Appengine with Python, HTML, and CSS. I know that to put a .css styling from separate file into html one should use a link tag, however I can't seem to get it to work. Here is the general directory config:</p> <p>Main<br> ├── app.yaml<br> ├── files.py<br> ├── Folder<br> │ ├── files.py<br> │ ├── Templates<br> │ │ ├── form.html<br> │ ├── Static<br> │ │ ├── style.css<br></p> <p>"form.html" contains the layout and "style.css" contains styling. I tried putting in the code from "style.css" directly into "form.html" with a style tag and it worked, however when I use the link tag in the head section of the html file it doesn't work. Here is what link tags I tried so far:<br></p> <pre><code>&lt;head&gt; &lt;link type="text/css" rel="stylesheet" href="/Static/style.css"&gt; &lt;title&gt; ... &lt;/title&gt; &lt;/head&gt; </code></pre> <p>or<br></p> <pre><code>&lt;head&gt; &lt;link type="text/css" rel="stylesheet" href="/Folder/Static/style.css"&gt; &lt;title&gt; ... &lt;/title&gt; &lt;/head&gt; </code></pre> <p>or<br></p> <pre><code>&lt;head&gt; &lt;link type="text/css" rel="stylesheet" href="/Main/Folder/Static/style.css"&gt; &lt;title&gt; ... &lt;/title&gt; &lt;/head&gt; </code></pre> <p>None of these work, what could be a solution?</p>
0
2016-09-01T23:54:16Z
39,282,934
<p>You need a url handler in your app.yaml:</p> <pre><code>- url: /Static static_dir: Static/ secure: optional </code></pre> <p>I am not sure about your directory tree. If Static is nested inside Folder, then it would be:</p> <pre><code>- url: /Folder/Static static_dir: Folder/Static/ secure: optional </code></pre> <p>Or, if Static is nested inside Folder, and you want to simplify your html links, then:</p> <pre><code>- url: /Static # &lt;== what url to handle static_dir: Folder/Static/ # &lt;== where to point that url secure: optional </code></pre> <p>and you can access by:</p> <pre><code>&lt;link type="text/css" rel="stylesheet" href="/Static/style.css"&gt; </code></pre>
0
2016-09-02T01:05:54Z
[ "python", "html", "css", "google-app-engine" ]
Passing an object method to an external function in python
39,282,483
<p>Ok, so the task Im trying to accomplish is a bit dense to post in full here, but Ive written an example that shows what Im trying to do.</p> <pre><code>import random class Dog: def __init__(self, height, weight, length, age): self.Height = height self.Weight = weight self.Length = length self.Age = age def getAge(self): return self.Age ## the real version would have a lot more methods that return the ## stats for this object def getStatMean(doggies, statCall): output = 0.0 for dog in doggies: output += dog.statCall() output /= float(len(doggies)) return output if(__name__ == "__main__"): doggies = [] for i in range(0, 100): doggies.append(Dog(10, 20, 30, random.random()*10)) print getStatMean(doggies, Dog.getAge) </code></pre> <p>essentially my problem is that I have a list of objects. These objects all have a large number of stat calls that I am looking to manipulate in the same way (in this case calculate a mean, but the actual example is more complex).</p> <p>The simplest way of doing this would be to write a getStatMean function for each one of the methods that the object has, but this starts to grow out of control as I add more and more methods to the object. I want to be able to pass the method name to one function, and call the method name that was passed on each object like in the example.</p> <p>When I try to run the snippet posted above, I get</p> <blockquote> <p>Traceback (most recent call last): File "example.py", line 39, in print getStatMean(doggies, Dog.getAge) File "example.py", line 26, in getStatMean output += dog.statCall() AttributeError: Dog instance has no attribute 'statCall'</p> </blockquote> <p>Is what I am trying to do possible in python, or am I approaching this problem the wrong way?</p>
1
2016-09-01T23:56:54Z
39,282,692
<p>FIrst of all : methods of instance are named <strong>methods</strong> because they are in fact <strong>bound function</strong> thats mean python is automatically passing to them it first param which is instance on which You call them. So if you are acessing method from class You must provide this <em>self</em> by yourself. And use just function without class. so call should look like this :</p> <pre><code>output += statCall(dog) </code></pre>
1
2016-09-02T00:29:35Z
[ "python", "methods" ]
Python list to csv throws error: iterable expected, not numpy.int64
39,282,516
<p>I want to write a list into a csv,When trying to do it I receive the below error </p> <pre><code>out.writerows(fin_city_ids) _csv.Error: iterable expected, not numpy.int64 </code></pre> <p>My code is as below </p> <pre><code>org_id.append([pol_id,bldest_id]) fin_ids=list(org_city_id['org_id'].unique()) print(fin_ids) out = csv.writer(open("D:/dataset/fin_ids.csv","w"), delimiter='|') out.writerows(fin_ids) </code></pre> <p>Below is the output from fin_ids</p> <pre><code>[1002774, 0, 1000702, 1000339, 1001620, 1000710, 1000202, 1003143, 147897, 31018, 1001502, 1002812, 1003026, 1003280, 1003289, 1002714, 133191, 5252218, 6007821, 1002632] </code></pre> <p>Org_id is a dataFrame which contains duplicate ids .fin_ids is a list which contains unqiue values of ids .Fin ID is a list of unique ids derived from the data frame org_id.</p> <p>output desired is a CSV with all the values in separate rows as I am going to load the data into a sql table later .</p>
1
2016-09-02T00:00:34Z
39,282,731
<p>You can get this done in many ways. But if you wish to <code>writerows</code> from the <code>csv</code> module, then you will have to turn your list <code>fin_ids</code> into a sequence of lists first:</p> <pre><code>fin_ids = [1002774, 0, 1000702, 1000339, 1001620, 1000710, 1000202, 1003143, 147897, 31018, 1001502, 1002812, 1003026, 1003280, 1003289, 1002714, 133191, 5252218, 6007821, 1002632] outfile = open('D:/dataset/fin_ids.csv','w') out = csv.writer(outfile) out.writerows(map(lambda x: [x], fin_ids)) outfile.close() </code></pre> <p>Another way would be to just use the <code>.to_csv()</code> method from pandas <code>Series</code>. Since you started with a dataframe, you could just do:</p> <pre><code>org_city_id['org_id'].unique().to_csv("D:/dataset/fin_ids.csv", index=False) </code></pre> <p>Both of these should generate a csv file with the following data:</p> <pre><code>1002774 0 1000702 1000339 1001620 1000710 1000202 1003143 147897 31018 1001502 1002812 1003026 1003280 1003289 1002714 133191 5252218 6007821 1002632 </code></pre>
3
2016-09-02T00:36:51Z
[ "python", "csv" ]
python importing file on virtual environment
39,282,612
<p>I am writing a web app using python3, venv and c9.io PAAS. I have the following structure of my code:</p> <pre><code>batch_runner.py logic/ __init__.py parsers/ __init__.py time_parser.py abstract_parser.py </code></pre> <p>here <code>batch_runner</code> imports <code>abstract_parser</code>, which, in it turn, import from time_parser. everything was installed and runs with venv activated.</p> <p>To be specific, <code>batch_runner.py</code> contains:</p> <pre><code>from logic.parsers import abstract from sys import argv url = argv[1] a = abstract(url) </code></pre> <p><code>logic/__init__.py</code> is empty. <code>logic/parsers/__init__.py</code> contains:</p> <pre><code>from abstract_parser import abstract from time_parser import _timeInfo </code></pre> <p>If I go to <code>logic</code> and run <code>python abstract_parser.py</code> directly, everything works as expected. However, if I go one level up, and run <code>python batch_runner.py</code>, it is able to import <code>abstract_parser</code>, but it can't find <code>time_parser</code> which is called from <code>abstract_parser</code>, throwing <code>ImportError: No module named 'abstract'</code></p>
2
2016-09-02T00:14:33Z
39,283,243
<p>Change this:</p> <pre><code>from abstract_parser import abstract </code></pre> <p>To</p> <pre><code>from logic.parsers.abstract_parser import abstract </code></pre>
2
2016-09-02T01:56:32Z
[ "python", "python-venv", "c9.io" ]
python importing file on virtual environment
39,282,612
<p>I am writing a web app using python3, venv and c9.io PAAS. I have the following structure of my code:</p> <pre><code>batch_runner.py logic/ __init__.py parsers/ __init__.py time_parser.py abstract_parser.py </code></pre> <p>here <code>batch_runner</code> imports <code>abstract_parser</code>, which, in it turn, import from time_parser. everything was installed and runs with venv activated.</p> <p>To be specific, <code>batch_runner.py</code> contains:</p> <pre><code>from logic.parsers import abstract from sys import argv url = argv[1] a = abstract(url) </code></pre> <p><code>logic/__init__.py</code> is empty. <code>logic/parsers/__init__.py</code> contains:</p> <pre><code>from abstract_parser import abstract from time_parser import _timeInfo </code></pre> <p>If I go to <code>logic</code> and run <code>python abstract_parser.py</code> directly, everything works as expected. However, if I go one level up, and run <code>python batch_runner.py</code>, it is able to import <code>abstract_parser</code>, but it can't find <code>time_parser</code> which is called from <code>abstract_parser</code>, throwing <code>ImportError: No module named 'abstract'</code></p>
2
2016-09-02T00:14:33Z
39,283,449
<p>Do read about importing from the <a href="https://docs.python.org/2/tutorial/modules.html#packages" rel="nofollow">python documentation</a> on modules.</p> <p>In this case, one possible solution is to use relative imports inside your package:</p> <p>That is, in <code>logic/parsers/__init__.py</code>, use:</p> <pre><code>from .abstract_parser import abstract from .time_parser import _timeInfo </code></pre> <p>and in <code>abstract_parser.py</code>:</p> <pre><code>from .time_parser import _timeInfo </code></pre> <p>This should let <code>parsers/__init__.py</code> find the <code>abstract_parser</code> module and the <code>time_parser</code> module.</p> <p>The python import system has a surprising number of traps that you can fall into. <a href="http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html" rel="nofollow">This blog post</a> by Nick Coghlan describes many of them, and I personally consider it a must-read if you're planning to develop a package.</p>
2
2016-09-02T02:27:10Z
[ "python", "python-venv", "c9.io" ]
JSON dump for User defined class in python
39,282,652
<p>Here is how I want my data to be : (key=name, value=[dob,[misc1, misc2,..]])</p> <pre><code> # my sample code inputNames = [ ('james', ['1990-01-19', ['james1', 'james2', 'james3'] ]), ('julie', ['1991-08-07', ['julie1', 'julie2'] ]), ('mikey', ['1989-01-23', ['mikey1'] ]), ('sarah', ['1988-02-05', ['sarah1', 'sarah2', 'sarah3', 'sarah4'] ]) ] class empData (list): def __init__ (self, misc=None): list.__init__([]) # print('add empdata: ',misc[0],misc[1]) self.dob = misc[0] self.extend(misc[1]) def edprint(self): return(self.dob, self) class myEmp(): def __init__ (self, anm, amisc=None): self.nm = anm self.details = empData(amisc) def printme(self): print(self.nm, self.details.edprint()) emps={} for i in inputNames: m = myEmp(i[0],i[1]) emps[m] = m print(emps) # prints addresses of variables # for actual data use the following lines for ea in emps: emps[ea].printme() try: with open('data.json','w') as wfd: json.dump(emps, wfd) except IOError as ioerr: print('File error: ',str(ioerr)) wfd.close() </code></pre> <p>The above gives me an error: TypeError: key &lt;<strong>main</strong>.myEmp object at 0x10143d588> is not a string I am unable to figure out how to dump my dict of myEmp data structures as JSON</p>
1
2016-09-02T00:22:57Z
39,282,881
<p>Before you can dump to <code>json</code> you need explicitly convert your data to a serializable type like <code>dict</code> or <code>list</code>. You could do this using a list comprehension:</p> <pre><code>&gt;&gt;&gt; d = [{'key':ea.nm, 'value':[ea.details.dob, ea.details]} for ea in emps] &gt;&gt;&gt; json.dumps(d) '[{"value": ["1991-08-07", ["julie1", "julie2"]], "key": "julie"}, {"value": ["1989-01-23", ["mikey1"]], "key": "mikey"}, {"value": ["1990-01-19", ["james1", "james2", "james3"]], "key": "james"}, {"value": ["1988-02-05", ["sarah1", "sarah2", "sarah3", "sarah4"]], "key": "sarah"}]' </code></pre>
0
2016-09-02T00:57:52Z
[ "python", "json", "dictionary", "dump", "user-defined-types" ]
Parsing key-value log in Python
39,282,736
<p>I have a system log that looks like the following:</p> <pre><code>{ a = 1 b = 2 c = [ x:1, y:2, z:3, ] d = 4 } </code></pre> <p>I want to parse this in Python into a dictionary object with = splitting key-value pairs. At the same time, the array that is enclosed by [] is also preserved. I want to keep this as generic as possible so the parsing can also hold some future variations.</p> <p>What I tried so far (code will be written): split each line by "=" into key-value pair, determine where [ and ] starts and end and then split the lines in between by ":" into key-value pairs. That seems a little hard-coded.. Any better idea?</p>
0
2016-09-02T00:37:16Z
39,283,017
<p>There is probably a better answer, but I would take advantage of all your dictionary keys being at the same indentation level. There's not an obvious way to be to do this with newline splitting, JSON loading, or that sort of thing since the list structure is a bit weird (it seems like a cross between a list and a dictionary).</p> <p>Here's an implementation that parses keys based on indentation level:</p> <pre><code>import re log = '''{ a = 1 b = 2 c = [ x:1, y:2, z:3, ] d = 4 }''' log_lines = log.split('\n')[1:-1] # strip bracket lines KEY_REGEX = re.compile(r' [^ ]') d = {} current_pair = '' for i, line in enumerate(log_lines): if KEY_REGEX.match(line): if current_pair: key, value = current_pair.split('=') d[key.strip()] = value.strip() current_pair = line else: current_pair += line.strip() if current_pair: key, value = current_pair.split('=') d[key.strip()] = value.strip() print(d) </code></pre> <p><strong>Output</strong>:</p> <pre><code>{'d': '4', 'c': '[x:1,y:2,z:3,]', 'a': '1', 'b': '2'} </code></pre>
1
2016-09-02T01:19:52Z
[ "python" ]
Parsing key-value log in Python
39,282,736
<p>I have a system log that looks like the following:</p> <pre><code>{ a = 1 b = 2 c = [ x:1, y:2, z:3, ] d = 4 } </code></pre> <p>I want to parse this in Python into a dictionary object with = splitting key-value pairs. At the same time, the array that is enclosed by [] is also preserved. I want to keep this as generic as possible so the parsing can also hold some future variations.</p> <p>What I tried so far (code will be written): split each line by "=" into key-value pair, determine where [ and ] starts and end and then split the lines in between by ":" into key-value pairs. That seems a little hard-coded.. Any better idea?</p>
0
2016-09-02T00:37:16Z
39,283,252
<p>This could be pretty easily simplified to YAML. <code>pip install pyyaml</code>, then set up like so:</p> <pre><code>import string, yaml data = """ { a = 1 b = 2 c = [ x:1, y:2, z:3, ] d = 4 } """ </code></pre> <p>With this setup, you can use the following to parse your data:</p> <pre><code>data2 = data.replace(":", ": ").replace("=", ":").replace("[","{").replace("]","}") lines = data2.splitlines() for i, line in enumerate(lines): if len(line)&gt;0 and line[-1] in string.digits and not line.endswith(",") or i &lt; len(lines) - 1 and line.endswith("}"): lines[i] += "," data3 = "\n".join(lines) yaml.load(data3) # {'a': 1, 'b': 2, 'c': {'x': 1, 'y': 2, 'z': 3}, 'd': 4} </code></pre> <hr> <h1>Explanation</h1> <p>In the first line, we perform some simple substitutions:</p> <ul> <li>YAML requires that there is a space after colons in key/value pairs. So with <code>replace(":", ": ")</code>, we can ensure this.</li> <li>Since YAML key/value pairs are always denoted by a colon and your format sometimes uses equals signs, we replace equal signs with commas using <code>.replace("=", ":")</code></li> <li>Your format sometimes uses square brackets where curly brackets should be used in YAML. We fix using <code>.replace("[","{").replace("]","}")</code></li> </ul> <p>At this point, your data looks like this:</p> <pre><code>{ a : 1 b : 2 c : { x: 1, y: 2, z: 3, } d : 4 } </code></pre> <p>Next, we have a <code>for</code> loop. This is simply responsible for adding commas after lines where they're missing. The two cases in which for loops are missing are: - They're absent after a numeric value - They're absent after a closing bracket</p> <p>We match the first of these cases using <code>len(line)&gt;0 and line[-1] in string.digits</code> (the last character in the line is a digit)</p> <p>The second case is matched using <code>i &lt; len(lines) - 1 and line.endswith("}")</code>. This checks if the line ends with <code>}</code>, and also checks that the line is not the last, since YAML won't allow a comma after the last bracket.</p> <p>After the loop, we have:</p> <pre><code>{ a : 1, b : 2, c : { x: 1, y: 2, z: 3, }, d : 4, } </code></pre> <p>which is valid YAML. All that's left is <code>yaml.load</code>, and you've got yourself a python <code>dict</code>.</p> <p>If anything isn't clear please leave a comment and I'll happily elaborate.</p>
0
2016-09-02T01:57:15Z
[ "python" ]
How can I tell/specify which version of the postgres client/libs psycopg2 is using?
39,282,745
<p>I have psycopg2 for a python program, but the computer the program is running on has two version of postgres installed: 9.2 in the 'main' system, and 9.5 in /opt. The postgres DB is hosted elsewhere, and is 9.5. The 9.2 psql client will still happily connect to the 9.5 DB, with a warning. How can I tell which version or postgres the psycopg2 library is using, and how can I force it to use a specific version? Running <code>SELECT version();</code> seems to return the server version, while I'm only interested in the client version.</p>
0
2016-09-02T00:39:13Z
39,286,677
<p>Should be able to force it by putting the 9.5 client binaries at the start of the path for the user that is running your python program. To test:</p> <pre><code>export PATH=/opt/&lt;path-to-your-9.5&gt;;$PATH which psql #ensure the 9.5 one is returned psql -h &lt;remote-host&gt; -p &lt;remote-port&gt; -U &lt;user&gt; -W -d &lt;dbname&gt; # test even further if you wish </code></pre> <p>If you wanting know the lib then you need to look at what libpq your python is using:</p> <pre><code>[root@pgbuilder cgi-bin]# ldd /usr/lib64/python2.7/site-packages/psycopg2/_psycopg.so | grep libpq libpq.so.5 =&gt; /usr/pgsql-9.5/lib/libpq.so.5 (0x00007fd5f40b7000) </code></pre> <p>Change your path to suit your "_psycopg.so" location.</p>
0
2016-09-02T07:28:56Z
[ "python", "postgresql", "psycopg2" ]
How can I tell/specify which version of the postgres client/libs psycopg2 is using?
39,282,745
<p>I have psycopg2 for a python program, but the computer the program is running on has two version of postgres installed: 9.2 in the 'main' system, and 9.5 in /opt. The postgres DB is hosted elsewhere, and is 9.5. The 9.2 psql client will still happily connect to the 9.5 DB, with a warning. How can I tell which version or postgres the psycopg2 library is using, and how can I force it to use a specific version? Running <code>SELECT version();</code> seems to return the server version, while I'm only interested in the client version.</p>
0
2016-09-02T00:39:13Z
39,600,423
<p>In psycopg 2.6.x <code>ldd</code> is the way to go. In 2.7 there will be a function to return that information, but it's not been released yet.</p>
0
2016-09-20T17:34:33Z
[ "python", "postgresql", "psycopg2" ]
Restore postrgres without ending connections
39,282,825
<p>I run a number of queries for adhoc analysis against a postgres database. Many times I will leave the connection open through the day instead of ending after each query.</p> <p>I receive a postgres dump over scp through a shell script every five minutes and I would like to restore the database without cutting the connections. Is this possible?</p>
0
2016-09-02T00:49:32Z
39,286,433
<p>One of the few activities that you cannot perform while a user is connected is dropping the database.<br> So &ndash; if that is what you are doing during restore &ndash; you'll have to change your approach. Don't drop the database (don't use the <code>-C</code> option in <code>pg_dump</code> or <code>pg_restore</code>), but rather drop and recreate the schemas and objects that don't depend on a schema (like large objects).<br> You can use the <code>-c</code> flag of <code>pg_dump</code> or <code>pg_restore</code> for that.</p> <p>The other problem you might run into is connections with open transactions (state &ldquo;idle in transaction&rdquo;). Such connections can hold locks that keep you from dropping and recreating objects, and you'll have to use <code>pg_terminate_backend()</code> to get rid of them.</p>
1
2016-09-02T07:16:04Z
[ "python", "database", "postgresql", "restore" ]
Python error in Mac OS X 10.11.6
39,282,848
<p>I have homebrew installed as well as the system python under 10.11.6. When I try to use pip (or pip3) pip does not run and gives the following error. Does anyone have any suggestions as to how to fix it?</p> <p>Here are the error messages</p> <pre><code>echo $PYTHON_PATH /Users/paulfons/ase: axion:~ paulfons$ echo $PATH /opt/local/bin:/opt/local/sbin:/usr/local/Cellar/pyenv-virtualenv/20160716/shims:/opt/intel//compilers_and_libraries_2016.1.111/mac/bin/intel64:/opt/intel//documentation_2016/en/debugger//gdb-ia/man/:/Users/paulfons/bin:/Users/paulfons/ase/tools:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Library/TeX/texbin:/opt/intel//debugger_2016/gdb/intel64/bin axion:~ paulfons$ pip -V Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2927, in &lt;module&gt; @_call_aside File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2913, in _call_aside f(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2940, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 635, in _build_master ws.require(__requires__) File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 943, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 829, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==8.1.2' distribution was not found and is required by the application axion:~ paulfons$ pip3 -V Traceback (most recent call last): File "/usr/local/bin/pip3", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2927, in &lt;module&gt; @_call_aside File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2913, in _call_aside f(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2940, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 635, in _build_master ws.require(__requires__) File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 943, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 829, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==8.1.2' distribution was not found and is required by the application axion:~ paulfons$ </code></pre>
-1
2016-09-02T00:53:55Z
39,283,104
<p>You can try to reinstall your pip, or upgrade it using easyinstall. On your MacBook you can run this command on your terminal:</p> <pre><code>sudo easy_install-3.5 --upgrade pip </code></pre>
0
2016-09-02T01:32:40Z
[ "python" ]
Django TypeError: allow_migrate() got an unexpected keyword argument 'model_name'
39,282,860
<p>So I copied over my Django project to a new server, replicated the environment and imported the tables to the local mysql database.</p> <p>But when I try to run makemigrations it gives me the TypeError: allow_migrate() got an unexpected keyword argument 'model_name'</p> <p>This is the full stack trace:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 353, in execute self.check() File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/home/cicd/.local/lib/python2.7/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/cicd/.local/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/base.py", line 1266, in check errors.extend(cls._check_fields(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/base.py", line 1337, in _check_fields errors.extend(field.check(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 893, in check errors = super(AutoField, self).check(**kwargs) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 208, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/home/cicd/.local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 310, in _check_backend_specific_checks if router.allow_migrate(db, app_label, model_name=self.model._meta.model_name): File "/home/cicd/.local/lib/python2.7/site-packages/django/db/utils.py", line 300, in allow_migrate allow = method(db, app_label, **hints) TypeError: allow_migrate() got an unexpected keyword argument 'model_name' </code></pre> <p>I would appreciate any help in debugging this error and trying to understand what is causing this error.</p>
1
2016-09-02T00:55:49Z
39,408,774
<p>I meet the same problem when i move from 1.6.* to 1.10.Finally i found the problem cause by the <strong>DATABASE_ROUTERS</strong> </p> <p>the old version i write like this </p> <pre><code>class OnlineRouter(object): # ... def allow_migrate(self, db, model): if db == 'myonline': return model._meta.app_label == 'online' elif model._meta.app_label == 'online': return False return None </code></pre> <p>it work by rewrite like this</p> <pre><code>class OnlineRouter(object): # ... def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'my_online': return app_label == 'online' elif app_label == 'online': return False return None </code></pre> <p>more detail see <a href="https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#an-example" rel="nofollow" title="djangoproject">https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#an-example</a></p>
2
2016-09-09T09:52:52Z
[ "python", "mysql", "django" ]
Unable to install Snap7 Library on Ubuntu 16.04 (64-bit)
39,282,877
<p>I'm new to Linux based OS's (and very new to Snap7). Trying to install Snap7 library on Ubuntu machine following instructions at - <a href="http://python-snap7.readthedocs.io/en/latest/installation.html" rel="nofollow">http://python-snap7.readthedocs.io/en/latest/installation.html</a>. However I'm getting the following errors during the 3rd step</p> <pre><code>E: Unable to locate package libsnap71 E: Unable to locate package libsnap7-dev </code></pre> <p>I'm not sure how exactly to manually install it and I'm unsure how to fix this installation issue so any advice whould be fantastic :)</p> <p>Below is a copy of the log after already running the "add repository" command:</p> <pre><code>administrator@*pc-name*:~/Documents/*folder*$ sudo apt-get update Hit:1 http://au.archive.ubuntu.com/ubuntu xenial InRelease Get:2 http://au.archive.ubuntu.com/ubuntu xenial-updates InRelease [95.7 kB] Hit:3 http://au.archive.ubuntu.com/ubuntu xenial-backports InRelease Get:4 http://au.archive.ubuntu.com/ubuntu xenial-updates/main amd64 DEP-11 Metadata [299 kB] Ign:5 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial InRelease Get:6 http://security.ubuntu.com/ubuntu xenial-security InRelease [94.5 kB] Get:7 http://au.archive.ubuntu.com/ubuntu xenial-updates/main DEP-11 64x64 Icons [184 kB] Ign:8 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial Release Ign:9 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 Packages Ign:10 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main i386 Packages Ign:11 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main all Packages Ign:12 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en_AU Ign:13 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en Ign:14 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 DEP-11 Metadata Ign:15 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main DEP-11 64x64 Icons Ign:9 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 Packages Ign:10 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main i386 Packages Ign:11 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main all Packages Ign:12 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en_AU Ign:13 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en Ign:14 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 DEP-11 Metadata Ign:15 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main DEP-11 64x64 Icons Ign:9 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 Packages Ign:10 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main i386 Packages Ign:11 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main all Packages Ign:12 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en_AU Ign:13 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en Ign:14 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 DEP-11 Metadata Ign:15 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main DEP-11 64x64 Icons Ign:9 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 Packages Ign:10 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main i386 Packages Ign:11 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main all Packages Ign:12 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en_AU Ign:13 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en Ign:14 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 DEP-11 Metadata Ign:15 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main DEP-11 64x64 Icons Ign:9 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 Packages Ign:10 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main i386 Packages Ign:11 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main all Packages Ign:12 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en_AU Ign:13 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en Ign:14 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 DEP-11 Metadata Ign:15 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main DEP-11 64x64 Icons Err:9 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 Packages 404 Not Found Ign:10 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main i386 Packages Ign:11 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main all Packages Ign:12 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en_AU Ign:13 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main Translation-en Ign:14 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main amd64 DEP-11 Metadata Ign:15 http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial/main DEP-11 64x64 Icons Fetched 673 kB in 13s (50.9 kB/s) Reading package lists... Done W: The repository 'http://ppa.launchpad.net/gijzelaar/snap7/ubuntu xenial Release' does not have a Release file. N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use. N: See apt-secure(8) manpage for repository creation and user configuration details. E: Failed to fetch http://ppa.launchpad.net/gijzelaar/snap7/ubuntu/dists/xenial/main/binary-amd64/Packages 404 Not Found E: Some index files failed to download. They have been ignored, or old ones used instead. administrator@*pc-name*:~/Documents/*folder*$ sudo apt-get install libsnap71 libsnap7-dev Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package libsnap71 E: Unable to locate package libsnap7-dev </code></pre> <p>Please let me know if you need more information to make a proper assessment.</p>
0
2016-09-02T00:57:34Z
39,282,917
<p>You missed this part on the very page you linked to:</p> <pre><code>If you are using Ubuntu you can use the Ubuntu packages from our launchpad PPA. To install: $ sudo add-apt-repository ppa:gijzelaar/snap7 $ sudo apt-get update $ sudo apt-get install libsnap71 libsnap7-dev </code></pre> <p>Execute all three commands in order and you should be fine. <em>However</em>, as the software is older than your system, you need to edit the <code>/etc/apt/sources.d</code> file created after the first step and replace <code>xenial</code> (or even <code>yaketty</code>) with <code>trusty</code>. The ppa only has builds for older releases.</p>
1
2016-09-02T01:03:13Z
[ "python", "linux", "ubuntu", "scada" ]
Heroku/python failed to detect set buildpack
39,282,911
<p>I'm a Django newbie, I created an app and want to deploy it using Heroku. However, when I do <code>git push heroku master</code> (I follow Heroku's getting started), this is what I got:</p> <pre><code>Counting objects: 36, done. Delta compression using up to 4 threads. Compressing objects: 100% (33/33), done. Writing objects: 100% (36/36), 19.22 KiB | 0 bytes/s, done. Total 36 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to dry-waters-63931. remote: To https://git.heroku.com/dry-waters-63931.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/dry-waters-63931.git' </code></pre> <p>My root directory:</p> <pre><code>├── assignment ├── household_management (django app) ├── templates | ├── db.sqlite3 | ├── manage.py </code></pre> <p>I will be very appreciated if you guys can help. I'm really depressed right now...</p>
1
2016-09-02T01:02:11Z
39,283,046
<p>You need to add a <code>requirements.txt</code> file which contains all of the modules required to run your application.</p> <p>You can do <code>pip freeze &gt; requirements.txt</code> to freeze all of your modules into a file. I would only recommend doing this if you're using a virtualenv because otherwise it will add ALL of your modules.</p> <p>Anyways, just determine exactly what modules your application requires and create a file called <code>requirements.txt</code> and put it in your application directory.</p> <p>The syntax for a requirements file is as follows:</p> <pre><code>package name == version # package name == version # package name == version # </code></pre> <p>Note: It is optional to specify a certain version number.</p> <p>Here is an example requirements file (taken from <a href="https://github.com/deis/example-python-flask/blob/master/requirements.txt" rel="nofollow">this</a> tutorial):</p> <pre><code>Flask==0.11 Jinja2==2.8 gunicorn==19.6.0 </code></pre>
2
2016-09-02T01:23:34Z
[ "python", "django", "git", "heroku", "deployment" ]
Python get bash double-tab completion output
39,282,925
<p>I am programming a Ros interface in python, and I would like to be able to select the node I want to run from a list showing all available nodes once I choose a package.</p> <p>In other words I would like to create the list of all nodes contained in a package getting the output I would have in the terminal if I type:</p> <pre><code>rosrun &lt;package-name&gt; \t\t </code></pre> <p>In terms of python code, a wrong example of what I am trying to do could be:</p> <pre><code>from subprocess import Popen, PIPE p = Popen (["rosrun", "&lt;package-name&gt;", "\t\t"], stdout = PIPE, stderr = PIPE) out, err = p.communicate () print (out.decode ("ascii")) print (err.decode ("ascii")) </code></pre> <p>But this does not work because "\t\t" is not processed in Popen like it is in the terminal.</p> <p>Is there any way to get this working or is it impossible to emulate the double-tab completion of the terminal from inside a python script?</p> <p>Is Popen to be used in a different way to do this or should I totally change the code using other facilities?</p> <p>Please help me :)</p>
0
2016-09-02T01:04:09Z
39,298,132
<p>Finally I solved this by myself, I went right throw Ros own code and found out how it generates the bash completion output.</p> <p>My code now is like this:</p> <pre><code>from subprocess import Popen, PIPE package = "&lt;package&gt;" comm = str("catkin_find --first-only --without-underlays --libexec " + package).split () out, err = Popen (comm, stdout = PIPE, stderr = PIPE).communicate () out = out.decode ("ascii") if (out.strip () == ""): return comm = "find -L " + out.strip () + " -type f -exec basename {} ';'" out, err = Popen (comm, shell = True, stdout = PIPE, stderr = PIPE).communicate () out = out.decode ("ascii") print (out.strip ()) </code></pre> <p>I simplified Ros code, it was originally more complicated, but this version does what I need for now.</p> <p>I hope it can be useful also for others. </p> <p>Thanks for the advices :)</p>
0
2016-09-02T17:46:32Z
[ "python", "bash", "subprocess", "ros" ]
NoSuchElement exception with Selenium even after using Wait and checking page_soure
39,282,930
<p>I have this simple scraper that I am running. I am trying to scrape the search results for letter q from sam.gov:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup import re import sys reload(sys) sys.setdefaultencoding('utf8') letter = 'q' driver = webdriver.PhantomJS() driver.set_window_size(1120, 550) driver.get("http://sam.gov") #element = WebDriverWait(driver, 10).until( # EC.presence_of_element_located((By.ID, "pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1")) # ) #element.click() driver.find_element_by_id('pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1').click() driver.find_element_by_id(letter).send_keys(letter) driver.find_element_by_id('RegSearchButton').click() def crawl(): bsObj = BeautifulSoup(driver.page_source, "html.parser") tableList = bsObj.find_all("table", {"class":"width100 menu_header_top_emr"}) tdList = bsObj.find_all("td", {"class":"menu_header width100"}) for table in tableList: item = table.find_all("span", {"class":"results_body_text"}) print item[0].get_text().strip() + ', ' + item[1].get_text().strip() if driver.find_element_by_id('anch_16'): crawl() driver.find_element_by_id('anch_16').click() print "Going to next page" else: crawl() print "Done with last page" driver.quit() </code></pre> <p>When i run it gives a weird error which is bothering me:</p> <p>Traceback (most recent call last):</p> <pre><code> File "save.py", line 22, in &lt;module&gt; driver.find_element_by_id('pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1').click() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 269, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element 'value': value})['value'] File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":"Unable to find element with id 'pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"153","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:40423","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"id\", \"sessionId\": \"eb7dfa50-70a7-11e6-b125-9ff4e2dbd485\", \"value\": \"pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/eb7dfa50-70a7-11e6-b125-9ff4e2dbd485/element"}} Screenshot: available via screen </code></pre> <p>I have since tried using an implicit wait of 60 right after i initialize the browser. No luck</p> <p>I have also tried webdriverwait (commented out in the code right below <code>driver.get("http://sam.gov")</code>, and it gave me at TimeOutException.</p> <p>The weird thing is if i do a <code>print driver.page_source</code> right after the get call, the source is fine and it contains the following code which actually contains the element with the id that I am searching for. There is no frame or iframe either.</p> <pre><code>&lt;a id="pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1" href="#" title="Search Records" onclick="if(typeof jsfcljs == 'function'){jsfcljs(document.getElementById('pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12'),{'pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1':'pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1'},'');}return false" class="button"&gt; </code></pre>
0
2016-09-02T01:05:28Z
39,283,907
<p>Id locator of the element looks like dynamically generated, you should try some different locator.</p> <p>You can try using <code>css_selector</code> as below:-</p> <pre><code>driver.find_element_by_css_selector("a.button[title='Search Records']").click() </code></pre> <p>Or using <code>WebDriverWait</code> as:-</p> <pre><code>element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.button[title='Search Records']"))) element.click() </code></pre> <p><strong>Note</strong> :- Before finding element make sure it's not inside any <code>frame/iframe</code>. If it's inside any <code>frame/iframe</code> you need to switch that <code>frame/iframe</code> before finding element as <code>driver.switch_to_frame("frame/iframe id or name")</code></p>
0
2016-09-02T03:33:21Z
[ "python", "selenium", "exception", "phantomjs" ]
Pandas parallel groupBy consumes tons of memory
39,282,945
<p>I have a medium sized file (~300MB) containing a list of individuals (~300k) and actions they performed. I'm trying to apply an operation for each individuals using <code>groupBy</code> and the paralellized version of <code>apply</code> described <a href="http://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">here</a>. It looks something like this</p> <pre><code>import pandas import multiprocessing from joblib import Parallel, delayed df = pandas.read_csv(src) patients_table_raw = apply_parallel(df.groupby('ID'), f) def applyParallel(dfGrouped, func): retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(group) for name, group in dfGrouped) return pd.concat(retLst) </code></pre> <p>But unfortunately this consumes A HELL LOT OF SPACE. I think it is related with the fact that the simple command:</p> <pre><code>list_groups = list(df.groupby('ID')) </code></pre> <p>Consumes several GB of memory! How to procceed? My initial thoughts were to iterate the groupBy in small 'stacks', not consuming too much memory (but I didn't found a way to do so without casting it to a list).</p> <h2>More detailed context</h2> <p>I have a simple CSV dataset in the following fashion:</p> <pre><code>|-------------------------| | ID | Timestamp | Action | |-------------------------| |1 | 0 | A | |1 | 10 | B | |1 | 20 | C | |2 | 0 | B | |2 | 15 | C | ... </code></pre> <p>What I'm basically trying to do is create a different table that contains a description of sequence of actions/timestamps of the individuals and their IDs. This will help me retrieve the individuals</p> <pre><code>|------------------| | ID | Description | |------------------| |1 | 0A10B20C | |2 | 0B15C | ... </code></pre> <p>In order to do so, and to follow a Pythonic way, my idea was basically to load the first table in a pandas DataFrame, groupBy the ID, and apply a function in the grouping that returns a row of the table I want for each group (each ID). However, I have LOTS of individuals in my dataset (around 1 million), and the groupBy operation was extremely expensive (without explicit garbage collection, as I mentioned in my own answer). Also, parallelizing the groupBy implied in significant memory use, because apparently some things get duplicated.</p> <p>Therefore, the more detailed question is: how to use groupBy (and therefore make the data processing faster than if you would implement a loop of your own) and don't get this huge memory overhead?</p>
2
2016-09-02T01:07:59Z
39,283,764
<p>Some comments and then the solution I've found:</p> <ul> <li><p>I've tried <code>dask</code> and it didn't made much difference. I guess it is because the file is not big enough to use the secondary memory.</p></li> <li><p>The memory performance improves significantly if you perform the garbage collection inside the function you apply to the groups. I've managed to do so with a simple <code>gc.collect()</code> that happens every $10000$ interactions. Something like:</p> <pre><code>x['ID'].head(1).values[0] % 10000 == 0: gc.collect() </code></pre></li> <li><p>The garbage collection actually made my parallel version run. But the <code>return pd.concat(retLst)</code> was another huge bottleneck, and consumed tons of memory!</p></li> </ul> <p>My final solution was to paralellize the solution in an outer fashion:</p> <ul> <li><p>I created a function that will perform the groupBy and the apply for individuals with ID's inside a range [X,Y]</p></li> <li><p>I simply create a pool and run those in parallel. Each process saves a file with a different name, depending on its range</p> <pre><code>f = functools.partial(make_patient_tables2, src="in", dest="out") range_of = [(0, 10000), (10000, 20000), (20000, 30000)] with Pool(cpu_count()) as p: ret_list = p.map(f, range_of) </code></pre></li> <li><p>Last but not least, I concatenate all the generated files.</p></li> </ul> <p>Notice that this is still a bit memory intensive, as we have to replicate the reading of the table (which is done inside <em>make_patient_tables2</em>, but would happen anyway, as the multiprocessing doesn't share resources. A better solution, therefore, would envolve sharing resources, but the garbage collector + not using the concat + replication the original data only 2-3 times was enough for me!</p> <p>Certainly not pretty. Hope it can be of help for someone else.</p>
0
2016-09-02T03:12:46Z
[ "python", "pandas", "group-by" ]
Pandas parallel groupBy consumes tons of memory
39,282,945
<p>I have a medium sized file (~300MB) containing a list of individuals (~300k) and actions they performed. I'm trying to apply an operation for each individuals using <code>groupBy</code> and the paralellized version of <code>apply</code> described <a href="http://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">here</a>. It looks something like this</p> <pre><code>import pandas import multiprocessing from joblib import Parallel, delayed df = pandas.read_csv(src) patients_table_raw = apply_parallel(df.groupby('ID'), f) def applyParallel(dfGrouped, func): retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(group) for name, group in dfGrouped) return pd.concat(retLst) </code></pre> <p>But unfortunately this consumes A HELL LOT OF SPACE. I think it is related with the fact that the simple command:</p> <pre><code>list_groups = list(df.groupby('ID')) </code></pre> <p>Consumes several GB of memory! How to procceed? My initial thoughts were to iterate the groupBy in small 'stacks', not consuming too much memory (but I didn't found a way to do so without casting it to a list).</p> <h2>More detailed context</h2> <p>I have a simple CSV dataset in the following fashion:</p> <pre><code>|-------------------------| | ID | Timestamp | Action | |-------------------------| |1 | 0 | A | |1 | 10 | B | |1 | 20 | C | |2 | 0 | B | |2 | 15 | C | ... </code></pre> <p>What I'm basically trying to do is create a different table that contains a description of sequence of actions/timestamps of the individuals and their IDs. This will help me retrieve the individuals</p> <pre><code>|------------------| | ID | Description | |------------------| |1 | 0A10B20C | |2 | 0B15C | ... </code></pre> <p>In order to do so, and to follow a Pythonic way, my idea was basically to load the first table in a pandas DataFrame, groupBy the ID, and apply a function in the grouping that returns a row of the table I want for each group (each ID). However, I have LOTS of individuals in my dataset (around 1 million), and the groupBy operation was extremely expensive (without explicit garbage collection, as I mentioned in my own answer). Also, parallelizing the groupBy implied in significant memory use, because apparently some things get duplicated.</p> <p>Therefore, the more detailed question is: how to use groupBy (and therefore make the data processing faster than if you would implement a loop of your own) and don't get this huge memory overhead?</p>
2
2016-09-02T01:07:59Z
39,284,194
<p>Try this (<strong>without</strong> parallelization):</p> <pre><code>In [87]: df Out[87]: ID Timestamp Action 0 1 0 A 1 1 10 B 2 1 20 C 3 2 0 B 4 2 15 C In [88]: df.set_index('ID').astype(str).sum(axis=1).groupby(level=0).sum().to_frame('Description').reset_index() Out[88]: ID Description 0 1 0A10B20C 1 2 0B15C </code></pre>
2
2016-09-02T04:13:14Z
[ "python", "pandas", "group-by" ]
Qt with PyQt. Is it possible to view the object hierarchy of a running window?
39,282,963
<p>I am currently working on a project using PyQt5, and am using several windows that will dynamically change their widgets, depending on the data I supply.</p> <p>For the purposes of debugging, would it be possible to view the object structure of a window as it is running? I am using Qt Designer to design many of my windows, but as the contents change while the program is running, Qt Creator cannot show me the structure of my windows at all times in my program.</p> <p>Is it possible to view the object hierarchy, such as in the Object Inspector in Qt Creator? Or perhaps is it possible to make the invisible widgets, like layouts and spacers, visible while running?</p>
0
2016-09-02T01:11:28Z
39,283,595
<p>I don't know if it's possible to do this in Qt Creator while the application is running, but you can definitely insert statements into the source code which will print out the entire object hierarchy. Just pick your base object and recursively print the output of <code>QWidget.children()</code>.</p> <p>One problem is when to print this so that you neither miss newly-added widgets nor completely overwhelm the terminal (so a timer is not the best idea). If your application responds to that data that you supply by calling a specific slot or function, which seems like the points at which the tree changes, that would be a perfect time to do this. You can start from the <code>QApplication</code> object, and walk the tree down from there.</p> <p>If you don't respond to data that way, there is a more involved but OK solution. You can instead intercept all <code>QChildEvent</code>s and print the new object hierarchy at that point. This can be done by installing a filter object on the root object you're interested in as soon as it's created, which would then install itself on any new children. This could then print the full object tree, starting from the root. Check out <a href="https://stackoverflow.com/questions/39155748/how-to-receive-event-whenever-a-qwidget-is-added-to-qapplications-widget-tree/39156966#39156966">this answer</a> for more details on how to create this kind of filter object. it's in C++, but the code should be straightforward to translate to Python.</p>
0
2016-09-02T02:47:10Z
[ "python", "qt", "pyqt" ]
Flask data storage in session with javascript or jquery
39,282,989
<p>I have a lot of data (about 30 columns) from different HTML pages to store:</p> <ol> <li>a string (can be retrieved by id) randomly generated with Javascript</li> <li>a form with data from user input</li> <li>a list of values generated with Javascript</li> </ol> <p>With Flask framework, most of the sessions are done on the Python file (app.py) itself. Is it possible to store data on session with Javascript or Jquery?</p>
0
2016-09-02T01:15:45Z
39,283,069
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API" rel="nofollow">web storage</a>. There are two kinds:</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage" rel="nofollow">Session Storage</a>:</p> <blockquote> <p>Maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)</p> </blockquote> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" rel="nofollow">Local Storage</a>:</p> <blockquote> <p>Does the same thing, but persists even when the browser is closed and reopened.</p> </blockquote>
1
2016-09-02T01:27:37Z
[ "javascript", "jquery", "python", "flask", "session-cookies" ]
Python checking sql database column for value
39,282,991
<p>How would one check an entire column in sqlite database for a given value and if found set a variable to true</p> <p>something like</p> <pre><code>hasvalue = 'false' cur = con.cursor() cur.execute("SELECT id FROM column WHERE hasvalue = '1' LIMIT 1;") ***IF execute returned rows set hasvalue = true here*** if hasvalue == 'true': do something else: dosomethingelse </code></pre> <p>How would I make hasvalue turn to true if the sql query returned with something and if it returned 0 rows stay false?</p> <p>Basically I want to execute something ONLY if something in a column equals 1</p>
0
2016-09-02T01:16:18Z
39,283,198
<p>I'm a little confused by your question. The SQL query suggests that you are using a <em>table</em> named <code>column</code>? If I can ignore that and assume you have a table named <code>test</code> which has columns <code>id</code> (an int) and <code>name</code> (a string). Then the query:</p> <pre><code>SELECT id FROM test where name = 'something' </code></pre> <p>would select all rows that have <code>name</code> set to the string <code>'something'</code>.</p> <p>In Python this would be:</p> <pre><code>cur = con.cursor() cur.execute("SELECT id FROM test where name = 'something' LIMIT 1") if cur.fetchone(): do_something() else: do_something_else() </code></pre> <p>The key here is to use <a href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.fetchone" rel="nofollow"><code>cursor.fetchone()</code></a> which will try and retrieve a row from the cursor. If there are no rows <code>fetchone()</code> will return <code>None</code>, and <code>None</code> evaluates to <code>False</code> when used as a condition in an <code>if</code> statement.</p> <p>You could create a function to generalise:</p> <pre><code>def has_value(cursor, table, column, value): query = 'SELECT 1 from {} WHERE {} = ? LIMIT 1'.format(table, column) return cursor.execute(query, (value,)).fetchone() is not None if has_value(cur, 'test', 'name', 'Ranga'): do_something() else: do_something_else() </code></pre> <p>This code constructs a query for the given table, column, and value and returns <code>True</code> if there is at least one row with the required value, otherwise it returns <code>False</code>.</p>
0
2016-09-02T01:50:08Z
[ "python", "database", "sqlite" ]
Using python in math
39,282,995
<p>Ok so i want to solve this equation through python but cant figure out what to do! I tried using for loops but that didn't work so well</p> <p>Im new to python so can anyone suggest what I should do</p> <pre><code>RWBG-(WBR^2)-WBR-(BR^3)-(3BR^2)+2BR-(R^3)-(6R^2)+11R-6 = 0 </code></pre> <p>R,W,B,G are different variables</p> <pre><code>for i in range(100): R == i for i in range(100): W == i for i in range(100): B == i for i in range(100): G == i if R*W*B*G-W*B*R**2-W*B*R-B*R**3-3*B*R**2+2*B*R-R**3-6*R**2+11*R-6 == 0: print(R) print(W) print(B) print(G) </code></pre> <p>Ive tried this but it isnt successful </p>
-2
2016-09-02T01:16:39Z
39,283,050
<p>Assuming each letter is a variable, and that you simply want to evaluate the expression, an easy Python script would be:</p> <pre><code>def equation (R,W,B,G,R): return R*W*B*G - W*B*(R**2) - W*B*R - B(R**3) - 3*B*(R**2) + 2*B*R - R**3 - 6*(R**2) + 11*R - 6 </code></pre>
1
2016-09-02T01:23:53Z
[ "python", "math", "equation", "polynomials", "quadratic" ]
Why is this Haskell code so slow?
39,283,047
<p>I'm kind of new to Haskell and tried making a scrabble solver. It takes in the letters you currently have, finds all permutations of them and filters out those that are dictionary words. The code's pretty simple: </p> <pre><code>import Data.List main = do dict &lt;- readFile "words" letters &lt;- getLine let dictWords = words dict let perms = permutations letters print [x | x &lt;- perms, x `elem` dictWords] </code></pre> <p>However it's incredibly slow, compared to a very similar implementation I have with Python. Is there something fundamental I'm doing wrong?</p> <p>*edit: Here's my Python code:</p> <pre><code>from itertools import permutations letters = raw_input("please enter your letters (without spaces): ") d = open('words') dictionary = [line.rstrip('\n') for line in d.readlines()] d.close() perms = ["".join(p) for p in permutations(letters)] validWords = [] for p in perms: if p in dictionary: validWords.append(p) for validWord in validWords: print validWord </code></pre> <p>I didn't time them precisely, but roughly it feels like the Python implementation is about 2x as fast as the Haskell one. Perhaps I should't have said the Haskell code was "incredibly slow" in comparison, but since Haskell is statically typed I guess I just thought that it should've been much faster, and not slower than Python at all.</p>
6
2016-09-02T01:23:37Z
39,283,078
<p>Checking if <code>x</code> is an element of <code>dictWords</code> is likely to be very slow. I would assume that your similar python implementation stores <code>dictWords</code> in a set or sorted vector (using binary search in the latter case)? Seems like you probably want to do the same here.</p> <p>Using <a href="https://www.wordgamedictionary.com/twl06/download/twl06.txt" rel="nofollow">this word list</a> and the code below, the Python version runs in about 30 seconds, and the Haskell version takes 1.5 minutes. So Haskell is slower (perhaps because it's using a linked list, which all things being equal, is slower to iterate over), but I wouldn't call it "incredibly slow" compared to Python. Switching to use a set in either version reduces the time to under 1 second.</p> <pre class="lang-py prettyprint-override"><code>from itertools import permutations f = open('twl06.txt') words = f.read().split() print [''.join(p) for p in permutations('apricot') if ''.join(p) in words] </code></pre> <p>And here's the set-based Haskell code:</p> <pre><code>import Data.Set import Data.List main = do dict &lt;- readFile "twl06.txt" let letters = "apricot" let dictWords = Data.Set.fromList $ words dict let perms = permutations letters print [x | x &lt;- perms, member x dictWords] </code></pre>
5
2016-09-02T01:28:50Z
[ "python", "haskell", "optimization", "language-comparisons" ]
Why is this Haskell code so slow?
39,283,047
<p>I'm kind of new to Haskell and tried making a scrabble solver. It takes in the letters you currently have, finds all permutations of them and filters out those that are dictionary words. The code's pretty simple: </p> <pre><code>import Data.List main = do dict &lt;- readFile "words" letters &lt;- getLine let dictWords = words dict let perms = permutations letters print [x | x &lt;- perms, x `elem` dictWords] </code></pre> <p>However it's incredibly slow, compared to a very similar implementation I have with Python. Is there something fundamental I'm doing wrong?</p> <p>*edit: Here's my Python code:</p> <pre><code>from itertools import permutations letters = raw_input("please enter your letters (without spaces): ") d = open('words') dictionary = [line.rstrip('\n') for line in d.readlines()] d.close() perms = ["".join(p) for p in permutations(letters)] validWords = [] for p in perms: if p in dictionary: validWords.append(p) for validWord in validWords: print validWord </code></pre> <p>I didn't time them precisely, but roughly it feels like the Python implementation is about 2x as fast as the Haskell one. Perhaps I should't have said the Haskell code was "incredibly slow" in comparison, but since Haskell is statically typed I guess I just thought that it should've been much faster, and not slower than Python at all.</p>
6
2016-09-02T01:23:37Z
39,283,994
<blockquote> <p>I'm kind of new to Haskell and tried making a scrabble solver.</p> </blockquote> <p>You can substantially improve things by using a better algorithm.</p> <p>Instead of testing every permutation of the input letters, if you sort them first you can make only one dictionary lookup and get all of the possible words (anagrams) which may be formed from them (using all of them).</p> <p>Here is code which creates that dictionary as a Data.Map. There is a start-up cost to creating the Map, but after the first query subsequent lookups are very fast.</p> <pre><code>import Data.List import qualified Data.Map.Strict as Map import Control.Monad import System.IO main = do contents &lt;- readFile "words" let pairs = [ (sort w, [w]) | w &lt;- words contents ] dict = foldl' (\m (k,v) -&gt; Map.insertWith (++) k v m) Map.empty pairs -- dict = foldr (\(k,v) m -&gt; Map.insertWith (++) k v m) Map.empty pairs forever $ do putStr "Enter letters: " &gt;&gt; hFlush stdout letters &lt;- getLine case Map.lookup (sort letters) dict of Nothing -&gt; putStrLn "No words." Just ws -&gt; putStrLn $ "Words: " ++ show ws </code></pre> <p>Map creation time for a word file of 236K words (2.5 MB) is about 4-5 seconds. Better performance is likely possible by using ByteStrings or Text instead of Strings.</p> <p>Some good letter combinations to try:</p> <pre><code>steer rat tuna lapse groan neat </code></pre> <p>Note: Using GHC 7.10.2 I found this code performed the best <em>without</em> compiling with -O2.</p>
7
2016-09-02T03:44:02Z
[ "python", "haskell", "optimization", "language-comparisons" ]
Division & Modulo Operator
39,283,112
<p>I just started learning how to code, and I've been assigned a problem that I've been stuck on for many hours now and was hoping I could receive some hints at the very least to solve the problem. The main point of this exercise is to practice division and modulus. We can use basic statements, but nothing fancy like conditionals or anything since we haven't gotten to that point.</p> <p>I need a user to input a # from 1 - 25, and then my program will let them know which unit and row that number is in. I've managed to get the code working for the rows, but I cannot figure out how to get the unit number.</p> <p>Here's my code:</p> <pre><code>shelfNumber = int(raw_input('What is the shelf number? ')) row = int(shelfNumber / 5.1) + 1 unit = </code></pre> <p>I've tried a lot of things for unit, but none of them worked out, so I left it blank. I would appreciate any hints that anyone can give me. Thank you for any help.</p> <p><a href="http://i.stack.imgur.com/qNiAe.png" rel="nofollow"><img src="http://i.stack.imgur.com/qNiAe.png" alt="image"></a></p> <p>Edit: I realized that I should try and at least show which ideas I've tried. If I do a regular modulo with # % 5, that works for everything but the multiples of 5 all the way on the right. I've also tried implementing the row #'s each # has but haven't gotten anywhere with that either. I've also tried something similar by dividing by a decimal, casting it as an int, then using modulo but failed, etc., etc.\</p> <p><strong>Edit:</strong> Sorry, I realized I uploaded the wrong image.</p>
0
2016-09-02T01:34:17Z
39,313,730
<p>This problem would be easier if everything were countrd from 0 instead of from 1. That is, if the row and unit numbers were 0 to 4 instead of 1 to 5 and if the input value were 0 to 24 instead of 1 to 25.</p> <p>In that case, we'd just write:</p> <pre><code>row = shelfNumber / 5 unit = shelfNumber % 5 </code></pre> <p>Since everything starts ftom 1 ("is one-indexed" in the usual jargon), <code>shelfNumber</code> is one bigger than what that formula needs, and we need to make <code>row</code> and <code>unit</code> one bigger than what we computed.</p> <p>But there's no trouble fixing that:</p> <pre><code>row = (shelfNumber - 1) / 5 + 1 unit = (shelfNumber - 1) % 5 + 1 </code></pre> <p>In Python 3, you'd need to write <code>//</code> insted of <code>/</code>, and that will work with a reasonably recent Python 2.</p>
1
2016-09-04T05:12:37Z
[ "python", "python-2.x", "division", "modulo", "modulus" ]
Displaying text when a button is clicked in python
39,283,206
<p>Here i create a 9 buttons and when button is clicked hello must be displayed on the button....i know its simple but i'm not getting where did i get wrong.Thanks in advance. Here's the code</p> <pre><code>from Tkinter import * class Design: def __init__(self): self.button={} self.root=Tk() self.root.title("Simple Design") self.root.geometry("300x300") for i in range(3): for j in range(3): self.button[i,j]=Button(self.root,text="*",padx=12,pady=12).grid(row=i,column=j) self.click() def click(self): for i in range(3): for j in range(3): handler=lambda i,j:self.update(i,j) print "click function" self.button[i,j]=Button(self.root,command=handler) def update(self,i,j): self.button[i,j]=Button(self).grid() self.button[i,j]["text"]="Hello" print "Hello" </code></pre>
1
2016-09-02T01:51:40Z
39,286,634
<p>Right now i can't test the your code, but i see the problem here: <code>self.button[i,j]=Button(self.root,text="*",padx=12,pady=12).grid(row=i,column=j)</code>! You are calling <code>.grid()</code>, which has no return. So your self.button[i,j] is <code>None</code>!</p> <p>Just do it in 2 lines: <code>self.button[i,j]=Button(self.root,text="*",padx=12,pady=12)</code> and <code>self.button[i,j].grid(row=i,column=j)</code></p>
0
2016-09-02T07:26:28Z
[ "python", "button", "tkinter" ]
Using Python to kick off Python subprocesses without delay
39,283,306
<p>I want to launch multiple instances of a python script using <code>subprocess.call</code>, but the kick off script waits for each to complete. How do I prevent it from waiting from going one by one, without waiting for the previous job to complete?</p> <pre><code>step = 5 for n in range(5, 11, step): subprocess.call(["python", cwd + "/" + "subprocess.py", str(n - step), str(n)]) </code></pre>
1
2016-09-02T02:05:54Z
39,283,326
<p>From the <code>subprocess</code> documentation (emphasis mine):</p> <ul> <li>Run command with arguments. <strong>Wait for command to complete</strong>, then return the returncode attribute.</li> </ul> <p>Consider using <a href="https://docs.python.org/2.6/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>Popen</code></a> instead (see also <a class='doc-link' href="http://stackoverflow.com/documentation/python/1393/subprocess-library/5714/advanced-usage-with-popen#t=201609020209559169763">stackoverflow documentation</a>).</p>
1
2016-09-02T02:09:30Z
[ "python", "concurrency", "subprocess" ]
Using Python to kick off Python subprocesses without delay
39,283,306
<p>I want to launch multiple instances of a python script using <code>subprocess.call</code>, but the kick off script waits for each to complete. How do I prevent it from waiting from going one by one, without waiting for the previous job to complete?</p> <pre><code>step = 5 for n in range(5, 11, step): subprocess.call(["python", cwd + "/" + "subprocess.py", str(n - step), str(n)]) </code></pre>
1
2016-09-02T02:05:54Z
39,283,351
<p>That's the documented behaviour of <a href="https://docs.python.org/3/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call()</code></a> so you can't use it that way. Instead you can use <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>subprocess.Popen()</code></a>.</p> <pre><code>import subprocess import os.path processes = [] step = 5 for n in range(5, 11, step): processes.append(subprocess.Popen(['python', os.path.join(cwd, 'child.py'), str(n - step), str(n)])) for p in processes: # wait for the child processes to terminate, avoid zombies p.wait() </code></pre> <p>Note that it is a bad idea to name a file <code>subprocess.py</code>, especially if it is in the same directory as your main script - an <code>import subprocess</code> will import the local version, not the system version. I've renamed it to <code>child.py</code> in the above code.</p> <p>It is also important that the parent process waits for the child processes. Omitting this can lead to <a href="https://en.wikipedia.org/wiki/Zombie_process" rel="nofollow">"zombie" processes</a> in Linux.</p> <p>If you are using Python 3 you could investigate use of the <a href="https://docs.python.org/3/library/asyncio.html#module-asyncio" rel="nofollow"><code>asyncio</code></a> module.</p>
3
2016-09-02T02:13:21Z
[ "python", "concurrency", "subprocess" ]
Python to view and manipulate web page
39,283,333
<p>I want to use Python to edit an element on a webpage. I've been trying to figure out how to use selenium to do that. Right now, this is what I have so far...</p> <pre><code>driver = webdriver.Chrome() driver.get('https://www.website.com') elem = driver.find_element_by_id('id') print(elem) </code></pre> <p>Reading through the documentation (<a href="http://selenium-python.readthedocs.io/getting-started.html" rel="nofollow">http://selenium-python.readthedocs.io/getting-started.html</a>) I noticed they do the following</p> <pre><code>elem.send_keys("pycon") elem.send_keys(Keys.RETURN) </code></pre> <p>But I'm a little confused...is that changing the id name? I want to change a different aspect of the element I find. If you could point me in the right direction, or help me print out something more useful than elem (typical output looks like this (session="8428be97c843ee6fecc9038bceccbc0e", element="0.0761228464802568-1")), I'd really appreciate it!</p>
0
2016-09-02T02:10:29Z
39,283,359
<p>Selenium isn't a tool to edit elements on website. It used commonly to automate tests imitating user behavior on website. </p>
2
2016-09-02T02:14:59Z
[ "python", "google-chrome", "selenium" ]
how to understand axis = 0 or 1 in Python
39,283,339
<p>From the documentation, "the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1)" And the code is </p> <pre><code>df1 = pd.DataFrame({"x":[1, 2, 3, 4, 5], "y":[3, 4, 5, 6, 7]}, index=['a', 'b', 'c', 'd', 'e']) df2 = pd.DataFrame({"y":[1, 3, 5, 7, 9], "z":[9, 8, 7, 6, 5]}, index=['b', 'c', 'd', 'e', 'f']) pd.concat([df1, df2], join='inner') # by default axis=0 </code></pre> <p>since axis=0( which I interpret as column) I think concat only considers columns that are found in both dataframes. But the acutal output considers rows that are found in both dataframes.(the only common row element 'y') So how should I understand axis=0,1 correctly?</p>
1
2016-09-02T02:11:13Z
39,283,657
<p>Interpret axis=0 to apply the algorithm down each column, or to the row labels (the index).. A more detailed schema <a href="http://stackoverflow.com/a/25774395/624829">here</a>.</p> <p>If you apply that general interpretation to your case, the algorithm here is <code>concat</code>. Thus for axis=0, it means: </p> <p><em>for each column, take all the rows down (across all the dataframes for <code>concat</code>) , and do contact them when they are in common (because you selected <code>join=inner</code>).</em> </p> <p>So the meaning would be to take all columns <code>x</code> and concat them down the rows which would stack each chunk of rows one after another. However, here <code>x</code> is not present everywhere, so it is not kept for the final result. The same applies for <code>z</code>. For <code>y</code> the result is kept as <code>y</code> is in all dataframes. This is the result you have.</p>
0
2016-09-02T02:57:03Z
[ "python", "pandas", "axis" ]
how to understand axis = 0 or 1 in Python
39,283,339
<p>From the documentation, "the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1)" And the code is </p> <pre><code>df1 = pd.DataFrame({"x":[1, 2, 3, 4, 5], "y":[3, 4, 5, 6, 7]}, index=['a', 'b', 'c', 'd', 'e']) df2 = pd.DataFrame({"y":[1, 3, 5, 7, 9], "z":[9, 8, 7, 6, 5]}, index=['b', 'c', 'd', 'e', 'f']) pd.concat([df1, df2], join='inner') # by default axis=0 </code></pre> <p>since axis=0( which I interpret as column) I think concat only considers columns that are found in both dataframes. But the acutal output considers rows that are found in both dataframes.(the only common row element 'y') So how should I understand axis=0,1 correctly?</p>
1
2016-09-02T02:11:13Z
39,284,007
<p>Data:</p> <pre><code>In [55]: df1 Out[55]: x y a 1 3 b 2 4 c 3 5 d 4 6 e 5 7 In [56]: df2 Out[56]: y z b 1 9 c 3 8 d 5 7 e 7 6 f 9 5 </code></pre> <p>Concatenated <strong>horizontally</strong> (axis=1), using <strong>index elements</strong> found in both DFs (aligned by indexes for joining):</p> <pre><code>In [57]: pd.concat([df1, df2], join='inner', axis=1) Out[57]: x y y z b 2 4 1 9 c 3 5 3 8 d 4 6 5 7 e 5 7 7 6 </code></pre> <p>Concatenated <strong>vertically</strong> (DEFAULT: axis=0), using <strong>columns</strong> found in both DFs:</p> <pre><code>In [58]: pd.concat([df1, df2], join='inner') Out[58]: y a 3 b 4 c 5 d 6 e 7 b 1 c 3 d 5 e 7 f 9 </code></pre> <p>If you don't use the <code>inner</code> join method - you will have it this way:</p> <pre><code>In [62]: pd.concat([df1, df2]) Out[62]: x y z a 1.0 3 NaN b 2.0 4 NaN c 3.0 5 NaN d 4.0 6 NaN e 5.0 7 NaN b NaN 1 9.0 c NaN 3 8.0 d NaN 5 7.0 e NaN 7 6.0 f NaN 9 5.0 In [63]: pd.concat([df1, df2], axis=1) Out[63]: x y y z a 1.0 3.0 NaN NaN b 2.0 4.0 1.0 9.0 c 3.0 5.0 3.0 8.0 d 4.0 6.0 5.0 7.0 e 5.0 7.0 7.0 6.0 f NaN NaN 9.0 5.0 </code></pre>
0
2016-09-02T03:47:10Z
[ "python", "pandas", "axis" ]
Keras: how to record validation loss
39,283,358
<p>Note: this is a <a href="http://stackoverflow.com/questions/37664783/how-to-plot-a-learning-curve-for-a-keras-experiment">duplicate question</a>, but I'm not looking for the answer. Rather, how better to find the answer myself. </p> <p>How do I record loss, training accuracy, testing loss and testing accuracy, from a model, across epochs? I'd like to plot a graph that shows validation loss against each epoch.</p> <p>I know that the <a href="https://keras.io/callbacks/" rel="nofollow">callback</a> object, which can be called in fit(), or maybe model.history has something to do with it, but examining the source and docstrings are just a wall of code to me. Numpy, for instance, typically provides a very small use case as an example of very simple implementation. And yet I know that the answer to this is just a one-liner, because this really is just a question of input.</p>
0
2016-09-02T02:14:51Z
39,291,417
<p>As detailed in the doc <a href="https://keras.io/models/sequential/#fit" rel="nofollow">https://keras.io/models/sequential/#fit</a>, when you call <code>model.fit</code>, it returns a <code>callbacks.History</code> object. You can get loss and other metrics from it:</p> <pre><code>... train_history = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, Y_test)) loss = train_history.history['loss'] val_loss = train_history.history['val_loss'] plt.plot(loss) plt.plot(val_loss) plt.legend(['loss', 'val_loss']) plt.show() </code></pre>
2
2016-09-02T11:35:22Z
[ "python", "keras" ]
Python script to convert strings from hex to bin contained in a txt
39,283,382
<p>I am looking for a simple script possibly in python that can: -convert a list of 4 bytes Hexadecimal strings to Decimal</p> <p>Something that would look like" script.py infile.txt outfile.txt</p>
-8
2016-09-02T02:17:47Z
39,284,783
<pre><code>filename = "infile.txt" with open(filename, 'r') as f: content = f.read() out = int(content, 16) f = open('outfile.txt', 'w') f.write(str(out)) f.close() </code></pre> <p>This is what I came up with so far... It works well if infile contains only one line... I still need to figure out to do it line by line...</p>
2
2016-09-02T05:20:20Z
[ "python", "hex", "decimal" ]
How to move the turtle where I want to go
39,283,423
<p>So I'm trying to complete this question on my programming course, and it involves drawing stuff with the turtle. Basically, I'm trying to draw a city skyline, so the program needs to read multiple inputs from the user on one line (the heights of the buildings). I can get it to draw a building, but it only uses the last y-value.</p> <pre><code>from turtle import * h = input("Heights: ") y = h.split() nxc = -200 #Code for the background fillcolor("darkslategray") for i in y: for i in y: nyc = i pencolor("black") pendown() begin_fill() goto(nxc, nyc) right(90) forward(20) right(90) forward(nyc) right(90) forward(20) right(90) forward(nyc) end_fill() nxc = nxc + 20 </code></pre> <p>Help please!</p> <p>Here's a picture: <a href="http://i.stack.imgur.com/OsWbA.png" rel="nofollow">Description of the question</a> <a href="http://i.stack.imgur.com/suQ7M.png" rel="nofollow">Some of the specifics</a></p>
-2
2016-09-02T02:23:03Z
39,283,459
<p>Take out your second <code>for</code> loop:</p> <pre><code>from turtle import * h = input("Heights: ") y = h.split() nxc = -200 #Code for the background fillcolor("darkslategray") for i in y: nyc = i pencolor("black") pendown() begin_fill() goto(nxc, nyc) right(90) forward(20) right(90) forward(nyc) right(90) forward(20) right(90) forward(nyc) end_fill() nxc = nxc + 20 </code></pre> <p>This second loop will always reach the end, updating <code>nyc</code> each time, before it exits. Thus, for every iteration, <code>nyc</code> will advance to the final value before Python gets to your drawing code.</p>
-1
2016-09-02T02:27:45Z
[ "python", "turtle-graphics" ]
Conway's game of life rules not operating properly in python
39,283,491
<p>I am attempting to do a list based implementation of Conway's game of life without using any add-ons or lists of lists in python 3.5.2. The issue I am running into now is that the number of "neighbors" that each point has is incorrect. I have left my print statement in the code below. In this example, an occupied cell is denoted by a "o" while an unoccupied cell is denoted by a "."</p> <pre><code>#Determine how many neighbors are surrounding the provided point def getNeighbors(board, index, columns): neighbors = 0 try: if(board[index + 1] == "o"): neighbors += 1 except: pass try: if(board[index - 1] == "o"): neighbors += 1 except: pass try: if(board[index + columns] == "o"): neighbors += 1 except: pass try: if(board[index - columns] == "o"): neighbors += 1 except: pass try: if(board[index - columns + 1] == "o"): neighbors += 1 except: pass try: if(board[index - columns - 1] == "o"): neighbors += 1 except: pass try: if(board[index + columns + 1] == "o"): neighbors += 1 except: pass try: if(board[index + columns - 1] == "o"): neighbors += 1 except: pass return neighbors #Creates the game board in a list of lists def mkBoard(rows,columns): board = ["."] * rows * columns return board #Used to edit a point on the game board def editPoint(x,y,board,columns): i = 0 i = x + ((y - 1) * columns) - 1 if( board[i] == "o"): board[i] = "." elif( board[i] == "."): board[i] = "o" return board #Simulates the next step in the game def nextTurn(board, columns): prevBoard = board i = 0 for index in prevBoard: neighbors = 0 if( index == 'o'): neighbors = getNeighbors(prevBoard, i, columns) print(neighbors) if(neighbors == 0 or neighbors == 1): board[i] = "." elif(neighbors &gt;= 4): board[i] = "." elif(index == "."): neighbors = getNeighbors(prevBoard, i, columns) print(neighbors) if(neighbors == 3): board[i] = "o" i += 1 return board #Prints the board to the screen to show the user what is happening def printBoard(board, columns): counter = 0 for cell in board: print(cell,end=" ") counter += 1 if( counter == columns): print('\n') counter = 0 print("======Conway's Game of Life======") #Take user input for number of rows and columns for the board and converts them into integers rows = input('Enter the number of rows:') rows = int(rows) columns = input('Enter the number of columns:') columns = int(columns) #Create the board and show it to the user board = mkBoard(rows,columns) printBoard(board,columns) choice = 0 #If the user wants to add points to the board they can, otherwise they can begin the game while( 1 != 3): choice = input('Make a choice:\n1) Change a point\n2) Continue the game\n3) Quit\n') if(choice =='1'): x = input('Enter the x coordinate of the point to negate: ') x = int(x) y = input('Enter the y coordinate of the point to negate: ') y = int(y) board = editPoint(x,y,board, rows) printBoard(board,columns) elif(choice =='2'): board = nextTurn(board, columns) printBoard(board,columns) elif(choice == '3'): break </code></pre>
0
2016-09-02T02:32:30Z
39,285,213
<p>I found two mistakes:</p> <ol> <li>At <code>board = editPoint(x,y,board, rows)</code> you should pass <code>columns</code> instead of <code>rows</code>.</li> <li><p>In <code>nextTurn</code>, <code>prevBoard = board</code> doesn't do what you think it does. An assignment does not create a copy of the list. Both variables reference the <em>same</em> list object. See this example:</p> <p><code>&gt;&gt;&gt; a= [0,1]</code></p> <p><code>&gt;&gt;&gt; b= a</code></p> <p><code>&gt;&gt;&gt; a[0]= 9</code></p> <p><code>&gt;&gt;&gt; b # output: [9, 1]</code> </p> <p>To create a copy of the list, use <code>prevBoard= board[:]</code> .</p></li> </ol>
0
2016-09-02T05:55:19Z
[ "python", "list", "conways-game-of-life" ]
Save and reset parameters of multilayer networks in theano
39,283,560
<p>We can save and load object in python using <code>six.moves.cPickle</code>. </p> <p>I saved and reset the parameters for LeNet using the following code.</p> <pre><code># save model # params = layer3.params + layer2.params + layer1.params + layer0.params import six.moves.cPickle as pickle f = file('best_cnnmodel.save', 'wb') pickle.dump(params, f, protocol=pickle.HIGHEST_PROTOCOL) f.close() # reset parameters model_file = file('best_cnnmodel.save', 'rb') params = pickle.load(model_file) model_file.close() layer3.W.set_value(params[0].get_value()) layer3.b.set_value(params[1].get_value()) layer2.W.set_value(params[2].get_value()) layer2.b.set_value(params[3].get_value()) layer1.W.set_value(params[4].get_value()) layer1.b.set_value(params[5].get_value()) layer0.W.set_value(params[6].get_value()) layer0.b.set_value(params[7].get_value()) </code></pre> <p>The code seems to be ok for LeNet. But it is not elegant. For deep networks, I can not save models using this code. What can I do in this case?</p>
0
2016-09-02T02:41:18Z
39,284,235
<p>You can consider to use json format. It is human readable and easy to work with.</p> <p>Here is an example:</p> <h1>Prepare the data</h1> <pre><code>import json data = { 'L1' : { 'W': layer1.W, 'b': layer1.b }, 'L2' : { 'W': layer2.W, 'b': layer2.b }, 'L3' : { 'W': layer3.W, 'b': layer3.b }, } json_data = json.dumps(data) </code></pre> <p>The <code>json_data</code> looks like this: </p> <pre><code>{"L2": {"b": 2, "W": 17}, "L3": {"b": 2, "W": 10}, "L1": {"b": 2, "W": 1}} </code></pre> <h1>Unpack the data</h1> <pre><code>params = json.loads(json_data) for k, v in params.items(): level = int(k[1:]) # assume you save the layer in an array, but you can use # different way to store and reference the layers layer = layers[level] layer.W = v['W'] layer.b = v['b'] </code></pre>
0
2016-09-02T04:17:34Z
[ "python", "save", "load", "theano", "conv-neural-network" ]
How do i run python script on all files in a directory?
39,283,608
<pre><code>import pyfits file = input('Enter file name as string: ') newfile = file.replace('.fits','.dat') f = pyfits.getdata(file) h = pyfits.getheader(file) g = open(newfile,'w') ref = h['JD_REF'] for x in range (len(f)): deltat = (f[x][0]-ref)/86400 refday = ref/86400 time = refday + deltat mag = f[x][3] err = f[x][4] flag = f[x][8] g.write('%9s %9s %10s %2s\n'% (time,mag,err,flag)) g.close() </code></pre> <p>I am trying to convert a .fits file containing a table of data into a .dat file. This program performs the necessary functions that I want, but it only performs the action one at a time. I have around 300 .fits files that need to be converted and doing them all by typing in the name each time would be painful. I would like it to where I can just select to run the program and it would cycle through and perform the script on all files in my directory. </p> <p>How can I modify this program to run on all of the files that are in the current directory?</p>
1
2016-09-02T02:48:35Z
39,283,631
<p>Use <code>os.listdir()</code>. If you only want to return the files that match the <code>'.fits'</code> pattern, you can use <code>glob.glob('*.fits')</code>.</p> <p>This will return all files in the current directory, or whatever directory you supply it as an argument. You can loop over these names, and use those as your input files. Something like:</p> <pre><code>for f in os.listdir(): newfile = f.replace('.fits', '.dat') # all the rest of your code </code></pre>
1
2016-09-02T02:52:26Z
[ "python", "scripting", "directory", "save" ]
Python word length
39,283,611
<p>Is there a way that I can set only some variables.</p> <pre><code>l1, l2, l3, l4, l5, l6, l7, l8, l9, = (' ',)*9 word = input("Choose up to a 9 letter word: ") wordlist = list(word) wordl = len(word) l1, l2, l3, l4, l5, l6, l7, l8, l9, = (wordlist) </code></pre> <p>More specifically is there a way that if someone enters a 6 letter word that it will only set up l6 and leave l7-l9 blank? </p>
0
2016-09-02T02:49:14Z
39,283,693
<p>You can pad the input iterable with something like <code>None</code>, then slice the padded iterable to the expected length.</p> <pre><code>l1, l2, l3, l4, l5, l6, l7, l8, l9 = (list(word) + [None]*8)[:9] </code></pre> <p>No matter how short <code>word</code> is, the combined word/<code>None</code> list has at least 9 characters; the slice trims the extras.</p> <p>However, more often you don't need separate variables for each letter; just store the list <code>l = list(word)</code> and use <code>l[i]</code> in place of each individual <code>l</code>-variable.</p>
0
2016-09-02T03:03:18Z
[ "python", "python-3.x" ]
Python word length
39,283,611
<p>Is there a way that I can set only some variables.</p> <pre><code>l1, l2, l3, l4, l5, l6, l7, l8, l9, = (' ',)*9 word = input("Choose up to a 9 letter word: ") wordlist = list(word) wordl = len(word) l1, l2, l3, l4, l5, l6, l7, l8, l9, = (wordlist) </code></pre> <p>More specifically is there a way that if someone enters a 6 letter word that it will only set up l6 and leave l7-l9 blank? </p>
0
2016-09-02T02:49:14Z
39,283,703
<p>You don't need to do any of that. If you want to fill unused characters with a space, you can use <code>str.ljust</code> or string formatting.</p> <pre><code>&gt;&gt;&gt; 'word'.ljust(9) 'word ' &gt;&gt;&gt; '{:&lt;9}'.format('word') 'word ' </code></pre>
1
2016-09-02T03:04:43Z
[ "python", "python-3.x" ]
Python word length
39,283,611
<p>Is there a way that I can set only some variables.</p> <pre><code>l1, l2, l3, l4, l5, l6, l7, l8, l9, = (' ',)*9 word = input("Choose up to a 9 letter word: ") wordlist = list(word) wordl = len(word) l1, l2, l3, l4, l5, l6, l7, l8, l9, = (wordlist) </code></pre> <p>More specifically is there a way that if someone enters a 6 letter word that it will only set up l6 and leave l7-l9 blank? </p>
0
2016-09-02T02:49:14Z
39,284,034
<p>I really don't understand what you are trying to do, but if you want to assign values to <code>l1</code>, <code>l2</code>... <code>l9</code> based on the suffix(number) where the suffix corresponds to the length word then here's the code:</p> <pre><code>&gt;&gt;&gt; l1, l2, l3, l4, l5, l6, l7, l8, l9, = (' ',)*9 ... word = input("Choose up to a 9 letter word: ") ... locals().update({'l'+str(len(w)): w for w in word.split() if len(w)&lt;10}) ... l1, l2, l3, l4, l5, l6, l7, l8, l9, Choose up to a 9 letter word: idoKtknow waht you trying ti do ? 10: ('?', 'do', 'you', 'waht', ' ', 'trying', ' ', ' ', 'idoKtknow') </code></pre>
1
2016-09-02T03:50:40Z
[ "python", "python-3.x" ]
Python word length
39,283,611
<p>Is there a way that I can set only some variables.</p> <pre><code>l1, l2, l3, l4, l5, l6, l7, l8, l9, = (' ',)*9 word = input("Choose up to a 9 letter word: ") wordlist = list(word) wordl = len(word) l1, l2, l3, l4, l5, l6, l7, l8, l9, = (wordlist) </code></pre> <p>More specifically is there a way that if someone enters a 6 letter word that it will only set up l6 and leave l7-l9 blank? </p>
0
2016-09-02T02:49:14Z
39,284,071
<p>You really should use a list. If <code>l</code> were a list (so you have <code>l[0], l[1], ..., l[9] = ...</code>), this does what you want:</p> <pre><code>for (index, letter) in enumerate(word): l[index] = letter </code></pre> <p>(I assume you have some reason to want to leave later variables unassigned. if you just want them blank a simpler string padding method is better) </p>
1
2016-09-02T03:56:37Z
[ "python", "python-3.x" ]
Converting double slash utf-8 encoding
39,283,689
<p>I cannot get this to work! I have a text file from a save game file parser with a bunch of UTF-8 Chinese names in it in byte form, like this in the source.txt:</p> <p>\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89</p> <p>But, no matter how I import it into Python (3 or 2), I get this string, at best:</p> <p>\\xe6\\x89\\x8e\\xe5\\x8a\\xa0\\xe6\\x8b\\x89</p> <p>I have tried, like other threads have suggested, to re-encode the string as UTF-8 and then decode it with unicode escape, like so:</p> <pre><code>stringName.encode("utf-8").decode("unicode_escape") </code></pre> <p>But then it messes up the original encoding, and gives this as the string:</p> <p>'æ\x89\x8eå\x8a\xa0æ\x8b\x89' (printing this string results in: æå æ )</p> <p>Now, if I manually copy and paste b + the original string in the filename and encode this, I get the correct encoding. For example:</p> <pre><code>b'\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89'.encode("utf-8") </code></pre> <p>Results in: '扎加拉'</p> <p>But, I can't do this programmatically. I can't even get rid of the double slashes. </p> <p>To be clear, source.txt contains single backslashes. I have tried importing it in many ways, but this is the most common: </p> <pre><code>with open('source.txt','r',encoding='utf-8') as f_open: source = f_open.read() </code></pre> <p>Okay, so I clicked the answer below (I think), but here is what works:</p> <pre><code>from ast import literal_eval decodedString = literal_eval("b'{}'".format(stringVariable)).decode('utf-8') </code></pre> <p>I can't use it on the whole file because of other encoding issues, but extracting each name as a string (stringVariable) and then doing that works! Thank you!</p> <p>To be more clear, the original file is not just these messed up utf encodings. It only uses them for certain fields. For example, here is the beginning of the file:</p> <pre><code>{'m_cacheHandles': ['s2ma\x00\x00CN\x1f\x1b"\x8d\xdb\x1fr \\\xbf\xd4D\x05R\x87\x10\x0b\x0f9\x95\x9b\xe8\x16T\x81b\xe4\x08\x1e\xa8U\x11', 's2ma\x00\x00CN\x1a\xd9L\x12n\xb9\x8aL\x1d\xe7\xb8\xe6\xf8\xaa\xa1S\xdb\xa5+\t\xd3\x82^\x0c\x89\xdb\xc5\x82\x8d\xb7\x0fv', 's2ma\x00\x00CN\x92\xd8\x17D\xc1D\x1b\xf6(\xedj\xb7\xe9\xd1\x94\x85\xc8`\x91M\x8btZ\x91\xf65\x1f\xf9\xdc\xd4\xe6\xbb', 's2ma\x00\x00CN\xa1\xe9\xab\xcd?\xd2PS\xc9\x03\xab\x13R\xa6\x85u7(K2\x9d\x08\xb8k+\xe2\xdeI\xc3\xab\x7fC', 's2ma\x00\x00CNN\xa5\xe7\xaf\xa0\x84\xe5\xbc\xe9HX\xb93S*sj\xe3\xf8\xe7\x84`\xf1Ye\x15~\xb93\x1f\xc90', 's2ma\x00\x00CN8\xc6\x13F\x19\x1f\x97AH\xfa\x81m\xac\xc9\xa6\xa8\x90s\xfdd\x06\rL]z\xbb\x15\xdcI\x93\xd3V'], 'm_campaignIndex': 0, 'm_defaultDifficulty': 7, 'm_description': '', 'm_difficulty': '', 'm_gameSpeed': 4, 'm_imageFilePath': '', 'm_isBlizzardMap': True, 'm_mapFileName': '', 'm_miniSave': False, 'm_modPaths': None, 'm_playerList': [{'m_color': {'m_a': 255, 'm_b': 255, 'm_g': 92, 'm_r': 36}, 'm_control': 2, 'm_handicap': 0, 'm_hero': '\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89', </code></pre> <p>All of the information before the 'm_hero': field is not utf-8. So using ShadowRanger's solution works if the file is only made up of these fake utf-encodings, but it doesn't work when I have already parsed m_hero as a string and try to convert that. Karin's solution does work for that.</p>
0
2016-09-02T03:02:56Z
39,283,815
<p>at the end of day, what you get back is a string right? i would use string.replace method to convert double slash to single slash and add b prefix to make it work. </p>
0
2016-09-02T03:21:39Z
[ "python", "unicode", "encoding", "utf-8" ]
Converting double slash utf-8 encoding
39,283,689
<p>I cannot get this to work! I have a text file from a save game file parser with a bunch of UTF-8 Chinese names in it in byte form, like this in the source.txt:</p> <p>\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89</p> <p>But, no matter how I import it into Python (3 or 2), I get this string, at best:</p> <p>\\xe6\\x89\\x8e\\xe5\\x8a\\xa0\\xe6\\x8b\\x89</p> <p>I have tried, like other threads have suggested, to re-encode the string as UTF-8 and then decode it with unicode escape, like so:</p> <pre><code>stringName.encode("utf-8").decode("unicode_escape") </code></pre> <p>But then it messes up the original encoding, and gives this as the string:</p> <p>'æ\x89\x8eå\x8a\xa0æ\x8b\x89' (printing this string results in: æå æ )</p> <p>Now, if I manually copy and paste b + the original string in the filename and encode this, I get the correct encoding. For example:</p> <pre><code>b'\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89'.encode("utf-8") </code></pre> <p>Results in: '扎加拉'</p> <p>But, I can't do this programmatically. I can't even get rid of the double slashes. </p> <p>To be clear, source.txt contains single backslashes. I have tried importing it in many ways, but this is the most common: </p> <pre><code>with open('source.txt','r',encoding='utf-8') as f_open: source = f_open.read() </code></pre> <p>Okay, so I clicked the answer below (I think), but here is what works:</p> <pre><code>from ast import literal_eval decodedString = literal_eval("b'{}'".format(stringVariable)).decode('utf-8') </code></pre> <p>I can't use it on the whole file because of other encoding issues, but extracting each name as a string (stringVariable) and then doing that works! Thank you!</p> <p>To be more clear, the original file is not just these messed up utf encodings. It only uses them for certain fields. For example, here is the beginning of the file:</p> <pre><code>{'m_cacheHandles': ['s2ma\x00\x00CN\x1f\x1b"\x8d\xdb\x1fr \\\xbf\xd4D\x05R\x87\x10\x0b\x0f9\x95\x9b\xe8\x16T\x81b\xe4\x08\x1e\xa8U\x11', 's2ma\x00\x00CN\x1a\xd9L\x12n\xb9\x8aL\x1d\xe7\xb8\xe6\xf8\xaa\xa1S\xdb\xa5+\t\xd3\x82^\x0c\x89\xdb\xc5\x82\x8d\xb7\x0fv', 's2ma\x00\x00CN\x92\xd8\x17D\xc1D\x1b\xf6(\xedj\xb7\xe9\xd1\x94\x85\xc8`\x91M\x8btZ\x91\xf65\x1f\xf9\xdc\xd4\xe6\xbb', 's2ma\x00\x00CN\xa1\xe9\xab\xcd?\xd2PS\xc9\x03\xab\x13R\xa6\x85u7(K2\x9d\x08\xb8k+\xe2\xdeI\xc3\xab\x7fC', 's2ma\x00\x00CNN\xa5\xe7\xaf\xa0\x84\xe5\xbc\xe9HX\xb93S*sj\xe3\xf8\xe7\x84`\xf1Ye\x15~\xb93\x1f\xc90', 's2ma\x00\x00CN8\xc6\x13F\x19\x1f\x97AH\xfa\x81m\xac\xc9\xa6\xa8\x90s\xfdd\x06\rL]z\xbb\x15\xdcI\x93\xd3V'], 'm_campaignIndex': 0, 'm_defaultDifficulty': 7, 'm_description': '', 'm_difficulty': '', 'm_gameSpeed': 4, 'm_imageFilePath': '', 'm_isBlizzardMap': True, 'm_mapFileName': '', 'm_miniSave': False, 'm_modPaths': None, 'm_playerList': [{'m_color': {'m_a': 255, 'm_b': 255, 'm_g': 92, 'm_r': 36}, 'm_control': 2, 'm_handicap': 0, 'm_hero': '\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89', </code></pre> <p>All of the information before the 'm_hero': field is not utf-8. So using ShadowRanger's solution works if the file is only made up of these fake utf-encodings, but it doesn't work when I have already parsed m_hero as a string and try to convert that. Karin's solution does work for that.</p>
0
2016-09-02T03:02:56Z
39,283,826
<p>You can do some silly things like <code>eval</code>uating the string:</p> <pre><code>import ast s = r'\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89' print ast.literal_eval('"%s"' % s).decode('utf-8') </code></pre> <ul> <li>note use <code>ast.literal_eval</code> if you don't want attackers to gain access to your system :-P</li> </ul> <p>Using this in your case would probably look something like:</p> <pre><code>with open('file') as file_handle: data = ast.literal_eval('"%s"' % file.read()).decode('utf-8') </code></pre> <p>I think that the real issue here is <em>likely</em> that you have a file that contains strings representing bytes (rather than having a file that just stores the bytes themselves). So, fixing whatever code generated that file in the first place is probably a better bet. However, barring that, this is the next best thing that I could come up with ...</p>
0
2016-09-02T03:22:47Z
[ "python", "unicode", "encoding", "utf-8" ]
Converting double slash utf-8 encoding
39,283,689
<p>I cannot get this to work! I have a text file from a save game file parser with a bunch of UTF-8 Chinese names in it in byte form, like this in the source.txt:</p> <p>\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89</p> <p>But, no matter how I import it into Python (3 or 2), I get this string, at best:</p> <p>\\xe6\\x89\\x8e\\xe5\\x8a\\xa0\\xe6\\x8b\\x89</p> <p>I have tried, like other threads have suggested, to re-encode the string as UTF-8 and then decode it with unicode escape, like so:</p> <pre><code>stringName.encode("utf-8").decode("unicode_escape") </code></pre> <p>But then it messes up the original encoding, and gives this as the string:</p> <p>'æ\x89\x8eå\x8a\xa0æ\x8b\x89' (printing this string results in: æå æ )</p> <p>Now, if I manually copy and paste b + the original string in the filename and encode this, I get the correct encoding. For example:</p> <pre><code>b'\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89'.encode("utf-8") </code></pre> <p>Results in: '扎加拉'</p> <p>But, I can't do this programmatically. I can't even get rid of the double slashes. </p> <p>To be clear, source.txt contains single backslashes. I have tried importing it in many ways, but this is the most common: </p> <pre><code>with open('source.txt','r',encoding='utf-8') as f_open: source = f_open.read() </code></pre> <p>Okay, so I clicked the answer below (I think), but here is what works:</p> <pre><code>from ast import literal_eval decodedString = literal_eval("b'{}'".format(stringVariable)).decode('utf-8') </code></pre> <p>I can't use it on the whole file because of other encoding issues, but extracting each name as a string (stringVariable) and then doing that works! Thank you!</p> <p>To be more clear, the original file is not just these messed up utf encodings. It only uses them for certain fields. For example, here is the beginning of the file:</p> <pre><code>{'m_cacheHandles': ['s2ma\x00\x00CN\x1f\x1b"\x8d\xdb\x1fr \\\xbf\xd4D\x05R\x87\x10\x0b\x0f9\x95\x9b\xe8\x16T\x81b\xe4\x08\x1e\xa8U\x11', 's2ma\x00\x00CN\x1a\xd9L\x12n\xb9\x8aL\x1d\xe7\xb8\xe6\xf8\xaa\xa1S\xdb\xa5+\t\xd3\x82^\x0c\x89\xdb\xc5\x82\x8d\xb7\x0fv', 's2ma\x00\x00CN\x92\xd8\x17D\xc1D\x1b\xf6(\xedj\xb7\xe9\xd1\x94\x85\xc8`\x91M\x8btZ\x91\xf65\x1f\xf9\xdc\xd4\xe6\xbb', 's2ma\x00\x00CN\xa1\xe9\xab\xcd?\xd2PS\xc9\x03\xab\x13R\xa6\x85u7(K2\x9d\x08\xb8k+\xe2\xdeI\xc3\xab\x7fC', 's2ma\x00\x00CNN\xa5\xe7\xaf\xa0\x84\xe5\xbc\xe9HX\xb93S*sj\xe3\xf8\xe7\x84`\xf1Ye\x15~\xb93\x1f\xc90', 's2ma\x00\x00CN8\xc6\x13F\x19\x1f\x97AH\xfa\x81m\xac\xc9\xa6\xa8\x90s\xfdd\x06\rL]z\xbb\x15\xdcI\x93\xd3V'], 'm_campaignIndex': 0, 'm_defaultDifficulty': 7, 'm_description': '', 'm_difficulty': '', 'm_gameSpeed': 4, 'm_imageFilePath': '', 'm_isBlizzardMap': True, 'm_mapFileName': '', 'm_miniSave': False, 'm_modPaths': None, 'm_playerList': [{'m_color': {'m_a': 255, 'm_b': 255, 'm_g': 92, 'm_r': 36}, 'm_control': 2, 'm_handicap': 0, 'm_hero': '\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89', </code></pre> <p>All of the information before the 'm_hero': field is not utf-8. So using ShadowRanger's solution works if the file is only made up of these fake utf-encodings, but it doesn't work when I have already parsed m_hero as a string and try to convert that. Karin's solution does work for that.</p>
0
2016-09-02T03:02:56Z
39,283,837
<p>So there are several different ways to interpret having the data "in byte form." Let's assume you really do:</p> <pre class="lang-py prettyprint-override"><code>s = b'\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89' </code></pre> <p>The <code>b</code> prefix indicates those are bytes. Without getting into the whole mess that is bytes vs codepoints/characters and the long differences between Python 2 and 3, the <code>b</code>-prefixed string indicates those are intended to be bytes (e.g. raw UTF-8 bytes).</p> <p>Then just decode it, which converts UTF-8 encoding (which you already have in the bytes, into true Unicode characters. In Python 2.7, e.g.:</p> <pre><code>print s.decode('utf-8') </code></pre> <p>yields:</p> <pre><code>扎加拉 </code></pre> <p>One of your examples did an encode followed by a decode, which can only lead to sorrow and pain. If your variable holds true UTF-8 bytes, you only need the decode.</p> <p><strong>Update</strong> Based on discussion, it appears the data isn't really in UTF-8 bytes, but a string-serialized version of same. There are a lot of ways to get from string serial to bytes. Here's mine:</p> <pre><code>from struct import pack def byteize(s): """ Given a backslash-escaped string serialization of bytes, decode it into a genuine byte string. """ bvals = [int(s[i:i+2], 16) for i in range(2, len(s), 4)] return pack(str(len(bvals)) + 'B', *bvals) </code></pre> <p>Then:</p> <pre><code>print byteize(s).decode('utf-8') </code></pre> <p>as before yields:</p> <pre><code>扎加拉 </code></pre> <p>This <code>byteize()</code> isn't as general as the <code>literal_eval()</code>-based <a href="http://stackoverflow.com/a/39283896/240490">accepted answer</a>, but <code>%timeit</code> benchmarking shows it to be about 33% faster on short strings. It could be further accelerated by swapping out <code>range</code> for <code>xrange</code> under Python 2. The <code>literal_eval</code> approach wins handily on long strings, however, given its lower-level nature.</p> <pre><code>100000 loops, best of 3: 6.19 µs per loop 100000 loops, best of 3: 8.3 µs per loop </code></pre>
0
2016-09-02T03:23:54Z
[ "python", "unicode", "encoding", "utf-8" ]
Converting double slash utf-8 encoding
39,283,689
<p>I cannot get this to work! I have a text file from a save game file parser with a bunch of UTF-8 Chinese names in it in byte form, like this in the source.txt:</p> <p>\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89</p> <p>But, no matter how I import it into Python (3 or 2), I get this string, at best:</p> <p>\\xe6\\x89\\x8e\\xe5\\x8a\\xa0\\xe6\\x8b\\x89</p> <p>I have tried, like other threads have suggested, to re-encode the string as UTF-8 and then decode it with unicode escape, like so:</p> <pre><code>stringName.encode("utf-8").decode("unicode_escape") </code></pre> <p>But then it messes up the original encoding, and gives this as the string:</p> <p>'æ\x89\x8eå\x8a\xa0æ\x8b\x89' (printing this string results in: æå æ )</p> <p>Now, if I manually copy and paste b + the original string in the filename and encode this, I get the correct encoding. For example:</p> <pre><code>b'\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89'.encode("utf-8") </code></pre> <p>Results in: '扎加拉'</p> <p>But, I can't do this programmatically. I can't even get rid of the double slashes. </p> <p>To be clear, source.txt contains single backslashes. I have tried importing it in many ways, but this is the most common: </p> <pre><code>with open('source.txt','r',encoding='utf-8') as f_open: source = f_open.read() </code></pre> <p>Okay, so I clicked the answer below (I think), but here is what works:</p> <pre><code>from ast import literal_eval decodedString = literal_eval("b'{}'".format(stringVariable)).decode('utf-8') </code></pre> <p>I can't use it on the whole file because of other encoding issues, but extracting each name as a string (stringVariable) and then doing that works! Thank you!</p> <p>To be more clear, the original file is not just these messed up utf encodings. It only uses them for certain fields. For example, here is the beginning of the file:</p> <pre><code>{'m_cacheHandles': ['s2ma\x00\x00CN\x1f\x1b"\x8d\xdb\x1fr \\\xbf\xd4D\x05R\x87\x10\x0b\x0f9\x95\x9b\xe8\x16T\x81b\xe4\x08\x1e\xa8U\x11', 's2ma\x00\x00CN\x1a\xd9L\x12n\xb9\x8aL\x1d\xe7\xb8\xe6\xf8\xaa\xa1S\xdb\xa5+\t\xd3\x82^\x0c\x89\xdb\xc5\x82\x8d\xb7\x0fv', 's2ma\x00\x00CN\x92\xd8\x17D\xc1D\x1b\xf6(\xedj\xb7\xe9\xd1\x94\x85\xc8`\x91M\x8btZ\x91\xf65\x1f\xf9\xdc\xd4\xe6\xbb', 's2ma\x00\x00CN\xa1\xe9\xab\xcd?\xd2PS\xc9\x03\xab\x13R\xa6\x85u7(K2\x9d\x08\xb8k+\xe2\xdeI\xc3\xab\x7fC', 's2ma\x00\x00CNN\xa5\xe7\xaf\xa0\x84\xe5\xbc\xe9HX\xb93S*sj\xe3\xf8\xe7\x84`\xf1Ye\x15~\xb93\x1f\xc90', 's2ma\x00\x00CN8\xc6\x13F\x19\x1f\x97AH\xfa\x81m\xac\xc9\xa6\xa8\x90s\xfdd\x06\rL]z\xbb\x15\xdcI\x93\xd3V'], 'm_campaignIndex': 0, 'm_defaultDifficulty': 7, 'm_description': '', 'm_difficulty': '', 'm_gameSpeed': 4, 'm_imageFilePath': '', 'm_isBlizzardMap': True, 'm_mapFileName': '', 'm_miniSave': False, 'm_modPaths': None, 'm_playerList': [{'m_color': {'m_a': 255, 'm_b': 255, 'm_g': 92, 'm_r': 36}, 'm_control': 2, 'm_handicap': 0, 'm_hero': '\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89', </code></pre> <p>All of the information before the 'm_hero': field is not utf-8. So using ShadowRanger's solution works if the file is only made up of these fake utf-encodings, but it doesn't work when I have already parsed m_hero as a string and try to convert that. Karin's solution does work for that.</p>
0
2016-09-02T03:02:56Z
39,283,896
<p>I'm assuming you're using Python 3. In Python 2, strings are bytes by default, so it would just work for you. But in Python 3, strings are unicode and interpretted as unicode, which is what makes this problem harder if you have a byte string being read as unicode.</p> <p>This solution was inspired by mgilson's answer. We can literally evaluate your unicode string as a byte string by using <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow"><code>literal_eval</code></a>:</p> <pre><code>from ast import literal_eval with open('source.txt', 'r', encoding='utf-8') as f_open: source = f_open.read() string = literal_eval("b'{}'".format(source)).decode('utf-8') print(string) # 扎加拉 </code></pre>
1
2016-09-02T03:32:23Z
[ "python", "unicode", "encoding", "utf-8" ]
Converting double slash utf-8 encoding
39,283,689
<p>I cannot get this to work! I have a text file from a save game file parser with a bunch of UTF-8 Chinese names in it in byte form, like this in the source.txt:</p> <p>\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89</p> <p>But, no matter how I import it into Python (3 or 2), I get this string, at best:</p> <p>\\xe6\\x89\\x8e\\xe5\\x8a\\xa0\\xe6\\x8b\\x89</p> <p>I have tried, like other threads have suggested, to re-encode the string as UTF-8 and then decode it with unicode escape, like so:</p> <pre><code>stringName.encode("utf-8").decode("unicode_escape") </code></pre> <p>But then it messes up the original encoding, and gives this as the string:</p> <p>'æ\x89\x8eå\x8a\xa0æ\x8b\x89' (printing this string results in: æå æ )</p> <p>Now, if I manually copy and paste b + the original string in the filename and encode this, I get the correct encoding. For example:</p> <pre><code>b'\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89'.encode("utf-8") </code></pre> <p>Results in: '扎加拉'</p> <p>But, I can't do this programmatically. I can't even get rid of the double slashes. </p> <p>To be clear, source.txt contains single backslashes. I have tried importing it in many ways, but this is the most common: </p> <pre><code>with open('source.txt','r',encoding='utf-8') as f_open: source = f_open.read() </code></pre> <p>Okay, so I clicked the answer below (I think), but here is what works:</p> <pre><code>from ast import literal_eval decodedString = literal_eval("b'{}'".format(stringVariable)).decode('utf-8') </code></pre> <p>I can't use it on the whole file because of other encoding issues, but extracting each name as a string (stringVariable) and then doing that works! Thank you!</p> <p>To be more clear, the original file is not just these messed up utf encodings. It only uses them for certain fields. For example, here is the beginning of the file:</p> <pre><code>{'m_cacheHandles': ['s2ma\x00\x00CN\x1f\x1b"\x8d\xdb\x1fr \\\xbf\xd4D\x05R\x87\x10\x0b\x0f9\x95\x9b\xe8\x16T\x81b\xe4\x08\x1e\xa8U\x11', 's2ma\x00\x00CN\x1a\xd9L\x12n\xb9\x8aL\x1d\xe7\xb8\xe6\xf8\xaa\xa1S\xdb\xa5+\t\xd3\x82^\x0c\x89\xdb\xc5\x82\x8d\xb7\x0fv', 's2ma\x00\x00CN\x92\xd8\x17D\xc1D\x1b\xf6(\xedj\xb7\xe9\xd1\x94\x85\xc8`\x91M\x8btZ\x91\xf65\x1f\xf9\xdc\xd4\xe6\xbb', 's2ma\x00\x00CN\xa1\xe9\xab\xcd?\xd2PS\xc9\x03\xab\x13R\xa6\x85u7(K2\x9d\x08\xb8k+\xe2\xdeI\xc3\xab\x7fC', 's2ma\x00\x00CNN\xa5\xe7\xaf\xa0\x84\xe5\xbc\xe9HX\xb93S*sj\xe3\xf8\xe7\x84`\xf1Ye\x15~\xb93\x1f\xc90', 's2ma\x00\x00CN8\xc6\x13F\x19\x1f\x97AH\xfa\x81m\xac\xc9\xa6\xa8\x90s\xfdd\x06\rL]z\xbb\x15\xdcI\x93\xd3V'], 'm_campaignIndex': 0, 'm_defaultDifficulty': 7, 'm_description': '', 'm_difficulty': '', 'm_gameSpeed': 4, 'm_imageFilePath': '', 'm_isBlizzardMap': True, 'm_mapFileName': '', 'm_miniSave': False, 'm_modPaths': None, 'm_playerList': [{'m_color': {'m_a': 255, 'm_b': 255, 'm_g': 92, 'm_r': 36}, 'm_control': 2, 'm_handicap': 0, 'm_hero': '\xe6\x89\x8e\xe5\x8a\xa0\xe6\x8b\x89', </code></pre> <p>All of the information before the 'm_hero': field is not utf-8. So using ShadowRanger's solution works if the file is only made up of these fake utf-encodings, but it doesn't work when I have already parsed m_hero as a string and try to convert that. Karin's solution does work for that.</p>
0
2016-09-02T03:02:56Z
39,283,941
<p>The problem is that <a href="https://docs.python.org/3/library/codecs.html#python-specific-encodings" rel="nofollow">the <code>unicode_escape</code> codec is implicitly decoding the result of the escape fixes by assuming the bytes are <code>latin-1</code>, not <code>utf-8</code></a>. You can fix this by:</p> <pre><code># Read the file as bytes: with open(myfile, 'rb') as f: data = f.read() # Decode with unicode-escape to get Py2 unicode/Py3 str, but interpreted # incorrectly as latin-1 badlatin = data.decode('unicode-escape') # Encode back as latin-1 to get back the raw bytes (it's a 1-1 encoding), # then decode them properly as utf-8 goodutf8 = badlatin.encode('latin-1').decode('utf-8') </code></pre> <p>Which (assuming the file contains the literal backslashes and codes, not the bytes they represent) leaves you with <code>'\u624e\u52a0\u62c9'</code> (Which should be correct, I'm just on a system without font support for those characters, so that's just the safe <code>repr</code> based on Unicode escapes). You could skip a step in Py2 by using the <code>string-escape</code> codec for the first stage <code>decode</code> (which I believe would allow you to omit the <code>.encode('latin-1')</code> step), but this solution should be portable, and the cost shouldn't be terrible.</p>
3
2016-09-02T03:37:49Z
[ "python", "unicode", "encoding", "utf-8" ]
django register multiple admin link to each other
39,283,729
<p>Hi im still new to django. im planning to create an admin where i can add a Quiz,Question and choice. a Quiz has a Question and a Question has a choice. I can only do (Quiz and Question) and (Question and Choice). </p> <p>here is my model.</p> <pre><code>class Quiz(models.Model): quiz_title = models.CharField(max_length=200) created_date = models.DateTimeField('date created') expired_date = models.DateTimeField( null=True, blank=True) def __str__(self): return self.quiz_title class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) answer = models.CharField(max_length=200,blank=True) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class UserSession(models.Model): #for future use. user = models.ForeignKey(User) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) user_answer = models.CharField(max_length=200) </code></pre> <p>and here is my admin from django.contrib import admin</p> <pre><code># Register your models here. from .models import Choice, Question, Quiz class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionInline(admin.TabularInline): model = Question extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date Information', {'fields': ['question_text'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_filter = ['question_text'] search_fields = ['question_text'] list_display = ('question_text',) class QuizAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['quiz_title']}), ('Date Information', {'fields': ['created_date'], 'classes': ['collapse']}), ] inlines = [QuestionInline] list_filter = ['created_date'] search_fields = ['quiz_title'] list_display = ('quiz_title', 'created_date') admin.site.register(Quiz, QuizAdmin) #~ admin.site.register(Question, QuestionAdmin) </code></pre>
0
2016-09-02T03:07:49Z
39,284,489
<p>Django doesn't support nested inlines without building this functionality yourself or using an admin nested inline app for which I am not up to date.</p> <p>A common pattern is to link directly to your child object as a new <code>ModelAdmin</code> view.</p> <p>Create a readonly field which renders the link.</p> <pre><code>class QuestionInline(admin.TabularInline): model = Question extra = 3 readonly_fields = ('link', ) def link(self, obj): return '&lt;a href="%s" target="_blank"&gt;Edit&lt;/a&gt;' % reverse('admin:appname_modelname_change', args=[obj.id]) link.allow_tags = True </code></pre>
0
2016-09-02T04:46:49Z
[ "python", "django", "django-admin" ]
Split a string into unevenly sized chunks in a repeating pattern
39,283,744
<p>I have a string representing a series of bits:</p> <pre><code>bit_stream = "10100101011101011101011" # ...(so on) </code></pre> <p>I need to split this into unevenly sized chunks in a repeating pattern. The first chunk should be length 1, followed by a chunk of length 8, then a chunk of length 2, and so on until the bits are exhausted:</p> <pre><code>result = ["1", "01001010", "11", "1", "01011101", "01", "1"] # ...(so on) </code></pre>
-2
2016-09-02T03:09:46Z
39,283,892
<p>One way is to use a class to track state and an iterator to return groups of bits. <code>itertools.cycle</code> is used to generate the bit counts repeatedly:</p> <pre><code>from itertools import cycle class Bits(object): def __init__(self,input_bits,bit_counts): self.bits = input_bits self.counts = cycle(bit_counts) def __iter__(self): while self.bits: count = next(self.counts) bits,self.bits = self.bits[:count],self.bits[count:] yield bits print(list(Bits('10100101011101011101011',(1,8,2)))) </code></pre> <p>Output:</p> <pre><code>['1', '01001010', '11', '1', '01011101', '01', '1'] </code></pre>
2
2016-09-02T03:31:47Z
[ "python", "python-2.7", "split" ]
Split a string into unevenly sized chunks in a repeating pattern
39,283,744
<p>I have a string representing a series of bits:</p> <pre><code>bit_stream = "10100101011101011101011" # ...(so on) </code></pre> <p>I need to split this into unevenly sized chunks in a repeating pattern. The first chunk should be length 1, followed by a chunk of length 8, then a chunk of length 2, and so on until the bits are exhausted:</p> <pre><code>result = ["1", "01001010", "11", "1", "01011101", "01", "1"] # ...(so on) </code></pre>
-2
2016-09-02T03:09:46Z
39,283,911
<p>I did this similarly to the other answer posted about a minute ago but I didn't use a class to track state.</p> <pre><code>import itertools def alternating_size_chunks(iterable, steps): n = 0 step = itertools.cycle(steps) while n &lt; len(iterable): next_step = next(step) yield iterable[n:n + next_step] n += next_step </code></pre> <p>Testing:</p> <pre><code>&gt;&gt;&gt; test_string = ''.join(random.choice('01') for _ in range(50)) &gt;&gt;&gt; print(list(alternating_size_chunks(test_string, (1, 8, 2)))) ['1', '01111010', '01', '1', '00111011', '11', '0', '11010100', '01', '0', '10011101', '00', '0', '11111'] </code></pre> <p>Note that both these methods (mine and Mark's answer) will take an arbitrary set of lengths (whether it's 1, 8, 2 or anything else), and will work even if the length of the bit stream doesn't precisely add up to a multiple of the sum of the lengths. (You can see in my example it ran out of bits and the last chunk only has five.) This may or may not be desirable in your case, so you might want to check that you have enough data to convert once you get ready to do that.</p> <p>Reference: <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow"><code>itertools.cycle</code></a></p>
2
2016-09-02T03:33:40Z
[ "python", "python-2.7", "split" ]
Split a string into unevenly sized chunks in a repeating pattern
39,283,744
<p>I have a string representing a series of bits:</p> <pre><code>bit_stream = "10100101011101011101011" # ...(so on) </code></pre> <p>I need to split this into unevenly sized chunks in a repeating pattern. The first chunk should be length 1, followed by a chunk of length 8, then a chunk of length 2, and so on until the bits are exhausted:</p> <pre><code>result = ["1", "01001010", "11", "1", "01011101", "01", "1"] # ...(so on) </code></pre>
-2
2016-09-02T03:09:46Z
39,284,219
<pre><code>bit_stream = "10100101011101011101011" fmt = [1,8,2] i = 0 j = 0 lenb = len( bit_stream ) result = [] while True: l = j + fmt[i] if l &lt; lenb: result.append( bit_stream[j:l] ) else: result.append( bit_stream[j:lenb] ) break j = l i = i + 1 if i &gt; 2: i = 0 print result </code></pre> <p>Output:</p> <pre><code>['1', '01001010', '11', '1', '01011101', '01', '1'] </code></pre>
0
2016-09-02T04:15:26Z
[ "python", "python-2.7", "split" ]
Django NoReverseMatch wrong number of arguments
39,283,760
<p>I am getting a NoReverseMatch error after having added a new argument to one of my URLs. Initially, the URL in <code>urlpatterns</code> had been</p> <pre><code>url(r'^(?P&lt;myID&gt;[0-9]+)/go/(?P&lt;otherID&gt;[0-9]+)/$', views.go, name='go') </code></pre> <p>and this worked. I changed it to </p> <pre><code>url(r'^(?P&lt;myID&gt;[0-9]+)/go/(?P&lt;listID&gt;[0-9]+)/(?P&lt;otherID&gt;[0-9]+)/$', views.go, name='go') </code></pre> <p>and updated the function <code>go</code> in views.py to accept another argument (<code>def go(request,myID,listID,otherID):#...</code>). The new argument is not being recognized. When I try to go to <code>my_app/18/go/14/12/</code> (for example) from my local server it gives the error </p> <pre><code>Reverse for 'go' with arguments '(18, 12)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['frackr/(?P&lt;myID&gt;[0-9]+)/go/(?P&lt;listID&gt;[0-9]+)/(?P&lt;otherID&gt;[0-9]+)/$'] </code></pre> <p>So it seems that it does not recognize the <code>listID</code> argument. However, the debugging message says that one of the local variables in the view function is <code>listID</code> with the value of <code>u'14'</code>. So the problem does not seem to be coming from interpreting the URL. </p> <p>I have looked through tons of questions already to try to figure this out, but no one seems to have the same problem. And I realize this is probably a beginner's mistake, but any help would be greatly appreciated.</p>
0
2016-09-02T03:12:15Z
39,284,435
<p>Your error isn't related to your function arguments. It explicitly states the error is a <code>reverse</code> error.</p> <p>The traceback will tell you exactly where <code>reverse</code> was called from, and that function needs to be updated to use 3 arguments, not 2.</p> <p>It would be a <code>reverse()</code> call directly in python, <code>{% url %}</code> via template, <code>get_absolute_url</code> with the wrong parameters, etc., but the traceback will tell you exactly where.</p>
1
2016-09-02T04:40:27Z
[ "python", "django" ]
Django NoReverseMatch wrong number of arguments
39,283,760
<p>I am getting a NoReverseMatch error after having added a new argument to one of my URLs. Initially, the URL in <code>urlpatterns</code> had been</p> <pre><code>url(r'^(?P&lt;myID&gt;[0-9]+)/go/(?P&lt;otherID&gt;[0-9]+)/$', views.go, name='go') </code></pre> <p>and this worked. I changed it to </p> <pre><code>url(r'^(?P&lt;myID&gt;[0-9]+)/go/(?P&lt;listID&gt;[0-9]+)/(?P&lt;otherID&gt;[0-9]+)/$', views.go, name='go') </code></pre> <p>and updated the function <code>go</code> in views.py to accept another argument (<code>def go(request,myID,listID,otherID):#...</code>). The new argument is not being recognized. When I try to go to <code>my_app/18/go/14/12/</code> (for example) from my local server it gives the error </p> <pre><code>Reverse for 'go' with arguments '(18, 12)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['frackr/(?P&lt;myID&gt;[0-9]+)/go/(?P&lt;listID&gt;[0-9]+)/(?P&lt;otherID&gt;[0-9]+)/$'] </code></pre> <p>So it seems that it does not recognize the <code>listID</code> argument. However, the debugging message says that one of the local variables in the view function is <code>listID</code> with the value of <code>u'14'</code>. So the problem does not seem to be coming from interpreting the URL. </p> <p>I have looked through tons of questions already to try to figure this out, but no one seems to have the same problem. And I realize this is probably a beginner's mistake, but any help would be greatly appreciated.</p>
0
2016-09-02T03:12:15Z
39,286,020
<p>Post a complete stack trace of error so that it can be known which file is the cause for issue.</p> <p>Check your templates. There is a possibility that django is trying to call the url in templates using only two args. Try calling url in templates using namespaces and names as given below.</p> <pre><code>{% url 'go' arg1 arg2 arg3 %} </code></pre>
0
2016-09-02T06:51:38Z
[ "python", "django" ]
Run anaconda through bash file
39,283,908
<p>I have made a script in python that crops an image. I am using Anaconda for that and Python 2.7 in Windows</p> <p>What i want to do is to run this script for a whole folder with images, so i was thinking of making a bash file. I followed <a href="http://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/" rel="nofollow">these steps</a> and <em>bash on Ubuntu on Windows</em>. I installed again Anaconda for linux and some libraries needed but now i am getting <a href="http://i.stack.imgur.com/s0shU.png" rel="nofollow">this error</a> even if i have installed the same package as in Windows.</p> <p>Any ideas? Or maybe another ways to do it on Windows where my script is already running well on Anaconda?</p>
0
2016-09-02T03:33:26Z
39,284,973
<p>This may not be what you're looking for as you asked for assistance with your bash script. However, you could modify your python script to crop all the images in a specified folder using the glob function. You can run it on windows with anaconda installed.</p> <p>glob returns a list of all the file names matching the unix style flags and wildcards. A sample of how this might work for your scenario may be:</p> <pre><code>import glob files = glob.glob("c:/path/*") # where path is the path to your images to be cropped # then run your script on all the images to be cropped for f in files: # Run python script </code></pre>
1
2016-09-02T05:35:55Z
[ "python", "linux", "bash", "shell", "anaconda" ]
DJANGO Adding a User
39,284,032
<p>When I am trying to add a user for in my django admin site I get this error:</p> <p><strong>The above exception (NOT NULL constraint failed: auth_user.last_login) was the direct cause of the following exception: /usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py in get_response</strong></p> <p>I created the Super user with this command: python manage.py supersuser and was able to login with it. However, adding a user is giving me grief on proceeding with the site.</p>
0
2016-09-02T03:50:33Z
39,284,113
<p>Based on <a href="http://tutorial.djangogirls.org/en/django_admin/" rel="nofollow">this</a> tutorial:</p> <pre><code>$ python manage.py createsuperuser </code></pre> <p>And fill up the rest. Maybe try to add more details for I'm just guessing that you want to add superuser</p>
0
2016-09-02T04:02:45Z
[ "python", "django-admin" ]
Error tokenizing data
39,284,060
<p>This is my code:</p> <pre><code>import pandas import datetime from decimal import Decimal file_ = open('myfile.csv', 'r') result = pandas.read_csv( file_, header=None, names=('sec', 'date', 'sale', 'buy'), usecols=('date', 'sale', 'buy'), parse_dates=['date'], iterator=True, chunksize=100, compression=None, engine="c", date_parser=lambda dt: datetime.datetime.strptime(dt, '%Y%m%d %H:%M:%S.%f'), converters={'sale': (lambda u: Decimal(u)), 'buy': (lambda u: Decimal(u))} ) </code></pre> <p>And then I try...</p> <pre><code>result.get_chunk() </code></pre> <p>Only to get an error like this:</p> <pre><code>CParserError: Error tokenizing data. C error: Expected 3 fields in line 3, saw 4 </code></pre> <p>From a file like this (I just show the first 4 lines - the file has no header, and all the lines have this format):</p> <pre><code>EUR/USD,20160701 00:00:00.071,1.11031,1.11033 EUR/USD,20160701 00:00:00.255,1.11031,1.11033 EUR/USD,20160701 00:00:00.256,1.11025,1.11033 EUR/USD,20160701 00:00:00.258,1.11027,1.11033 ... &gt; l0.000.000 lines like these </code></pre> <p>My intention is to get an object to iterate by chunks and not have the whole crap in memory (the actual file has 560mb!). I want to discard the first column (there are 4 columns but since this file has the same value in the first column, I want to discard such column). I want to keep columns 1, 2, and 3 (discarding 0) as date, sale, and purchase price.</p> <p>Actually this is my first attempt with pandas, since the former solution used standard Python csv module, and takes a lot of time.</p> <p>What am I missing? Why am I getting such error?</p>
0
2016-09-02T03:55:12Z
39,287,343
<pre><code>#try this code import pandas as pd import numpy as np import csv # To print only three columns , create a data frame,to do that give names to columns in csv file with ',' as seperator myfile.csv: sec,date,sale,buy EUR/USD,20160701 00:00:00.071,1.11031,1.11033 EUR/USD,20160701 00:00:00.255,1.11031,1.11033 EUR/USD,20160701 00:00:00.256,1.11025,1.11033 EUR/USD,20160701 00:00:00.258,1.11027,1.11033 data = pd.read_csv('myfile.csv',sep=',') df = pd.DataFrame({'date':data.date,'sale':data.sale,'buy':data.buy}) print(df) output: buy date sale 0 1.11033 20160701 00:00:00.071 1.11031 1 1.11033 20160701 00:00:00.255 1.11031 2 1.11033 20160701 00:00:00.256 1.11025 3 1.11033 20160701 00:00:00.258 1.11027 </code></pre>
1
2016-09-02T08:06:31Z
[ "python", "pandas" ]
Why Eigen values of adajcency matrix are actually the sentence scores in Textrank
39,284,362
<p>Here is the route for TextRank:</p> <ol> <li>Document to be summarized expressed as tf-idf matrix</li> <li>(tf-idf matrix)*(tf-idf matrix).Transpose = Adjacency matrix of some graph whose vertices are actually the sentences of above document</li> <li>Page rank is applied on this graph -> returns PR values of each sentence</li> </ol> <p>Now, <strong>this PR values are actually Eigen values of that adjacency matrix</strong><br> What is the physical meaning or intuition behind this.? </p> <p><strong>Why Eigen values are actually the ranks ?</strong></p> <p>Here is the link for Page Rank: <a href="http://www.cs.princeton.edu/~chazelle/courses/BIB/pagerank.htm" rel="nofollow">http://www.cs.princeton.edu/~chazelle/courses/BIB/pagerank.htm</a></p> <p>Here is an extract from above page: <br> <strong>PageRank or PR(A) can be calculated using a simple iterative algorithm, and corresponds to the principal eigenvector of the normalized link matrix of the web.</strong></p> <p>Link for TextRank: <a href="https://joshbohde.com/blog/document-summarization" rel="nofollow">https://joshbohde.com/blog/document-summarization</a></p>
4
2016-09-02T04:33:19Z
39,295,580
<p>To begin with, your question is a bit mistaken. The eignevalues are <em>not</em> the scores. Rather, the <em>entries of the stationary eigenvector</em> are the scores.</p> <p>Textrank works on a <a href="https://web.eecs.umich.edu/~mihalcea/papers/mihalcea.emnlp04.pdf" rel="nofollow">graphical approach to words</a>. It has a number of variations, but they have the following common steps:</p> <ol> <li><p>Create a weighted graph where the vertices are entities (words or sentences), and the weights are the transition probabilities between entities.</p></li> <li><p>Find the <a href="https://en.wikipedia.org/wiki/Stochastic_matrix" rel="nofollow">stochastic matrix</a> associated with the graph, and score each entity according to its stationary distribution.</p></li> </ol> <p>In this case, the graph is built as follows. First, a matrix is built where the rows are sentences and the columns are words. The entries of the matrix are specified by TF-IDF. To find the similarity between sentences, the normalized matrix is multiplied by its transform. This is because, for each two sentences and a word, there is a similarity between the sentences based on the product of the TF-IDF of the word in each sentence, and we need to sum up over all words. If you think about it a bit, summing up the products is exactly what matrix multiplication by the transpose does.</p> <p>So now we have a stochastic matrix <em>P</em> which can be interpreted as the probability of transition from sentence <em>i</em> to sentence <em>j</em>. The score is the stationary distribution <em>x</em>, which means that</p> <p><em>P x = x = 1 x</em>.</p> <p>This means that <em>x</em> is the eigenvector associated with the eigenvalue 1. By the <a href="https://en.wikipedia.org/wiki/Perron%E2%80%93Frobenius_theorem" rel="nofollow">Perron-Frobenius Theorem</a>, this eigenvector exists under some mild conditions, and 1 is the largest eigenvalue. This last part is basically Pagerank.</p>
2
2016-09-02T15:06:50Z
[ "python", "nlp", "eigenvector", "pagerank", "summarization" ]
Adding nodes and edges to graph data structure dynamically in Matlab
39,284,401
<p>I usually create graphs in matlab as follows:</p> <pre><code>g=sparse(5,5); g(2,3)=1; </code></pre> <p>and so on.</p> <p>This works very well if i have the graph created in advance and given to me figuratively so that i have to make a adjacency matrix representing that graph. But now i have a different kind of problem. I have to create the graph from scratch dynamically. I have a bunch of nodes, say 500 nodes. Now i have to loop over these 500 nodes and if certain conditions are satisfied i will put some of the nodes, say 200 in my graph structure. Then i will run a loop over different pairs of nodes in this pool of 200 nodes and if certain conditions are satisfied, then i will add an edge.</p> <p>I am working in Matlab and one method i could figure was that i will just intialise an adjacency matrix of size 500x500. And just add edges for the ones that pass the criterion. This is undesirable. I don't want to include the 500 points in my graph structure at all. </p> <p>Basically, I want to do this in Matlab. In pseudo-codes in research papers, it is told:</p> <pre><code>Add vertex v0 to graph G. </code></pre> <p>How can i implement this?</p> <p>And then later a pseudo-code tells </p> <pre><code>Add edge (v0,v1) to graph G. </code></pre> <p>And lastly if there is already an edge in the graph <code>(v0,v1)</code> and you are told:</p> <pre><code>Delete edge (v0,v1) % Not asking you to delete the nodes. Add node v. Add edges (v0,v) and (v,v1) </code></pre> <p>I want to do these steps efficiently. I want to be able to create my graph dynamically. I don't want to create a huge adjacency matrix and then designate edges in it. I want to build my graph step-by-step if needed. If this can be done in Matlab please let me know. Otherwise i am open to python also. </p>
1
2016-09-02T04:37:41Z
39,293,162
<p>Have you tried looking into MATLAB's new-ish <code>graph</code> class? It was introduced in R2015b and has methods you can use to do these steps efficiently. Specifically, it has <code>addnode</code>, <code>addedge</code>, <code>rmedge</code>, etc. You can also extract the adjacency matrix from the <code>graph</code> object with <code>adjacency</code>.</p> <p><a href="http://www.mathworks.com/help/matlab/graph-and-network-algorithms.html" rel="nofollow">http://www.mathworks.com/help/matlab/graph-and-network-algorithms.html</a></p>
0
2016-09-02T13:04:15Z
[ "python", "algorithm", "matlab", "graph" ]
How was this Python Turtle graphic made?
39,284,448
<p>My friend showed me this amazing image that she made using Python's inbuilt <a href="https://docs.python.org/2/library/turtle.html" rel="nofollow">Turtle module</a> and challenged me to find out how it was made. She gave me one hint: the image was produced with 10 lines of code. </p> <p><img src="http://i.imgur.com/M8c7BiP.jpg" alt="10 Line Turtle Graphic"></p> <p>From my question you probably already know that I have no clue. I've tried a whole heap of things, but I don't know how she made a filled in circle with <em>such</em> detailed patterns in only 10 lines. I've given up on figuring it out myself, and my friend won't tell me, so anyone who can produce 10 lines that make a similar image gets all the credit for figuring it out :P</p> <p>Note: I'm not sure if this is appropriate for StackOverflow, so I'm happy to ask elsewhere (let me know), but this <em>was</em> made using Python code, so I thought someone on a programming forum might have the experience to work it out.</p>
1
2016-09-02T04:41:44Z
39,285,344
<p>Thanks to @citaret and @JerryJeremiah's suggestions, I was able to put together something that produces similar results to the image, in less than 10 lines:</p> <pre><code>from turtle import Turtle, Screen mr_turtle = Turtle() screen = Screen() mr_turtle.speed(0) for i in range(1800): mr_turtle.forward(300) mr_turtle.right(179.9) screen.exitonclick() </code></pre> <p>Thanks guys!</p>
1
2016-09-02T06:05:39Z
[ "python", "graphics", "turtle-graphics" ]
How was this Python Turtle graphic made?
39,284,448
<p>My friend showed me this amazing image that she made using Python's inbuilt <a href="https://docs.python.org/2/library/turtle.html" rel="nofollow">Turtle module</a> and challenged me to find out how it was made. She gave me one hint: the image was produced with 10 lines of code. </p> <p><img src="http://i.imgur.com/M8c7BiP.jpg" alt="10 Line Turtle Graphic"></p> <p>From my question you probably already know that I have no clue. I've tried a whole heap of things, but I don't know how she made a filled in circle with <em>such</em> detailed patterns in only 10 lines. I've given up on figuring it out myself, and my friend won't tell me, so anyone who can produce 10 lines that make a similar image gets all the credit for figuring it out :P</p> <p>Note: I'm not sure if this is appropriate for StackOverflow, so I'm happy to ask elsewhere (let me know), but this <em>was</em> made using Python code, so I thought someone on a programming forum might have the experience to work it out.</p>
1
2016-09-02T04:41:44Z
39,285,356
<p>Here is what I believe your looking for:</p> <pre><code>Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import turtle &gt;&gt;&gt; t = turtle.Pen() &gt;&gt;&gt; for i in range(1000): ... t.forward(100) ... t.backward(100) ... t.left(79) ... </code></pre> <p>output:</p> <p><a href="http://i.stack.imgur.com/Ue8QG.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ue8QG.png" alt="enter image description here"></a></p> <p>It is a miniature example of the output you showed in your question. Basicly the way that is works is that each time the turtle pen goes forward and comes back, the pen turns. This is repeated multiple times, to create those 'detailed patterns'. Also, your friend may have mislead you a bit, as this is much shorter than ten lines.</p>
1
2016-09-02T06:06:24Z
[ "python", "graphics", "turtle-graphics" ]
How was this Python Turtle graphic made?
39,284,448
<p>My friend showed me this amazing image that she made using Python's inbuilt <a href="https://docs.python.org/2/library/turtle.html" rel="nofollow">Turtle module</a> and challenged me to find out how it was made. She gave me one hint: the image was produced with 10 lines of code. </p> <p><img src="http://i.imgur.com/M8c7BiP.jpg" alt="10 Line Turtle Graphic"></p> <p>From my question you probably already know that I have no clue. I've tried a whole heap of things, but I don't know how she made a filled in circle with <em>such</em> detailed patterns in only 10 lines. I've given up on figuring it out myself, and my friend won't tell me, so anyone who can produce 10 lines that make a similar image gets all the credit for figuring it out :P</p> <p>Note: I'm not sure if this is appropriate for StackOverflow, so I'm happy to ask elsewhere (let me know), but this <em>was</em> made using Python code, so I thought someone on a programming forum might have the experience to work it out.</p>
1
2016-09-02T04:41:44Z
39,294,579
<p>After some tuning, I find this, which, I think, is very close to the image, with exact 10 lines.</p> <pre><code>import turtle bob = turtle.Turtle() bob.speed(0) for i in range(632): bob.forward(200) bob.right(1) bob.forward(100) bob.setpos(0,0) bob.left(1.57) turtle.done() </code></pre> <p><a href="http://i.stack.imgur.com/5c48a.png" rel="nofollow"><img src="http://i.stack.imgur.com/5c48a.png" alt="first try"></a></p> <p><strong>Edit:</strong> There are more, draw with a single line, get this, which I have not expected:</p> <pre><code>import turtle bob = turtle.Turtle() bob.speed(0) for i in range(1080): bob.forward(300) bob.setpos(0,0) bob.left(0.33333) turtle.done() </code></pre> <p><a href="http://i.stack.imgur.com/lyxXT.png" rel="nofollow"><img src="http://i.stack.imgur.com/lyxXT.png" alt="draw with lines"></a> And draw with a triangle:</p> <pre><code>import turtle bob = turtle.Turtle() bob.speed(0) for i in range(720): bob.forward(50) bob.right(19) bob.forward(250) bob.setpos(0,0) bob.left(19.5) turtle.done() </code></pre> <p><a href="http://i.stack.imgur.com/ykUIy.png" rel="nofollow"><img src="http://i.stack.imgur.com/ykUIy.png" alt="draw with triangles"></a></p>
2
2016-09-02T14:16:23Z
[ "python", "graphics", "turtle-graphics" ]
Absolute linking in Python
39,284,599
<p>How can I make my links relative to the home directory (absolute linking)? I have a program that will use a file given anywhere in my user account. Code:</p> <pre><code>file_name = input("Enter file path") try: file = open("../" + file_name) print(file) except: print("Failed to open") </code></pre> <p>Currently this assumes my program is in my desktop (which it is). Can I make it so that it will work the same regardless of how many folders it is in?</p> <p><strong>EDIT</strong>: I want to make it relative to the user's home directory.</p>
0
2016-09-02T05:01:11Z
39,284,720
<pre><code>import os </code></pre> <p>home_dir = os.path.expanduser('~')</p> <pre><code>file_name = input("Enter file path") try: file = open(os.path.join(home_dir, file_name)) print(file) except: print("Failed to open") </code></pre> <p><code>os.path.expanduser('~')</code> should return the home directory of the user.</p> <p>Though I can't quite tell if you want an absolute or relative path, and whether its to the home directory or your desktop directory that you want. You may want to reword your question.</p>
1
2016-09-02T05:14:35Z
[ "python", "python-3.x", "absolute-path" ]
Sort duplicate values column A from csv file
39,284,717
<p>I am trying to sort duplicate values column A from csv file but not getting expected result in python.</p> <p>Input File: (.csv)</p> <p>Column names:</p> <pre><code>Uniprot Acc, PDB ID, Ligand ID, Structure Title, Uniprot Recommended Name, Gene Name, Macromolecular Name </code></pre> <p>I want to sort duplicates values and single of Uniport Acc column along with pdb id and ligand id.</p> <pre><code> Input file: Uni port Acc PDB ID Ligand ID * P0AET8 1AHI NAI * P04036 1ARZ NAI * Q59771 1C1D NAI * P0C0F4 1DLJ NAI * Q9QYY9 1E3E NAI * Q9QYY9 1E3I NAI * Q14376 1EK6 NAI * Q16836 1F17 NAI * P0AET8 1FMC NAI * Q46220 1GIQ NAI * P97852 1GZ6 NAI * P07195 1I0Z NAI * P00338 1I10 NAI * P11986 1JKI NAI * P10760 1KY5 NAI * Q2RSB2 1L7E NAI * Q27743 1LDG NAI * O32080 1LSU NAI * P00334 1MG5 NAI * P26392 1N2S NAI * P9WGT1 1NFQ NAI * P0ABH7 1NXG NAI * P05091 1NZW NAI * P05091 1NZZ NAI * P27443 1O0S NAI * P0A6D5 1O9B NAI * P20974 1OG4 NAI * P11986 1P1J NAI Expected Result: Uni port Acc PDB ID Ligand ID * P0AET8 1AHI NAI * P0AET8 1FMC NAI * P04036 1ARZ NAI * Q59771 1C1D NAI * P0C0F4 1DLJ NAI * Q9QYY9 1E3E NAI * Q9QYY9 1E3I NAI . . . I want to sort how many uniport acc id same with pdb id along with single id, No need to remove any id. </code></pre> <p>Code: </p> <pre><code>import csv import re import sys import os f1 = csv.reader(open('one.csv', 'rb')) writer = csv.writer(open("Output_file_1.csv", "wb")) def has_duplicates(f1): for i in range(0, len(f1)): for x in range(i + 1, len(f1)): if f1[i] == f1[x]: var = f1[i] writer.writerow(var) </code></pre>
1
2016-09-02T05:14:06Z
39,285,225
<p>You can first store all the values in a list then you can easily find the duplicate values in a sorted order. see my below code.</p> <pre><code> import csv import re import sys import os f1 = csv.reader(open('one.csv', 'rb')) writer = csv.writer(open("Output_file_1.csv", "wb")) def has_duplicates(f1): list = [] for i in range(0, len(f1)): list.append(f1[i]) for var in set([x for x in list if list.count(x) &gt; 1]): writer.writerow(var) # print only duplicate values in a sorted list </code></pre> <h1>new edits as pr your expected result</h1> <p>if can use <code>sorted</code> for this but this will give your expected result but little bit difference are there. You can use the following code to get the expected result.</p> <pre><code>def sort_duplicates(f1): for i in range(0, len(f1)): f1.insert(f1.index(f1[i])+1, f1[i]) f1.pop(i+1) for var in f1: writer.writerow(var) </code></pre> <p>I have tested with a list. This is result screen shot..</p> <pre><code>&gt;&gt;&gt; a=['P0AET8', 'Q59771', 'P0C0F4','DFC4H', 'P0AET8','Q59771','ACG5D'] &gt;&gt;&gt; print sorted(a) ['ACG5D', 'DFC4H', 'P0AET8', 'P0AET8', 'P0C0F4', 'Q59771', 'Q59771'] </code></pre> <p>And if you use the above code then this is result.</p> <pre><code>&gt;&gt;&gt; a=['P0AET8', 'Q59771', 'P0C0F4','DFC4H', 'P0AET8','Q59771','ACG5D'] &gt;&gt;&gt; for i in range(0,len(a)): ... a.insert(a.index(a[i])+1, a[i]) ... a.pop(i+1) &gt;&gt;&gt; print a ['P0AET8', 'P0AET8', 'Q59771', 'Q59771', 'P0C0F4', 'DFC4H', 'ACG5D'] </code></pre>
1
2016-09-02T05:56:31Z
[ "python" ]
Rerun code block in Python
39,284,758
<p>I was looking to try to figure out a way to write something like this:</p> <pre><code>code_that_should_not_be_run_again() with rerun_code_that_may_fail(): another_method(x) run_me_again_if_i_fail(y) code_that_should_only_be_run_if_above_succeeds() </code></pre> <p>Where the above would run that code, and catch an exception, if it was caught, then try to run the code, again. here would be a longer version of what I want:</p> <pre><code>code_that_should_not_be_run_again() try: another_method(x) run_me_again_if_i_fail(y) catch Exception: try: another_method(x) run_me_again_if_i_fail(y) catch Exception: raise Exception("Couldn't run") code_that_should_only_be_run_if_above_succeeds() </code></pre> <p>I was thinking I could probably use a generator, maybe catch that yielded content in to a lambda and then run it twice, somehow, but now sure how I can code something like this.</p> <p>Is this possible in Python? Or maybe something similar to this that can be done?</p> <p>Here's what I've tried so far:</p> <pre><code>from contextlib import contextmanager @contextmanager def run_code(): print 'will run' try: yield except SomeException: try: yield except SomeException: raise SomeException('couldn't run') </code></pre> <p><em>Edit</em> Python wont' let you do what I want to do, so you can only use decorators on functions :(</p>
1
2016-09-02T05:18:00Z
39,285,112
<p>I hope someone posts a better solution than this but I would use exactly that method, and perhaps with a decorator:</p> <pre><code>def retry_if_fails(fn, exception=Exception, *args, **kwargs): try: fn(*args, **kwargs) except exception: fn(*args, **kwargs) # if this fails again here, the exception bubbles up </code></pre> <p>Of course, the issue is that you are only calling one function in <code>retry_if_fails</code> and not a two-stepper like what you've done.</p> <p>You could create a list of functions and pass that in along with a separate list of lists for the arguments to each of the functions you want handled.</p> <pre><code>def retry_funcs(fns, all_args, all_kwargs, exception=Exception): # all_args is a list of lists # all_kwargs is a list of dicts try: for fn, args, kwargs in zip(fns, all_args, all_kwargs): fn(*args, **kwargs) except exception: for fn, args, kwargs in zip(fns, all_args, all_kwargs): fn(*args, **kwargs) </code></pre> <p>In this one, the list of lists for <code>args</code> and list of dicts for <code>kwargs</code> have to match up by order. An empty list or empty dict in either <code>all_args</code> or <code>all_kwargs</code> would enable you to not pass any args to a particular function, or only args, or only kwargs, or both.</p> <pre><code>fns = [some_func, another_func] all_args = [['a', 'b'], # args for some_func [] # no args for another_func ] all_kwargs = [{'param': 'something'}, # kwargs for some_func {} # no kwargs ] </code></pre> <p>And instead of the list of <code>funcs</code>, <code>args</code> and <code>kwargs</code> being different, it might be easier to just put them in together like what the result of <code>zip</code>-ing would be, since that's how you'd know code in the calls anyway:</p> <pre><code>fns_with_args_and_kwargs = [(some_func, ['a', 'b'], {'param': 'something'}), (another_func, [], {}) ] # and then for fn, args, kwargs in fns_with_args_and_kwargs: fn(*args, **kwargs) </code></pre>
0
2016-09-02T05:47:43Z
[ "python", "python-2.7", "generator", "yield", "with-statement" ]
Rerun code block in Python
39,284,758
<p>I was looking to try to figure out a way to write something like this:</p> <pre><code>code_that_should_not_be_run_again() with rerun_code_that_may_fail(): another_method(x) run_me_again_if_i_fail(y) code_that_should_only_be_run_if_above_succeeds() </code></pre> <p>Where the above would run that code, and catch an exception, if it was caught, then try to run the code, again. here would be a longer version of what I want:</p> <pre><code>code_that_should_not_be_run_again() try: another_method(x) run_me_again_if_i_fail(y) catch Exception: try: another_method(x) run_me_again_if_i_fail(y) catch Exception: raise Exception("Couldn't run") code_that_should_only_be_run_if_above_succeeds() </code></pre> <p>I was thinking I could probably use a generator, maybe catch that yielded content in to a lambda and then run it twice, somehow, but now sure how I can code something like this.</p> <p>Is this possible in Python? Or maybe something similar to this that can be done?</p> <p>Here's what I've tried so far:</p> <pre><code>from contextlib import contextmanager @contextmanager def run_code(): print 'will run' try: yield except SomeException: try: yield except SomeException: raise SomeException('couldn't run') </code></pre> <p><em>Edit</em> Python wont' let you do what I want to do, so you can only use decorators on functions :(</p>
1
2016-09-02T05:18:00Z
39,285,140
<p>Using the retry decorator - <a href="https://pypi.python.org/pypi/retry/" rel="nofollow">https://pypi.python.org/pypi/retry/</a> - and under the scenario that you want to catch any <code>TypeError</code>, with a maximum of 3 tries, with a delay of 5 seconds:</p> <pre><code>from retry import retry @retry(TypeError, tries=3, delay=5) def code_block_that_may_fail(): method_1() method_2() #Some more methods here... code_block_that_may_fail() </code></pre> <p>Can't get too much cleaner than that. </p> <p>Additionally, you can use the built-in logger to log failed attempts (see documentation).</p>
1
2016-09-02T05:50:06Z
[ "python", "python-2.7", "generator", "yield", "with-statement" ]
How "File not open a bytes-like object is required, not 'int' " could be solved?
39,284,781
<p>I am writing a simple http server code using socket-network-programming as a way of connection between client-server nodes.</p> <p>simply, I used my browser as client and I coded server side using python. </p> <p>Now, everything seems right but when I run the server plus browser with specific path 'filename',like (http//:localhost:8080/filename) the browser gets my exception statement that is: 404 Not Found</p> <p>I believe my trouble is here: client_socket.send("HTTP/1.1 200 OK\r\n\r\n".encode())</p> <p>The following error appears on server terminal console screen.</p> <pre><code>File not open a bytes-like object is required, not 'int' </code></pre> <p>Any help or though is appreciated.</p>
-1
2016-09-02T05:20:06Z
39,317,116
<p>The problem was very simple. All what I did after a lot of digging on the Internet is the following: client_socket.send("HTTP/1.1 200 OK\n".encode())</p> <p>Sincerely</p>
0
2016-09-04T12:54:01Z
[ "python", "http", "networking" ]
Order dictionary index in python
39,284,842
<p>I have created a order dictionary and could not get the index out of it. I have gone through the below url but not working.</p> <blockquote> <p><a href="http://stackoverflow.com/questions/15114843/accessing-dictionary-value-by-index-in-python">Accessing dictionary value by index in python</a></p> </blockquote> <p>Here is my code and output.</p> <pre><code>line_1 = OrderedDict((('A1', "Miyapur"), ('A2', "JNTU College"), ('A3', "KPHB Colony"), ('A4', "Kukatpally"), ('A5', "Balanagar"), ('A6', "Moosapet"), ('A7', "Bharat Nagar"), ('A8', "Erragadda"), ('A9', "ESI Hospital"), ('A10', "S R Nagar"), ('X1', "Ameerpet"), ('A12', "Punjagutta"), ('A13', "Irrum Manzil"), ('A14', "Khairatabad"), ('A15', "Lakdikapul"), ('A16', "('Assembly"), ('A17', "Nampally"), ('A18', "Gandhi Bhavan"), ('A19', "Osmania Medical College"), ('X2', "MG Bus station"), ('A21', "Malakpet"), ('A22', "New Market"), ('A23', "Musarambagh"), ('A24', "Dilsukhnagar"), ('A25', "Chaitanyapuri"), ('A26', "Victoria Memorial"), ('A27', "L B Nagar"))) print(line_1.values()[1]) print(line_1[1]) print(line_1.keys()[1]) </code></pre> <p>All the above options are not working as mentioned in the referenced link. Any guidance is highly appreciated. Here is the output for each print statement in the given order.</p> <blockquote> <p>TypeError: 'odict_values' object does not support indexing</p> <p>KeyError: 1</p> <p>TypeError: 'odict_keys' object does not support indexing</p> </blockquote>
0
2016-09-02T05:25:37Z
39,284,909
<blockquote> <p>TypeError: 'odict_values' object does not support indexing</p> </blockquote> <p>You need to make it into a <code>list</code> first and then access it:</p> <pre><code>print(list(line_1.values())[1]) # or print([*line_1.values()][1]) </code></pre> <p>These <code>view</code> (new in Python 3) objects act more like sets which do not support indexing they .</p> <blockquote> <p>KeyError: 1</p> </blockquote> <p>The key <code>1</code> isn't in the ordered dictionary, hence the <code>KeyError</code>. Use <em>a valid key</em> like <code>'A1</code>.</p> <blockquote> <p>TypeError: 'odict_keys' object does not support indexing</p> </blockquote> <p>As previously, make it into a <code>list</code> in order to index it.</p> <hr> <p>Same applies for <code>line_1.items</code>, in order to index it you should first cast it to an object that supports indexing (<code>list</code>, <code>tuple</code>, custom etc)</p>
2
2016-09-02T05:31:18Z
[ "python", "python-3.x", "dictionary" ]
Order dictionary index in python
39,284,842
<p>I have created a order dictionary and could not get the index out of it. I have gone through the below url but not working.</p> <blockquote> <p><a href="http://stackoverflow.com/questions/15114843/accessing-dictionary-value-by-index-in-python">Accessing dictionary value by index in python</a></p> </blockquote> <p>Here is my code and output.</p> <pre><code>line_1 = OrderedDict((('A1', "Miyapur"), ('A2', "JNTU College"), ('A3', "KPHB Colony"), ('A4', "Kukatpally"), ('A5', "Balanagar"), ('A6', "Moosapet"), ('A7', "Bharat Nagar"), ('A8', "Erragadda"), ('A9', "ESI Hospital"), ('A10', "S R Nagar"), ('X1', "Ameerpet"), ('A12', "Punjagutta"), ('A13', "Irrum Manzil"), ('A14', "Khairatabad"), ('A15', "Lakdikapul"), ('A16', "('Assembly"), ('A17', "Nampally"), ('A18', "Gandhi Bhavan"), ('A19', "Osmania Medical College"), ('X2', "MG Bus station"), ('A21', "Malakpet"), ('A22', "New Market"), ('A23', "Musarambagh"), ('A24', "Dilsukhnagar"), ('A25', "Chaitanyapuri"), ('A26', "Victoria Memorial"), ('A27', "L B Nagar"))) print(line_1.values()[1]) print(line_1[1]) print(line_1.keys()[1]) </code></pre> <p>All the above options are not working as mentioned in the referenced link. Any guidance is highly appreciated. Here is the output for each print statement in the given order.</p> <blockquote> <p>TypeError: 'odict_values' object does not support indexing</p> <p>KeyError: 1</p> <p>TypeError: 'odict_keys' object does not support indexing</p> </blockquote>
0
2016-09-02T05:25:37Z
39,284,955
<p>In Python 3, dictionaries (including <code>OrderedDict</code>) return "view" objects from their <code>keys()</code> and <code>values()</code> methods. Those are iterable, but don't support indexing. The answer you linked appears to have been written for Python 2, where <code>keys()</code> and <code>values()</code> returned lists.</p> <p>There are a few ways you could make the code work in Python 3. One simple (but perhaps slow) option would be to pass the view object to <code>list()</code> and then index it:</p> <pre><code>print(list(line_1.values())[1]) </code></pre> <p>Another option would be to use <code>itertools.islice</code> to iterate over the view object to the desired index:</p> <pre><code>import itertools print(next(itertools.islice(line_1.values(), 1, 2))) </code></pre> <p>But all of these solutions are pretty ugly. It may be that a dictionary is not the best data structure for you to use in this situation. If your data was in a simple list, it would be trivial to lookup any item by index (but lookup up by key would be harder).</p>
1
2016-09-02T05:33:55Z
[ "python", "python-3.x", "dictionary" ]
How to use `.split()` for importing tab-delimited text from a large `gzip` file? Chunks?
39,284,925
<p>I have huge <code>gzip</code> file (several GB) of tab-delimited text which I would like to parse into a pandas dataframe. </p> <p>If the contents of this file were text, one would simply use <code>.split()</code>, e.g. </p> <pre><code>file_text = """abc 123 cat 456 dog 678 bird 111 fish ... moon 1969 revolution 1789 war 1927 reformation 1517 maxwell ...""" data = [line.split() for line in file_text.split('\n')] </code></pre> <p>and then you could put the data into a pandas dataframe using</p> <pre><code>import pandas as pd df = pd.DataFrame(data) </code></pre> <p>However, this isn't a text document. It is a tab-delimited file in a gzip, with several GB of data. What is the most efficient way to parse this data into a dataframe, using <code>.split()</code>? </p> <p>I guess the first step would be to use </p> <pre><code>import gzip with gzip.open(filename, 'r') as f: file_content = f.read() </code></pre> <p>and use <code>.split()</code> on <code>file_content</code>, but saving all GB to a single variable and then splitting would be inefficient. Is it possible to do this in "chunks"? </p>
0
2016-09-02T05:31:54Z
39,285,035
<p><code>read_csv()</code> supports <code>GZIP</code>ped files, so you can simply do the following:</p> <pre><code>for chunk in pd.read_csv('/path/to/file.csv.gz', sep='\s*', chunksize=10**5): # process chunk DF </code></pre> <p>if you are sure that you have a TSV (<strong>TAB</strong> separated file), you can use <code>sep='\t'</code></p>
1
2016-09-02T05:42:12Z
[ "python", "pandas", "dataframe", "split", "gzip" ]
Parallelize pandas apply
39,284,989
<p>New to pandas, I already want to parallelize a row-wise apply operation. So far I found <a href="http://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">Parallelize apply after pandas groupby</a> However, that only seems to work for grouped data frames.</p> <p>My use case is different: I have a list of holidays and for my current row/date want to find the no-of-days before and after this day to the next holiday.</p> <p>This is the function I call via apply:</p> <pre><code>def get_nearest_holiday(x, pivot): nearestHoliday = min(x, key=lambda x: abs(x- pivot)) difference = abs(nearesHoliday - pivot) return difference / np.timedelta64(1, 'D') </code></pre> <p>How can I speed it up?</p> <h1>edit</h1> <p>I experimented a bit with pythons pools - but it was neither nice code, nor did I get my computed results.</p>
3
2016-09-02T05:37:27Z
39,315,192
<p>I think going down the route of trying stuff in parallel is probably over complicating this. I haven't tried this approach on a large sample so your mileage may vary, but it should give you an idea...</p> <p>Let's just start with some dates...</p> <pre><code>import pandas as pd dates = pd.to_datetime(['2016-01-03', '2016-09-09', '2016-12-12', '2016-03-03']) </code></pre> <p>We'll use some holiday data from <code>pandas.tseries.holiday</code> - note that in effect we want a <code>DatetimeIndex</code>...</p> <pre><code>from pandas.tseries.holiday import USFederalHolidayCalendar holiday_calendar = USFederalHolidayCalendar() holidays = holiday_calendar.holidays('2016-01-01') </code></pre> <p>This gives us:</p> <pre><code>DatetimeIndex(['2016-01-01', '2016-01-18', '2016-02-15', '2016-05-30', '2016-07-04', '2016-09-05', '2016-10-10', '2016-11-11', '2016-11-24', '2016-12-26', ... '2030-01-01', '2030-01-21', '2030-02-18', '2030-05-27', '2030-07-04', '2030-09-02', '2030-10-14', '2030-11-11', '2030-11-28', '2030-12-25'], dtype='datetime64[ns]', length=150, freq=None) </code></pre> <p>Now we find the indices of the nearest nearest holiday for the original dates using <code>searchsorted</code>:</p> <pre><code>indices = holidays.searchsorted(dates) # array([1, 6, 9, 3]) next_nearest = holidays[indices] # DatetimeIndex(['2016-01-18', '2016-10-10', '2016-12-26', '2016-05-30'], dtype='datetime64[ns]', freq=None) </code></pre> <p>Then take the difference between the two:</p> <pre><code>next_nearest_diff = pd.to_timedelta(next_nearest.values - dates.values).days # array([15, 31, 14, 88]) </code></pre> <p>You'll need to be careful about the indices so you don't wrap around, and for the previous date, do the calculation with the <code>indices - 1</code> but it should act as (I hope) a relatively good base.</p>
2
2016-09-04T08:55:46Z
[ "python", "pandas", "parallel-processing", "apply", "embarrassingly-parallel" ]
Parallelize pandas apply
39,284,989
<p>New to pandas, I already want to parallelize a row-wise apply operation. So far I found <a href="http://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">Parallelize apply after pandas groupby</a> However, that only seems to work for grouped data frames.</p> <p>My use case is different: I have a list of holidays and for my current row/date want to find the no-of-days before and after this day to the next holiday.</p> <p>This is the function I call via apply:</p> <pre><code>def get_nearest_holiday(x, pivot): nearestHoliday = min(x, key=lambda x: abs(x- pivot)) difference = abs(nearesHoliday - pivot) return difference / np.timedelta64(1, 'D') </code></pre> <p>How can I speed it up?</p> <h1>edit</h1> <p>I experimented a bit with pythons pools - but it was neither nice code, nor did I get my computed results.</p>
3
2016-09-02T05:37:27Z
39,316,680
<p>For the parallel approach this is the answer based on <a href="http://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">Parallelize apply after pandas groupby</a>:</p> <pre><code>from joblib import Parallel, delayed import multiprocessing def get_nearest_dateParallel(df): df['daysBeforeHoliday'] = df.myDates.apply(lambda x: get_nearest_date(holidays.day[holidays.day &lt; x], x)) df['daysAfterHoliday'] = df.myDates.apply(lambda x: get_nearest_date(holidays.day[holidays.day &gt; x], x)) return df def applyParallel(dfGrouped, func): retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(group) for name, group in dfGrouped) return pd.concat(retLst) print ('parallel version: ') # 4 min 30 seconds %time result = applyParallel(datesFrame.groupby(datesFrame.index), get_nearest_dateParallel) </code></pre> <p>but I prefer @NinjaPuppy's approach because it does not require O(n * number_of_holidays) </p>
0
2016-09-04T11:59:45Z
[ "python", "pandas", "parallel-processing", "apply", "embarrassingly-parallel" ]
Translate code matlab to python numpy
39,285,004
<p>I don't understand about matlab programming, I just understand coding in python...</p> <p><img src="http://i.stack.imgur.com/ww2zr.jpg" alt="here my matrix want to solve "></p> <h3>Matlab Code:</h3> <pre><code> x = ones(3,1). con = [0.505868045540458,0.523598775598299]. series = [1,2,3] for j = 1:2 #here stuck to translate Python code# x = [x cos(con(j)*series)' sin(con(j)*series)']; end </code></pre> <h3>Result :</h3> <pre><code>1.0000 0.8748 0.4846 0.8660 0.5000 1.0000 0.5304 0.8478 0.5000 0.8660 1.0000 0.0532 0.9986 -0.0000 1.0000 </code></pre> <p>Anyone help me please, how to solve this problem... Regards!</p>
2
2016-09-02T05:38:59Z
39,285,269
<p>Here's a solution that entirely removes the loop which resizes the array, which <strong>for large <code>len(con)</code></strong> should make this more efficient than the matlab solution , and by association hpaulj's direct translation - this is linear in len(con) rather than quadratic.</p> <pre><code>import numpy as np # declare the arrays con = np.array([0.505868045540458, 0.523598775598299]) series = np.array([1,2,3]) # use broadcasting to generate trig_arg[i,j] = series[i]*con[j] trig_arg = series[:,np.newaxis] * con # Add another dimension that is either cos or sin trig_elems = np.stack([np.cos(trig_arg), np.sin(trig_arg)], axis=-1) # flatten out the last two dimensions all_but_ones = trig_elems.reshape(trig_elems.shape[:-2] + (-1,)) # and add the first column of ones result = np.concatenate([ np.ones(series.shape)[:,np.newaxis], all_but_ones ], axis=-1) </code></pre> <p>Looking at each step along the way:</p> <pre><code># configure numpy output to make it easier to see what's happening &gt;&gt;&gt; np.set_printoptions(suppress=True, precision=4) &gt;&gt;&gt; trig_arg array([[ 0.5059, 0.5236], [ 1.0117, 1.0472], [ 1.5176, 1.5708]]) &gt;&gt;&gt; trig_elems array([[[ 0.8748, 0.4846], [ 0.866 , 0.5 ]], [[ 0.5304, 0.8478], [ 0.5 , 0.866 ]], [[ 0.0532, 0.9986], [-0. , 1. ]]]) &gt;&gt;&gt; all_but_ones array([[ 0.8748, 0.4846, 0.866 , 0.5 ], [ 0.5304, 0.8478, 0.5 , 0.866 ], [ 0.0532, 0.9986, -0. , 1. ]]) &gt;&gt;&gt; result array([[ 1. , 0.8748, 0.4846, 0.866 , 0.5 ], [ 1. , 0.5304, 0.8478, 0.5 , 0.866 ], [ 1. , 0.0532, 0.9986, -0. , 1. ]]) </code></pre> <p>​<code>np.stack</code> is relatively new, but can be emulated with <code>np.concatenate</code> and some <code>np.newaxis</code> slicing. Or you can just go into the numpy source code and copy the new implementation of <code>stack</code> into your project if you're stuck with an older version.</p>
0
2016-09-02T05:59:49Z
[ "python", "matlab", "numpy", "math", "computer-science" ]
Translate code matlab to python numpy
39,285,004
<p>I don't understand about matlab programming, I just understand coding in python...</p> <p><img src="http://i.stack.imgur.com/ww2zr.jpg" alt="here my matrix want to solve "></p> <h3>Matlab Code:</h3> <pre><code> x = ones(3,1). con = [0.505868045540458,0.523598775598299]. series = [1,2,3] for j = 1:2 #here stuck to translate Python code# x = [x cos(con(j)*series)' sin(con(j)*series)']; end </code></pre> <h3>Result :</h3> <pre><code>1.0000 0.8748 0.4846 0.8660 0.5000 1.0000 0.5304 0.8478 0.5000 0.8660 1.0000 0.0532 0.9986 -0.0000 1.0000 </code></pre> <p>Anyone help me please, how to solve this problem... Regards!</p>
2
2016-09-02T05:38:59Z
39,285,371
<p>My recreation in an Ipython session (having first tested your code in an Octave session):</p> <pre><code>In [649]: con = np.array([0.505868, 0.5235897]) In [650]: series = np.array([1,2,3]) In [651]: x = [np.ones((3,))] In [652]: for j in range(2): ...: x.extend([np.cos(con[j]*series), np.sin(con[j]*series)]) ...: In [653]: x Out[653]: [array([ 1., 1., 1.]), array([ 0.8747542 , 0.53038982, 0.05316725]), array([ 0.48456691, 0.84775388, 0.99858562]), array([ 8.66029942e-01, 5.00015719e-01, 2.72267949e-05]), array([ 0.49999214, 0.86601633, 1. ])] In [654]: np.array(x).T Out[654]: array([[ 1.00000000e+00, 8.74754200e-01, 4.84566909e-01, 8.66029942e-01, 4.99992140e-01], [ 1.00000000e+00, 5.30389821e-01, 8.47753878e-01, 5.00015719e-01, 8.66016328e-01], [ 1.00000000e+00, 5.31672464e-02, 9.98585622e-01, 2.72267949e-05, 1.00000000e+00]]) </code></pre> <p>In MATLAB the </p> <pre><code>x = [x cos(...) sin(...)] </code></pre> <p>is closer to</p> <pre><code>x = np.concatenate([x, cos(...), sin(...)], axis=?) </code></pre> <p>but in numpy list append (or in this case extend) is faster. I just had to initial <code>x</code> to the appropriate list.</p> <p>==================</p> <p>I can get the same values without the loop</p> <pre><code>In [663]: y = con[:,None]*series In [664]: [np.cos(y), np.sin(y)] Out[664]: [array([[ 8.74754200e-01, 5.30389821e-01, 5.31672464e-02], [ 8.66029942e-01, 5.00015719e-01, 2.72267949e-05]]), array([[ 0.48456691, 0.84775388, 0.99858562], [ 0.49999214, 0.86601633, 1. ]])] </code></pre> <p>but it's a bit of a pain to rearrange them into the order produced by iteration, <code>[1, cos, sin, cos, sin]</code>.</p>
1
2016-09-02T06:07:39Z
[ "python", "matlab", "numpy", "math", "computer-science" ]
Mac os El Capitan recording sound with python
39,285,145
<p>I'm trying to record sound from mic. Firstly as used PyAudio then sounddevice but both failed.</p> <p>Here is code for PyAudio:</p> <pre><code>import pyaudio def _recording_loop(samples_queue, running, stream, chunk_size): stream.start_stream() while running.is_set(): samples_queue.put(stream.read(chunk_size)) stream.stop_stream() class Recoder: def __init__(self, frame_rate, period): self.proc = None self.running = Event() self.samples_queue = Queue() self.frame_rate = frame_rate self.chunk_size = (frame_rate*period) / 1000 self.channels = 1 self._pa = pyaudio.PyAudio() self._stream = None def start(self): if self.proc is None: self._stream = self._pa.open(format=pyaudio.paInt8, channels=self.channels, rate=self.frame_rate, input=True, frames_per_buffer=self.chunk_size) self.running.set() self.proc = Process(target=_recording_loop, args=[self.samples_queue, self.running, self._stream, self.chunk_size]) self.proc.start() def stop(self): if self.proc is not None: self.running.clear() self.proc.join() self._stream.close() self._pa.terminate() def empty(self): return self.samples_queue.empty() def read(self): res = [] while not self.samples_queue.empty(): res.append(self.samples_queue.get()) return res </code></pre> <p>It gives me a warning: <code>Python[21648:645093] 13:42:01.242 WARNING: 140: This application, or a library it uses, is using the deprecated Carbon Component Manager for hosting Audio Units. Support for this will be removed in a future release. Also, this makes the host incompatible with version 3 audio units. Please transition to the API's in AudioComponent.h. </code> and nothing is ever recorded.</p> <p>As I understand it's something with El Capitan and not solved yet. But maybe I'm wrong? </p> <p>So I decided to switch library to sounddevice:</p> <pre><code>from multiprocessing import Process, Queue, Event import sounddevice as sd def _recording_loop(samples_queue, running, frame_rate, chunk_size): while running.is_set(): samples_queue.put(sd.rec(chunk_size, samplerate=frame_rate, channels=1, dtype='int8', blocking=True)) class Recoder: def __init__(self, frame_rate, period): self.proc = None self.running = Event() self.samples_queue = Queue() self.frame_rate = frame_rate self.period = period self.chunk_size = (frame_rate * period) / 1000 def start(self): if self.proc is None: self.running.set() self.proc = Process(target=_recording_loop, args=[self.samples_queue, self.running, self.frame_rate, self.chunk_size]) self.proc.start() def stop(self): if self.proc is not None: self.running.clear() self.proc.join() def empty(self): return self.samples_queue.empty() def read(self): res = [] while not self.samples_queue.empty(): res.append(self.samples_queue.get()) return res </code></pre> <p>And it says:</p> <pre><code>||PaMacCore (AUHAL)|| Warning on line 530: err=''who?'', msg=Audio Hardware: Unknown Property ||PaMacCore (AUHAL)|| Warning on line 534: err=''who?'', msg=Audio Hardware: Unknown Property ||PaMacCore (AUHAL)|| Warning on line 445: err=''who?'', msg=Audio Hardware: Unknown Property </code></pre> <p>And again nothing is recorded. What I'm doing wrong?</p>
1
2016-09-02T05:50:32Z
39,299,532
<p><a href="http://python-sounddevice.readthedocs.io/en/latest/#sounddevice.rec" rel="nofollow">sounddevice.rec()</a> is not meant to be used like that. You just call it with the number of frames you want to record and that's it (see the <a href="http://python-sounddevice.readthedocs.io/en/latest/#recording" rel="nofollow">example from the docs</a>):</p> <pre><code>import sounddevice as sd fs = 44100 duration = 10 # seconds myrecording = sd.rec(duration * fs, samplerate=fs, channels=2, blocking=True) </code></pre> <p>That's it. You don't need half a page of code just to record some sound.</p> <p>BTW, you can ignore the warning for now, see <a href="https://github.com/spatialaudio/python-sounddevice/issues/10" rel="nofollow">https://github.com/spatialaudio/python-sounddevice/issues/10</a>.</p>
0
2016-09-02T19:30:23Z
[ "python", "osx", "osx-elcapitan", "pyaudio", "python-sounddevice" ]
Mac os El Capitan recording sound with python
39,285,145
<p>I'm trying to record sound from mic. Firstly as used PyAudio then sounddevice but both failed.</p> <p>Here is code for PyAudio:</p> <pre><code>import pyaudio def _recording_loop(samples_queue, running, stream, chunk_size): stream.start_stream() while running.is_set(): samples_queue.put(stream.read(chunk_size)) stream.stop_stream() class Recoder: def __init__(self, frame_rate, period): self.proc = None self.running = Event() self.samples_queue = Queue() self.frame_rate = frame_rate self.chunk_size = (frame_rate*period) / 1000 self.channels = 1 self._pa = pyaudio.PyAudio() self._stream = None def start(self): if self.proc is None: self._stream = self._pa.open(format=pyaudio.paInt8, channels=self.channels, rate=self.frame_rate, input=True, frames_per_buffer=self.chunk_size) self.running.set() self.proc = Process(target=_recording_loop, args=[self.samples_queue, self.running, self._stream, self.chunk_size]) self.proc.start() def stop(self): if self.proc is not None: self.running.clear() self.proc.join() self._stream.close() self._pa.terminate() def empty(self): return self.samples_queue.empty() def read(self): res = [] while not self.samples_queue.empty(): res.append(self.samples_queue.get()) return res </code></pre> <p>It gives me a warning: <code>Python[21648:645093] 13:42:01.242 WARNING: 140: This application, or a library it uses, is using the deprecated Carbon Component Manager for hosting Audio Units. Support for this will be removed in a future release. Also, this makes the host incompatible with version 3 audio units. Please transition to the API's in AudioComponent.h. </code> and nothing is ever recorded.</p> <p>As I understand it's something with El Capitan and not solved yet. But maybe I'm wrong? </p> <p>So I decided to switch library to sounddevice:</p> <pre><code>from multiprocessing import Process, Queue, Event import sounddevice as sd def _recording_loop(samples_queue, running, frame_rate, chunk_size): while running.is_set(): samples_queue.put(sd.rec(chunk_size, samplerate=frame_rate, channels=1, dtype='int8', blocking=True)) class Recoder: def __init__(self, frame_rate, period): self.proc = None self.running = Event() self.samples_queue = Queue() self.frame_rate = frame_rate self.period = period self.chunk_size = (frame_rate * period) / 1000 def start(self): if self.proc is None: self.running.set() self.proc = Process(target=_recording_loop, args=[self.samples_queue, self.running, self.frame_rate, self.chunk_size]) self.proc.start() def stop(self): if self.proc is not None: self.running.clear() self.proc.join() def empty(self): return self.samples_queue.empty() def read(self): res = [] while not self.samples_queue.empty(): res.append(self.samples_queue.get()) return res </code></pre> <p>And it says:</p> <pre><code>||PaMacCore (AUHAL)|| Warning on line 530: err=''who?'', msg=Audio Hardware: Unknown Property ||PaMacCore (AUHAL)|| Warning on line 534: err=''who?'', msg=Audio Hardware: Unknown Property ||PaMacCore (AUHAL)|| Warning on line 445: err=''who?'', msg=Audio Hardware: Unknown Property </code></pre> <p>And again nothing is recorded. What I'm doing wrong?</p>
1
2016-09-02T05:50:32Z
39,805,131
<p>Yesterday I ran into similar problem. It seems that it's caused by using multiprocessing with sounddevice. When I do <code>import sounddevice</code> at the top of the module I get <code>||PaMacCore (AUHAL)|| Warning on line 530: err=''who?'', msg=Audio Hardware: Unknown Property</code> and then the app just hangs while creating <code>sounddevice.RawInputStream</code>. When I import sounddevice in my <code>run()</code> method (I am creating a new class based on <code>multiprocessing.Process</code>) it works fine. For me it seems that sounddevice does something to initialise itself right after being imported and this must happen in the same process that will use it. <strong>Edit:</strong> instead of <code>Multiprocessing</code> use <code>Threading</code>.</p>
0
2016-10-01T09:44:14Z
[ "python", "osx", "osx-elcapitan", "pyaudio", "python-sounddevice" ]
AttributeError: 'unicode' object has no attribute 'regex' while upgrading Django from 1.7.11 to 1.9.2
39,285,232
<p>I'm working with the "third_party" example project of pybb (<a href="https://github.com/hovel/pybbm" rel="nofollow">https://github.com/hovel/pybbm</a>) [test folder] which works fine in django 1.7.11 but I've built the rest of my website in django 1.9.2. It gives me the following traceback in 1.9.2 and I'm not able to figure out whats wrong. </p> <pre><code>Unhandled exception in thread started by &lt;function wrapper at 0x032FB6B0&gt; Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver. py", line 116, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 10, in c heck_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 27, in c heck_resolver warnings.extend(check_pattern_startswith_slash(pattern)) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 63, in c heck_pattern_startswith_slash regex_pattern = pattern.regex.pattern AttributeError: 'unicode' object has no attribute 'regex' </code></pre> <p>If it helps: My urls.py:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals try: from django.conf.urls import patterns, include, url except ImportError: from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from .forms import SignupFormWithCaptcha admin.autodiscover() from account.views import ChangePasswordView, SignupView, LoginView urlpatterns = ['', url(r'^admin/', include(admin.site.urls)), # aliases to match original django-registration urls url(r"^accounts/password/$", ChangePasswordView.as_view(), name="auth_password_change"), url(r"^accounts/signup/$", SignupView.as_view(form_class=SignupFormWithCaptcha), name="registration_register"), url(r"^accounts/login/$", LoginView.as_view(), name="auth_login"), url(r'^accounts/', include('account.urls')), url(r'^captcha/', include('captcha.urls')), url(r'^', include('pybb.urls', namespace='pybb')), ] </code></pre> <p>Any help will be greatly appreciated. Please have a look. I'm relatively new to programming in general. Thanks,</p>
1
2016-09-02T05:56:49Z
39,285,632
<p>Just try it. Remove empty string in urlpatterns.</p> <pre><code>urlpatterns = [ url(r'^admin/', include(admin.site.urls)), # aliases to match original django-registration urls url(r"^accounts/password/$", ChangePasswordView.as_view(), name="auth_password_change"), url(r"^accounts/signup/$", SignupView.as_view(form_class=SignupFormWithCaptcha), name="registration_register"), url(r"^accounts/login/$", LoginView.as_view(), name="auth_login"), url(r'^accounts/', include('account.urls')), url(r'^captcha/', include('captcha.urls')), url(r'^', include('pybb.urls', namespace='pybb')), ] </code></pre>
3
2016-09-02T06:27:56Z
[ "python", "django", "version" ]
I want to print specific line just one time in for loop using python 3.4
39,285,257
<p>I want to print specific in line just one time in for loop but insted of result in one line it gives same result four time please help me how to stop for loop after printing one line </p> <p>Here is complete html and python code also with result of this script</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul class="breadcrumbs" id="BREADCRUMBS"&gt; &lt;li class="breadcrumb_item " itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"&gt; &lt;a class="breadcrumb_link" href="/Tourism-g191-United_States-Vacations.html" itemprop="url" onclick="ta.setEvtCookie('Breadcrumbs', 'click', 'Country', 1, this.href); "&gt; &lt;span itemprop="title"&gt;United States&lt;/span&gt; &lt;/a&gt; &lt;span class="separator"&gt;›&lt;/span&gt; &lt;/li&gt; . . . .</code></pre> </div> </div> Python script which print result</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>ulpart = soup.find_all("ul", {"class": "breadcrumbs"}) for unorder in ulpart: div2 = soup.find_all("li", {"class": "breadcrumb_item "}) for listitem in div2[0:]: country = soup.select_one("li.breadcrumb_item a[onclick*=Country]").get_text(strip=True) print(country)</code></pre> </div> </div> </p> <p>Here is result of this code which print same result four time </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>United State United State United State United State</code></pre> </div> </div> </p> <p>But i want United State just one time like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>United State</code></pre> </div> </div> </p>
0
2016-09-02T05:58:48Z
39,285,334
<pre><code>printed_countries = list() ulpart = soup.find_all("ul", {"class": "breadcrumbs"}) for unorder in ulpart: div2 = soup.find_all("li", {"class": "breadcrumb_item "}) for listitem in div2[0:]: country = soup.select_one("li.breadcrumb_item a[onclick*=Country]").get_text(strip=True) if not country in printed_countries: print(country) printed_countries.append(country) </code></pre>
0
2016-09-02T06:04:49Z
[ "python", "html", "html5", "python-3.4" ]
I want to print specific line just one time in for loop using python 3.4
39,285,257
<p>I want to print specific in line just one time in for loop but insted of result in one line it gives same result four time please help me how to stop for loop after printing one line </p> <p>Here is complete html and python code also with result of this script</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul class="breadcrumbs" id="BREADCRUMBS"&gt; &lt;li class="breadcrumb_item " itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"&gt; &lt;a class="breadcrumb_link" href="/Tourism-g191-United_States-Vacations.html" itemprop="url" onclick="ta.setEvtCookie('Breadcrumbs', 'click', 'Country', 1, this.href); "&gt; &lt;span itemprop="title"&gt;United States&lt;/span&gt; &lt;/a&gt; &lt;span class="separator"&gt;›&lt;/span&gt; &lt;/li&gt; . . . .</code></pre> </div> </div> Python script which print result</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>ulpart = soup.find_all("ul", {"class": "breadcrumbs"}) for unorder in ulpart: div2 = soup.find_all("li", {"class": "breadcrumb_item "}) for listitem in div2[0:]: country = soup.select_one("li.breadcrumb_item a[onclick*=Country]").get_text(strip=True) print(country)</code></pre> </div> </div> </p> <p>Here is result of this code which print same result four time </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>United State United State United State United State</code></pre> </div> </div> </p> <p>But i want United State just one time like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>United State</code></pre> </div> </div> </p>
0
2016-09-02T05:58:48Z
39,286,086
<p>since you are using unordered lists you can use python set datatype(if you need order use list):</p> <pre><code>printed = set() ulpart = soup.find_all("ul", {"class": "breadcrumbs"}) for unorder in ulpart: div2 = soup.find_all("li", {"class": "breadcrumb_item "}) for listitem in div2[0:]: country = soup.select_one("li.breadcrumb_item a[onclick*=Country]").get_text(strip=True) printed.add(country) </code></pre>
0
2016-09-02T06:55:36Z
[ "python", "html", "html5", "python-3.4" ]
Mapping coordinates to screen in PyGame
39,285,506
<p>Ok, lots of explaining to follow, so bear with me.</p> <p>I'm making a 2D top-down game in PyGame, and I have a "chunk loading" system set up. The system is as follows...</p> <p>I have a "world" object, made up of "chunks". Each chunk is 16x16 "tiles" and contains data for each one of those tiles. In the world object, I have a system for generating these chunks as needs be, and storing them in a dictionary, like <code>{(x, y):"grass"} etc...</code> Each tile in the chunk is a 10px image, that needs to be drawn to the screen in PyGame, given the position of the camera (<em>counted in tiles</em>). I want the camera to be able to pan around over the top of these images, and move around. How on earth can I make this work?</p> <p>A quick diagram...</p> <p><img src="http://williamgardner.noip.me/files/chunks" alt="diagram"></p> <p>I hope this makes sense, thanks!</p>
0
2016-09-02T06:17:37Z
39,285,964
<p>If I understand your problem right, TomTsagk explained it really good:</p> <p><a href="http://stackoverflow.com/questions/19746552/pygame-camera-follow-in-a-2d-tile-game">Pygame camera follow in a 2d tile game</a></p> <p>Hope this helps. </p>
0
2016-09-02T06:48:16Z
[ "python", "pygame", "coordinates", "chunks" ]
How to extend/overload range() function from Python 2.7 to accept floats?
39,285,559
<p>Our core application changed from Python 2.6 to Python 2.7 maybe to Python 3 in later release.</p> <p>Range function from python is changed (quote from the Python 2.7 changelog).</p> <blockquote> <p>The <code>range()</code> function processes its arguments more consistently; it will now call <code>__int__()</code> on non-float.</p> </blockquote> <p>We allow users to add expressions / Python code based on results we process further.</p> <p>Now how to change <code>range</code> function? Some of them are using <code>float</code> argument that are failing now in Python 2.7.</p> <p>As code is written by users we cannot change in Python code/expression. There are 1000s of files. Some users may have their own files.</p> <ol> <li><p>Is there is a way to extend the <code>range()</code> function from Python, such that it will take float arguments?</p></li> <li><p>Another alternative is to parse python code and change <code>float</code> to <code>int</code>. It is very time consuming as it requires lot of sting manipulation and some <code>range</code> calls have formulas as parameter.</p></li> </ol> <p>Our application build in C++, and we evaluate python expression using C++ python APIS</p>
0
2016-09-02T06:21:33Z
39,286,239
<p>You have a serious migration issue. If you want to switch to Python 2.7 and even Python 3, there is basically no easy way around refactoring the existing (user) code base eventually. IMHO, you have the following options.</p> <ol> <li><p>Provide a permanent (non-optional) 2.6 compatible interface to your users. That means they do not have to change anything, but it kind of defeats the purpose of upgrading to Python 2.7 since the users still have to satisfy Python 2.6 semantics. <em>Verdict:</em> Not recommended.</p></li> <li><p>Provide a temporary (non-optional) 2.6 compatible interface for a limited amount of time. In that case the existing code needs to be refactored eventually. <em>Verdict:</em> Not recommended.</p></li> <li><p>Make users include a flag in their code (e.g. a magic comment that can be identified safely without executing the file like <code># *$$ supertool-pythonversion: 2.7 $$*</code>), which Python version the code expects to be run with and use 2.6 compatibility only for the files that have not been flagged with Python 2.7. That way, you can do whatever compatibility hacks are needed to run old files and run new files the way they are. <em>Verdict:</em> Increases complexity, but helps you doing the migration. <strong>Recommended</strong>.</p></li> </ol> <p>However, you are in the convenient position of calling Python from C++. So you can control the environment that scripts are run with via the <code>globals</code> and <code>locals</code> dictionary passed to <code>PyEval_EvalCode</code>. In order to implement scenario 3, after checking the compatibility flag from the file, you can put a custom <code>range</code> function which supports <code>float</code> arguments into the gloabls dictionary before calling <code>PyEval_EvalCode</code> to "enable" the compatibility mode.</p> <p>I am not proficient with Python's C API, but in Python this would look like this (and it is possible to do the same via the C API):</p> <pre><code>range27 = range def range26(start=None, stop=None, step=None): if start is not None and not isinstance(start, int): start = int(start) if stop is not None and not isinstance(stop, int): stop = int(stop) if step is not None and not isinstance(step, int): step = int(step) return range27(start, stop, step) def execute_user_code(user_file): ... src = read(user_file) global_dict = {} local_dict = {} ... if check_magic_version_comment(src) in (None, '2.6'): global_dict['range'] = range26 global_dict['range27'] = range27 # the last line is needed because the call # of range27 will be resolved against global_dict # when the user code is executed eval_code(src, global_dict, local_dict) ... </code></pre>
3
2016-09-02T07:04:53Z
[ "python", "python-2.7", "python-2.6" ]
How to extend/overload range() function from Python 2.7 to accept floats?
39,285,559
<p>Our core application changed from Python 2.6 to Python 2.7 maybe to Python 3 in later release.</p> <p>Range function from python is changed (quote from the Python 2.7 changelog).</p> <blockquote> <p>The <code>range()</code> function processes its arguments more consistently; it will now call <code>__int__()</code> on non-float.</p> </blockquote> <p>We allow users to add expressions / Python code based on results we process further.</p> <p>Now how to change <code>range</code> function? Some of them are using <code>float</code> argument that are failing now in Python 2.7.</p> <p>As code is written by users we cannot change in Python code/expression. There are 1000s of files. Some users may have their own files.</p> <ol> <li><p>Is there is a way to extend the <code>range()</code> function from Python, such that it will take float arguments?</p></li> <li><p>Another alternative is to parse python code and change <code>float</code> to <code>int</code>. It is very time consuming as it requires lot of sting manipulation and some <code>range</code> calls have formulas as parameter.</p></li> </ol> <p>Our application build in C++, and we evaluate python expression using C++ python APIS</p>
0
2016-09-02T06:21:33Z
39,289,158
<p>The change is not that calling <code>__int__</code> on non-float. The change affecting you is that float arguments are not accepted any more in Python 2.7:</p> <pre><code>Python 2.6.9 (default, Sep 15 2015, 14:14:54) [GCC 5.2.1 20150911] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; range(10.0) __main__:1: DeprecationWarning: integer argument expected, got float [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>See the <code>DeprecationWarning</code> - all this time your code has emitted warnings but you chose to ignore them. In Python 2.7:</p> <pre><code>Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; range(10.0) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: range() integer end argument expected, got float. </code></pre> <p>The solution is to wrap the <code>range()</code> into a new function:</p> <pre><code>def py26_range(*args): args = [int(i) if isinstance(i, float) else i for i in args] return range(*args) </code></pre> <p>This function coerces floats into ints retaining the Python 2.6 behaviour. You then need to replace all usages of <code>range</code> with <code>py26_range</code> in those parts of code where the argument might be a float.</p> <hr> <p>If you're desperate enough, you can install this version of <code>range</code> into <code>__builtin__</code>:</p> <pre><code>from functools import wraps import __builtin__ @wraps(range) def py26_range(*args): args = [int(i) if isinstance(i, float) else i for i in args] return range(*args) __builtin__.range = py26_range </code></pre> <p>Execute this before the other modules are <em>even imported</em> and it should work as before.</p>
2
2016-09-02T09:36:12Z
[ "python", "python-2.7", "python-2.6" ]
Return c++ object (not a pointer preferably) in cython
39,285,591
<p>I have two classes (let's assume the most simple ones, implementation is not important). My <code>defs.pxd</code> file (with cython defs) looks like this:</p> <pre><code>cdef extern from "A.hpp": cdef cppclass A: A() except + cdef extern from "B.hpp": cdef cppclass B: B() except + A func () </code></pre> <p>My <code>pyx</code> file (with python defs) looks like this:</p> <pre><code>from cython.operator cimport dereference as deref from libcpp.memory cimport shared_ptr cimport defs cdef class A: cdef shared_ptr[cquacker_defs.A] _this @staticmethod cdef inline A _from_this(shared_ptr[cquacker_defs.A] _this): cdef A result = A.__new__(A) result._this = _this return result def __init__(self): self._this.reset(new cquacker_defs.A()) cdef class B: cdef shared_ptr[cquacker_defs.B] _this @staticmethod cdef inline B _from_this(shared_ptr[cquacker_defs.B] _this): cdef B result = B.__new__(B) result._this = _this return result def __init__(self): self._this.reset(new cquacker_defs.B()) def func(self): return deref(self._this).func() </code></pre> <p>The thing is that I cannot return non-python object from Python. Actually, I don't want to change my c++ code to return pointer instead of new object (because there are many functions like that). Now it gives me the error:</p> <pre><code>Cannot convert 'B' to Python object </code></pre> <p>How can I return one python object holding internal c++ object from another one's method in python? If I can only do that after some c++ changes, I want the most elegant solution, if possible.</p>
0
2016-09-02T06:24:37Z
39,300,256
<p>Your issue is that your wrapper class requires a pointer (to a <code>new</code> allocated object) but your function returns an C++ object on the stack. To solve this you have to copy or move the object from the stack.</p> <p>First ensure that your C++ class <code>A</code> has a working copy or move constructor. A move constructor is better if you're c++ class contains large members. Wrap this is Cython like so:</p> <pre><code>cdef extern from "A.hpp": cdef cppclass A: A() except + A(const A&amp;) except + # or A(A&amp;&amp;) except + </code></pre> <p>(Don't tell Cython about both a copy constructor and a move constructor - it gets confused! C++ finds the right one when it's compiled anyway).</p> <p>Then, in <code>func</code> use your copy/move constructor with <code>new</code> to pass to your python wrapper:</p> <pre><code>def func(self): return A._from_this(new cquacker_defs.A(self._this.func())) </code></pre>
1
2016-09-02T20:28:15Z
[ "python", "c++", "cython" ]
What is the best way to use a two value pair as a key in python?
39,286,012
<p>I am basically attempting to use a matrix in pythons. I have heard about things like a list of lists, but I wasn't sure what the easiest way to manipulate these values would be. I would essentially want there to be a value stored at coordinates (x,y) on a grid, that could only be accessed by having both x and y. Something like:</p> <pre><code>x = 3 y = 4 Matrix[3][4] = value </code></pre>
1
2016-09-02T06:51:19Z
39,286,041
<p>You can store a tuple of (x, y) as a key in the dictionary:</p> <pre><code>matrix = {(1, 1): value1, (1, 2): value2, ...} </code></pre> <p>You can retrieve a value associated by a coordinate like follows:</p> <pre><code>value = matrix[(1, 2)] </code></pre>
4
2016-09-02T06:53:23Z
[ "python", "list", "matrix" ]
python - Pass by value or by reference
39,286,036
<p>I have an object with an attribute that is a list. For example:</p> <pre><code>obj.a = [3, 4, 5] </code></pre> <p>I would like to get the following behavior (but I can't manage to find a solution using magics/etc.) :</p> <pre><code>l = obj.a obj.a[0] = 2 print(l) --&gt; [3, 4, 5] print(obj.a) ---&gt; [2, 4, 5] </code></pre> <p>Of course I could simply use copy.deepcopy : </p> <pre><code>l = copy.deepcopy(obj.a) </code></pre> <p>but for several reasons I would like, somehow, to make this step automatic/hide it for my users. </p> <p>[EDIT] Using <strong>getattribute</strong> and returning a copy won't work of course:</p> <pre><code>import copy class Test: def __init__(self): self.a = [] def __getattribute__(self, attr): if attr == 'a': return copy.deepcopy(super(Test, self).__getattribute__(attr)) </code></pre> <p>Any help appreciated !</p> <p>Thnak you, Thomas </p>
1
2016-09-02T06:53:04Z
39,286,262
<p>It's not possible to make the assignment <code>l = obj.a</code> make a copy of <code>obj.a</code>. As deceze said in a comment, you could make <code>a</code> a property that returns a copy of the value every time you access it, but that would, well, make a copy every time you access it, not just when you assign it to <code>l</code>. That's going to be inefficient, and probably not the behavior you want anyway</p> <p>There's no way for <code>obj</code> or <code>obj.a</code> to tell the difference between something like this:</p> <pre><code>x = obj.a </code></pre> <p>and this:</p> <pre><code>obj.a[:2] </code></pre> <p>Whatever happens when you access <code>obj.a</code>, it's going to happen in both cases. You can't "look ahead" to see whether it's going to be assigned to a variable, just to copy it in that particular case.</p>
1
2016-09-02T07:06:22Z
[ "python", "reference" ]
python - Pass by value or by reference
39,286,036
<p>I have an object with an attribute that is a list. For example:</p> <pre><code>obj.a = [3, 4, 5] </code></pre> <p>I would like to get the following behavior (but I can't manage to find a solution using magics/etc.) :</p> <pre><code>l = obj.a obj.a[0] = 2 print(l) --&gt; [3, 4, 5] print(obj.a) ---&gt; [2, 4, 5] </code></pre> <p>Of course I could simply use copy.deepcopy : </p> <pre><code>l = copy.deepcopy(obj.a) </code></pre> <p>but for several reasons I would like, somehow, to make this step automatic/hide it for my users. </p> <p>[EDIT] Using <strong>getattribute</strong> and returning a copy won't work of course:</p> <pre><code>import copy class Test: def __init__(self): self.a = [] def __getattribute__(self, attr): if attr == 'a': return copy.deepcopy(super(Test, self).__getattribute__(attr)) </code></pre> <p>Any help appreciated !</p> <p>Thnak you, Thomas </p>
1
2016-09-02T06:53:04Z
39,286,305
<p>Simply use the following code...</p> <pre><code>l = list(obj.a) </code></pre> <p>this will allow you to copy a list to a new list</p>
0
2016-09-02T07:09:02Z
[ "python", "reference" ]
python - Pass by value or by reference
39,286,036
<p>I have an object with an attribute that is a list. For example:</p> <pre><code>obj.a = [3, 4, 5] </code></pre> <p>I would like to get the following behavior (but I can't manage to find a solution using magics/etc.) :</p> <pre><code>l = obj.a obj.a[0] = 2 print(l) --&gt; [3, 4, 5] print(obj.a) ---&gt; [2, 4, 5] </code></pre> <p>Of course I could simply use copy.deepcopy : </p> <pre><code>l = copy.deepcopy(obj.a) </code></pre> <p>but for several reasons I would like, somehow, to make this step automatic/hide it for my users. </p> <p>[EDIT] Using <strong>getattribute</strong> and returning a copy won't work of course:</p> <pre><code>import copy class Test: def __init__(self): self.a = [] def __getattribute__(self, attr): if attr == 'a': return copy.deepcopy(super(Test, self).__getattribute__(attr)) </code></pre> <p>Any help appreciated !</p> <p>Thnak you, Thomas </p>
1
2016-09-02T06:53:04Z
39,290,499
<p>This is not possible without actually cloning the list to another list, you have to use copy() or deepcopy() depending on your requirement. </p>
0
2016-09-02T10:45:21Z
[ "python", "reference" ]
How to check if 2-D array is in another 2-D array
39,286,058
<p>consider the two dataframes <code>df1</code> and <code>df2</code></p> <pre><code>df1 = pd.DataFrame(np.zeros((6, 6)), list('abcdef'), list('abcdef'), dtype=int) df1.iloc[2:4, 2:4] = np.array([[1, 2], [3, 4]]) df1 </code></pre> <p><a href="http://i.stack.imgur.com/UEWbP.png" rel="nofollow"><img src="http://i.stack.imgur.com/UEWbP.png" alt="enter image description here"></a></p> <pre><code>df2 = pd.DataFrame(np.array([[1, 2], [3, 4]]), list('CD'), list('CD'), dtype=int) df2 </code></pre> <p><a href="http://i.stack.imgur.com/dUPSc.png" rel="nofollow"><img src="http://i.stack.imgur.com/dUPSc.png" alt="enter image description here"></a></p> <p>It's clear that <code>df2</code> is in <code>df1</code>. How do I test for this in general?</p>
2
2016-09-02T06:54:20Z
39,286,107
<p>Assuming the dataframes contain <code>0's</code> and <code>1s</code> only, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html" rel="nofollow"><code>2D convolution</code></a> and look if any element in the convoluted output is equal to the number of elements in <code>df2</code> -</p> <pre><code>from scipy.signal import convolve2d out = (convolve2d(df1,df2)==df2.size).any() </code></pre> <hr> <p>For a generic case, let me use <a href="http://scikit-image.org/docs/dev/api/skimage.html" rel="nofollow"><code>skimage</code> module</a> and <a href="http://stackoverflow.com/a/32531759/3293881"><code>this smart solution</code></a> -</p> <pre><code>from skimage.util import view_as_windows as viewW out = ((viewW(df1.values, df2.shape) == df2.values).all(axis=(2,3))).any() </code></pre> <p>This is basically a template-matching problem and it has been discussed and we have gotten really efficient solutions under this post : <a href="http://stackoverflow.com/questions/32531377/how-can-i-check-if-one-two-dimensional-numpy-array-contains-a-specific-pattern-o"><code>How can I check if one two-dimensional NumPy array contains a specific pattern of values inside it?</code></a>. That post also gives us the indices of all places in <code>df1</code> where <code>df2</code> could be located.</p>
3
2016-09-02T06:56:42Z
[ "python", "pandas", "numpy", "scipy" ]
How to check if 2-D array is in another 2-D array
39,286,058
<p>consider the two dataframes <code>df1</code> and <code>df2</code></p> <pre><code>df1 = pd.DataFrame(np.zeros((6, 6)), list('abcdef'), list('abcdef'), dtype=int) df1.iloc[2:4, 2:4] = np.array([[1, 2], [3, 4]]) df1 </code></pre> <p><a href="http://i.stack.imgur.com/UEWbP.png" rel="nofollow"><img src="http://i.stack.imgur.com/UEWbP.png" alt="enter image description here"></a></p> <pre><code>df2 = pd.DataFrame(np.array([[1, 2], [3, 4]]), list('CD'), list('CD'), dtype=int) df2 </code></pre> <p><a href="http://i.stack.imgur.com/dUPSc.png" rel="nofollow"><img src="http://i.stack.imgur.com/dUPSc.png" alt="enter image description here"></a></p> <p>It's clear that <code>df2</code> is in <code>df1</code>. How do I test for this in general?</p>
2
2016-09-02T06:54:20Z
39,289,049
<h3>Brute force</h3> <pre><code>def isin2d(small_df, large_df): di, dj = small_df.shape mi, mj = large_df.shape for i in range(mi - di + 1): for j in range(mj - dj + 1): if (small_df.values == large_df.values[i:i + di, j:j + dj]).all(): return True return False isin2d(df2, df1) True </code></pre>
1
2016-09-02T09:31:26Z
[ "python", "pandas", "numpy", "scipy" ]
python class behaves like dictionary-or-list-data-like
39,286,116
<p>In python3 console, input those:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version_info sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0) &gt;&gt;&gt; type(sys.version_info) # this is class type &lt;class 'sys.version_info'&gt; &gt;&gt;&gt; sys.version_info[0:2] # ?? But it acts like a list-data-like (3, 4) </code></pre> <p>My questions are:</p> <ol> <li>How can a class act like dictionary-or-list-data-like? </li> <li>May give an example to construct a class like this? </li> <li>Is there some documentation about this?</li> </ol>
0
2016-09-02T06:57:19Z
39,286,168
<p>It's quite easy ... All you need to do is define a <code>__getitem__</code> method that handles slicing or integer/string lookup. You can do pretty much whatever you want...</p> <pre><code>class Foo(object): def __init__(self, bar, baz): self.bar = bar self.baz = baz def __getitem__(self, ix): return (self.bar, self.baz).__getitem__(ix) </code></pre> <p>Here's a cheat sheet of what will be passed to <code>__getitem__</code> as <code>ix</code> in the following situations:</p> <pre><code>f[1] # f.__getitem__(1) f[1:] # f.__getitem__(slice(1, None, None)) f[1:, 2] # f.__getitem__( (slice(1, None, None), 2) ) f[1, 2] # f.__getitem__( (1, 2) ) f[(1, 2)] # f.__getitem__( (1, 2) ) </code></pre> <p>The trick (which can be slightly non-trivial) is simply writing <code>__getitem__</code> so that it looks at the type of the object that was passed and then does the right thing. For my answer, I cheated by creating a <code>tuple</code> in my <code>__getitem__</code> and then I called <code>__getitem__</code> on the tuple (since it already does the right thing in all of the cases that I wanted to support)</p> <p>Here's some example usage:</p> <pre><code>&gt;&gt;&gt; f = Foo(1, 2) &gt;&gt;&gt; f[1] 2 &gt;&gt;&gt; f[0] 1 &gt;&gt;&gt; f[:] (1, 2) </code></pre> <p>note that you don't <em>typically</em> need to even do this yourself. You can create a <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="nofollow">named tuple</a> to do the job for you:</p> <pre><code>from collections import namedtuple Foo = namedtuple('Foo', 'bar, baz') </code></pre> <p>And usage is pretty much the same:</p> <pre><code>&gt;&gt;&gt; f = Foo(1, 2) &gt;&gt;&gt; f[1] 2 &gt;&gt;&gt; f[0] 1 &gt;&gt;&gt; f[:] (1, 2) </code></pre> <p>The main difference here is that our namedtuple is immutable. Once created, we can't change it's members.</p>
2
2016-09-02T07:00:06Z
[ "python", "list", "class", "dictionary" ]
python class behaves like dictionary-or-list-data-like
39,286,116
<p>In python3 console, input those:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version_info sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0) &gt;&gt;&gt; type(sys.version_info) # this is class type &lt;class 'sys.version_info'&gt; &gt;&gt;&gt; sys.version_info[0:2] # ?? But it acts like a list-data-like (3, 4) </code></pre> <p>My questions are:</p> <ol> <li>How can a class act like dictionary-or-list-data-like? </li> <li>May give an example to construct a class like this? </li> <li>Is there some documentation about this?</li> </ol>
0
2016-09-02T06:57:19Z
39,286,207
<p>Python contains several methods for <a href="https://docs.python.org/3/reference/datamodel.html#emulating-container-types" rel="nofollow">emulating container types</a> such as dictionaries and lists. </p> <p>In particular, consider the following class:</p> <pre><code> class MyDict(object): def __getitem__(self, key): # Called for getting obj[key] def __setitem__(self, key, value): # Called for setting obj[key] = value </code></pre> <p>If you write</p> <pre><code>obj = MyDict() </code></pre> <p>Then</p> <pre><code>obj[3] </code></pre> <p>will call the first method, and</p> <pre><code>obj[3] = 'foo' </code></pre> <p>will call the second method.</p> <p>If you further want to support </p> <pre><code>len(obj) </code></pre> <p>then you just need to add the method</p> <pre><code>def __len__(self): # Return here the logical length </code></pre> <hr> <p>Here is an example of a (very inefficient) dictionary implemented by a list</p> <pre><code>class MyDict(object): def __init__(self, seq=None): self._vals = list(seq) if seq is not None else [] def __getitem__(self, key): return [v[1] for v in self._vals if v[0] == key][0] def __setitem__(self, key, val): self._vals = [v for v in self._vals if v[0] != key] self._vals.append((key, val)) def __len__(self): return len(self._vals) </code></pre> <p>You can use it pretty much like a regular <code>dict</code>:</p> <pre><code>obj = MyDict() obj[2] = 'b' &gt;&gt;&gt; obj[2] 'b' </code></pre>
2
2016-09-02T07:02:49Z
[ "python", "list", "class", "dictionary" ]
python class behaves like dictionary-or-list-data-like
39,286,116
<p>In python3 console, input those:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version_info sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0) &gt;&gt;&gt; type(sys.version_info) # this is class type &lt;class 'sys.version_info'&gt; &gt;&gt;&gt; sys.version_info[0:2] # ?? But it acts like a list-data-like (3, 4) </code></pre> <p>My questions are:</p> <ol> <li>How can a class act like dictionary-or-list-data-like? </li> <li>May give an example to construct a class like this? </li> <li>Is there some documentation about this?</li> </ol>
0
2016-09-02T06:57:19Z
39,287,007
<p>i think in python like ECMAScript (aka javascript) class is a dictionary or <strong>associative array</strong>(<a href="https://en.wikipedia.org/wiki/Associative_array" rel="nofollow">associative array</a>). since you can add a property or method to your class at runtime.(<a href="http://slides.com/alirezaafzalaghaei/introduction-to-javascript#/7/3" rel="nofollow">see</a>)</p> <pre><code>class A(object): def __init__(self): self.x = 0 a = A() a.y=5 print a.y # 5 </code></pre> <p>if you want write a class like that you can use <code>__getitem__</code> and <code>__setitem__</code> methods:</p> <pre><code>class A(object): class B(object): def __init__(self, x, y): self.vals = (x, y) def __getitem__(self, key): return self.vals[key] def __setitem__(self, key, val): self.vals[key] = val def __len__(self): return len(self.__vals) def __init__(self, x, y): self.b = self.B(x,y) a = A('foo','baz') print type(a.b) # __main__.b __main__ because we run script straightly print a.b[:] # ('foo', 'baz') </code></pre>
0
2016-09-02T07:46:11Z
[ "python", "list", "class", "dictionary" ]
python class behaves like dictionary-or-list-data-like
39,286,116
<p>In python3 console, input those:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version_info sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0) &gt;&gt;&gt; type(sys.version_info) # this is class type &lt;class 'sys.version_info'&gt; &gt;&gt;&gt; sys.version_info[0:2] # ?? But it acts like a list-data-like (3, 4) </code></pre> <p>My questions are:</p> <ol> <li>How can a class act like dictionary-or-list-data-like? </li> <li>May give an example to construct a class like this? </li> <li>Is there some documentation about this?</li> </ol>
0
2016-09-02T06:57:19Z
39,290,115
<p>You can achieve the same behaviour by overriding <strong>getitem</strong>() and <strong>setitem</strong>() in your class.</p> <pre><code> class Example: def __getitem__(self, index): return index ** 2 &gt;&gt;&gt; X = Example() &gt;&gt;&gt; X[2] &gt;&gt;&gt; 4 </code></pre> <p>You can override <strong>setitem</strong>() too in your class for achieving the setter kind of thing. </p>
0
2016-09-02T10:24:09Z
[ "python", "list", "class", "dictionary" ]
Pass custom value to the logger instead of to every message
39,286,145
<p>I want to log the user session. Currently the code is as follows (setting formatter and handlers is omitted):</p> <pre><code>logger = logging.getLogger("component") logger.info("message", extra={"session": 123}) logger.debug("debug", extra={"session": 123}) </code></pre> <p>If there are several messages to be logged, it's annoying to send this extra information each time. What would be the best/cleanest/most pythonic way to achieve something like that:</p> <pre><code>logger = logging.getLogger("component") # for example: logger.addExtra({"session": 123}) logger.info("message") # extra would be added automatically logger.debug("debug") # extra would be added automatically </code></pre> <p>I could think of extending the logger and overriding logging methods.</p>
0
2016-09-02T06:58:56Z
39,286,315
<p>In Java we have Mapped Diagnostic Context (<code>MDC</code>) in <code>Log4j</code> framework.</p> <p>Basically it is a map. You can put values there which can be used in logger output pattern.</p> <p>Please take a look at: <a href="https://gist.github.com/mdaniel/8347533" rel="nofollow">https://gist.github.com/mdaniel/8347533</a></p> <p>I don't know is it working, but maybe <code>MDC</code> will be a key for Your further research.</p>
-1
2016-09-02T07:09:34Z
[ "python", "python-3.x", "logging" ]
Pass custom value to the logger instead of to every message
39,286,145
<p>I want to log the user session. Currently the code is as follows (setting formatter and handlers is omitted):</p> <pre><code>logger = logging.getLogger("component") logger.info("message", extra={"session": 123}) logger.debug("debug", extra={"session": 123}) </code></pre> <p>If there are several messages to be logged, it's annoying to send this extra information each time. What would be the best/cleanest/most pythonic way to achieve something like that:</p> <pre><code>logger = logging.getLogger("component") # for example: logger.addExtra({"session": 123}) logger.info("message") # extra would be added automatically logger.debug("debug") # extra would be added automatically </code></pre> <p>I could think of extending the logger and overriding logging methods.</p>
0
2016-09-02T06:58:56Z
39,286,357
<p>Use function factories for instance like that</p> <pre><code>def get_logger_with_context(name, context=None): extra = context or {} logger = logging.getLogger(name) def log(level, message, **kwargs): getattr(logger, level)(message, extra=context) return log </code></pre>
1
2016-09-02T07:11:42Z
[ "python", "python-3.x", "logging" ]
Pass custom value to the logger instead of to every message
39,286,145
<p>I want to log the user session. Currently the code is as follows (setting formatter and handlers is omitted):</p> <pre><code>logger = logging.getLogger("component") logger.info("message", extra={"session": 123}) logger.debug("debug", extra={"session": 123}) </code></pre> <p>If there are several messages to be logged, it's annoying to send this extra information each time. What would be the best/cleanest/most pythonic way to achieve something like that:</p> <pre><code>logger = logging.getLogger("component") # for example: logger.addExtra({"session": 123}) logger.info("message") # extra would be added automatically logger.debug("debug") # extra would be added automatically </code></pre> <p>I could think of extending the logger and overriding logging methods.</p>
0
2016-09-02T06:58:56Z
39,286,514
<p>Such <a href="https://docs.python.org/2/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output" rel="nofollow">custom logging</a> is feasible in python logging class, using logging.loggerAdapters which modify the logging behaviour.</p> <blockquote> <p>An easy way in which you can pass contextual information to be output along with logging event information is to use the LoggerAdapter class. This class is designed to look like a Logger, so that you can call debug(), info(), warning(), error(), exception(), critical() and log(). These methods have the same signatures as their counterparts in Logger, so you can use the two types of instances interchangeably.</p> </blockquote>
1
2016-09-02T07:20:31Z
[ "python", "python-3.x", "logging" ]
Pass custom value to the logger instead of to every message
39,286,145
<p>I want to log the user session. Currently the code is as follows (setting formatter and handlers is omitted):</p> <pre><code>logger = logging.getLogger("component") logger.info("message", extra={"session": 123}) logger.debug("debug", extra={"session": 123}) </code></pre> <p>If there are several messages to be logged, it's annoying to send this extra information each time. What would be the best/cleanest/most pythonic way to achieve something like that:</p> <pre><code>logger = logging.getLogger("component") # for example: logger.addExtra({"session": 123}) logger.info("message") # extra would be added automatically logger.debug("debug") # extra would be added automatically </code></pre> <p>I could think of extending the logger and overriding logging methods.</p>
0
2016-09-02T06:58:56Z
39,286,671
<p>Create a <code>LoggerAdapter</code> as @DhruvPathak specified. According to <a href="https://docs.python.org/3/library/logging.html#logging.LoggerAdapter" rel="nofollow"><code>LoggerAdapter</code>s signature</a>:</p> <pre><code>class logging.LoggerAdapter(logger, extra) </code></pre> <p>you do that by providing your logger instance and the <code>extra</code> args during initialization:</p> <pre><code>logger = logging.LoggerAdapter(logger, extra) </code></pre>
1
2016-09-02T07:28:27Z
[ "python", "python-3.x", "logging" ]
Excel or Access change some rows to columns
39,286,158
<p>I have some long data I need to convert into a wide fixed width text format. </p> <p>I have a large spreadsheet of rows that are duplicated for each person where the only difference, where the person is the same, are two columns. </p> <p>I want to remove the duplicates and instead of having multiple rows where the only difference are the columns 'type' and 'process'. They are all in the same row and repeated 30 times each, some columns would be blank if there are not 30 rows for that person. I've attached a picture if my explanation makes no sense: <a href="http://i.stack.imgur.com/wg7gr.png" rel="nofollow"><img src="http://i.stack.imgur.com/wg7gr.png" alt="enter image description here"></a></p> <p>I'm not sure if this can be done in VBA, or python or other language would be better</p>
1
2016-09-02T06:59:33Z
39,286,838
<p>You can do that using a pivot table:</p> <ul> <li>put name then DOB as row labels</li> <li>put type then process as column labels</li> <li>put count of process in values</li> <li>right-click your pivot table, select expand/collapse and expand by process</li> <li>go to design, report layout, and select tabular layout</li> <li>right click on totals rows and columns that you do not want and hide them</li> </ul> <p>Here's how it looks for me, for a smaller table:</p> <p><a href="http://i.stack.imgur.com/F3uc5.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/F3uc5.jpg" alt="enter image description here"></a></p>
2
2016-09-02T07:37:39Z
[ "python", "excel" ]
handing qwidget.winid to DLL in Python
39,286,164
<p>I have a dll, which use OpenGl to draw on window. Dll get window by HWMD.</p> <p>DLL:</p> <pre><code>extern "C" __declspec(dllexport) int Init(HWND hWnd); extern "C" __declspec(dllexport) void Resize(HWND hWnd, int w, int h); extern "C" __declspec(dllexport) void Paint(HWND hWnd); </code></pre> <p>The c++ qt application is work properly.</p> <pre><code>#include "windows.h" #include &lt;QApplication&gt; #include &lt;QWidget&gt; #include &lt;QGLWidget&gt; #include &lt;QMessageBox&gt; #include &lt;QSplitter&gt; #include &lt;QLibrary&gt; typedef void (*InitPrototype)(HWND); typedef void (*PaintPrototype)(HWND); typedef void (*ResizePrototype)(HWND, int, int); InitPrototype c_Init; PaintPrototype c_Paint; ResizePrototype c_Resize; bool load_opengl_library(){ QLibrary lib("engine3d"); lib.load(); c_Init = (InitPrototype)lib.resolve("Init"); c_Paint = (PaintPrototype)lib.resolve("Paint"); c_Resize = (ResizePrototype)lib.resolve("Resize"); return true; } class MyGlWidget: public QGLWidget { public: MyGlWidget(QWidget *parent = 0): QGLWidget(parent){} void showEvent(QShowEvent* event){ c_Init((HWND)(this-&gt;winId())); } void paintEvent(QPaintEvent* event){ c_Paint((HWND)this-&gt;winId()); } void resizeEvent(QResizeEvent* event){ c_Resize((HWND)this-&gt;winId(), this-&gt;width(), this-&gt;height()); } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); load_opengl_library(); MyGlWidget w; w.show(); return a.exec(); } </code></pre> <p>But how do the same in python? My program crushes on sending widget.winId().</p> <pre><code># coding=utf-8 import ctypes from PyQt5 import QtWidgets, QtOpenGL app = QtWidgets.QApplication([]) e3d = ctypes.CDLL(r"engine3d.dll") init = lambda hwnd: e3d.Init(hwnd) paint = lambda hwnd: e3d.Paint(hwnd) resize = lambda hwnd, w, h: e3d.Paint(hwnd, w, h) class MyGLWidget(QtOpenGL.QGLWidget): def __init__(self): super().__init__() def showEvent(self, ev): init(self.winId()) def paintEvent(self, ev): paint(self.winId()) def resizeEvent(self, ev): resize(self.winId(), self.width(), self.height()) w = MyGLWidget() w.show() app.exec_() </code></pre> <p>print(self.winId()) is </p>
2
2016-09-02T06:59:48Z
39,288,498
<p>It'd be easier to check having the dll, so I'll speak out the blue. In your c++ code you got this initialization code:</p> <pre><code>bool load_opengl_library(){ QLibrary lib("engine3d"); lib.load(); c_Init = (InitPrototype)lib.resolve("Init"); c_Paint = (PaintPrototype)lib.resolve("Paint"); c_Resize = (ResizePrototype)lib.resolve("Resize"); return true; } ... int main(int argc, char *argv[]) { QApplication a(argc, argv); load_opengl_library(); MyGlWidget w; w.show(); return a.exec(); } </code></pre> <p>Where you create your engine instance <code>lib</code>and using <code>load</code>method but in python you're not doing anything of that:</p> <pre><code>w = MyGLWidget() w.show() app.exec_() </code></pre> <p>But before creating the <code>MyGLWidget</code> you're not initializing your engine as its c++ counterpart, question is, why not?</p>
0
2016-09-02T09:06:40Z
[ "python", "dll", "ctypes", "hwnd" ]
Running a python script from shell
39,286,331
<p>I want to run a python script from a shell script. I have been able to run it from the "command window" (Cygwin), but now I want to be able to call it from a shell script. It does not work the way I thought it would and the Internet has not really helped me with it.</p> <p>My code so far:</p> <pre><code>#!/bin/bash python Calibrate.py </code></pre> <p>I hope someone could help me further. <em>Calibrate</em> just contains a few basic command lines to transform some data that has been read in with an excelreader in the script itself.</p>
0
2016-09-02T07:10:31Z
39,286,535
<p>Just make sure the python executable is in your PATH environment variable, then add in your script</p> <p>In the file job.sh,</p> <p><code>#!/bin/sh python &lt;path/to/python/script&gt;/python_script.py</code></p> <p>Execute this command to make the script runnable for you : <code>chmod u+x job.sh</code> Run it : <code>./job.sh</code></p>
1
2016-09-02T07:21:58Z
[ "python", "shell" ]
Running a python script from shell
39,286,331
<p>I want to run a python script from a shell script. I have been able to run it from the "command window" (Cygwin), but now I want to be able to call it from a shell script. It does not work the way I thought it would and the Internet has not really helped me with it.</p> <p>My code so far:</p> <pre><code>#!/bin/bash python Calibrate.py </code></pre> <p>I hope someone could help me further. <em>Calibrate</em> just contains a few basic command lines to transform some data that has been read in with an excelreader in the script itself.</p>
0
2016-09-02T07:10:31Z
39,287,160
<p>A Bash script needs to use the Unix EOL (End Of Line) convention, which terminates each line with <code>\n</code>. But it looks like your test.sh shell script file uses the Windows / DOS EOL convention, which terminates each line with <code>\r\n</code>. </p> <p>You need to get rid of those <code>\r</code> characters in test.sh, and you need to set your editor to use Unix line endings.</p> <p>A simple way to strip <code>\r</code> out of a file is to use the Unix <code>sed</code> command; I assume it's available in Cygwin: </p> <pre><code>sed -i 's/\r//g' test.sh </code></pre> <p>This removes all <code>\r</code> characters in test.sh, writing the result back to test.sh</p>
1
2016-09-02T07:55:18Z
[ "python", "shell" ]