title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to save a configuration file / python file IO | 1,423,214 | <p>I have this python code for opening a .cfg file, writing to it and saving it:</p>
<pre><code>import ConfigParser
def get_lock_file():
cf = ConfigParser.ConfigParser()
cf.read("svn.lock")
return cf
def save_lock_file(configurationParser):
cf = configurationParser
config_file = open('svn.lock', 'w')
cf.write(config_file)
config_file.close()
</code></pre>
<p>Does this seem normal or am I missing something about how to open-write-save files? Is there a more standard way to read and write config files? </p>
<p>I ask because I have two methods that seem to do the same thing, they get the config file handle ('cf') call cf.set('blah', 'foo' bar) then use the save_lock_file(cf) call above. For one method it works and for the other method the write never takes place, unsure why at this point.</p>
<pre><code>def used_like_this():
cf = get_lock_file()
cf.set('some_prop_section', 'some_prop', 'some_value')
save_lock_file(cf)
</code></pre>
| 0 | 2009-09-14T18:35:35Z | 1,423,287 | <p>Looks good to me.</p>
<p>If both places call <code>get_lock_file</code>, then <code>cf.set(...)</code>, and then <code>save_lock_file</code>, and no exceptions are raised, this should work.</p>
<p>If you have different threads or processes accessing the same file you could have a race condition:</p>
<ol>
<li>thread/process A reads the file</li>
<li>thread/process B reads the file</li>
<li>thread/process A updates the file</li>
<li>thread/process B updates the file</li>
</ol>
<p>Now the file only contains B's updates, not A's.</p>
<p>Also, for safe file writing, don't forget the <code>with</code> statement (Python 2.5 and up), it'll save you a try/finally (which you should be using if you're not using <code>with</code>). From <code>ConfigParser</code>'s docs:</p>
<pre><code>with open('example.cfg', 'wb') as configfile:
config.write(configfile)
</code></pre>
| 1 | 2009-09-14T18:55:01Z | [
"python",
"file",
"file-io",
"configuration-files"
] |
How to save a configuration file / python file IO | 1,423,214 | <p>I have this python code for opening a .cfg file, writing to it and saving it:</p>
<pre><code>import ConfigParser
def get_lock_file():
cf = ConfigParser.ConfigParser()
cf.read("svn.lock")
return cf
def save_lock_file(configurationParser):
cf = configurationParser
config_file = open('svn.lock', 'w')
cf.write(config_file)
config_file.close()
</code></pre>
<p>Does this seem normal or am I missing something about how to open-write-save files? Is there a more standard way to read and write config files? </p>
<p>I ask because I have two methods that seem to do the same thing, they get the config file handle ('cf') call cf.set('blah', 'foo' bar) then use the save_lock_file(cf) call above. For one method it works and for the other method the write never takes place, unsure why at this point.</p>
<pre><code>def used_like_this():
cf = get_lock_file()
cf.set('some_prop_section', 'some_prop', 'some_value')
save_lock_file(cf)
</code></pre>
| 0 | 2009-09-14T18:35:35Z | 1,423,303 | <p>Works for me.</p>
<pre>
C:\temp>type svn.lock
[some_prop_section]
Hello=World
C:\temp>python
ActivePython 2.6.2.2 (ActiveState Software Inc.) based on
Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigParser
>>> def get_lock_file():
... cf = ConfigParser.ConfigParser()
... cf.read("svn.lock")
... return cf
...
>>> def save_lock_file(configurationParser):
... cf = configurationParser
... config_file = open('svn.lock', 'w')
... cf.write(config_file)
... config_file.close()
...
>>> def used_like_this():
... cf = get_lock_file()
... cf.set('some_prop_section', 'some_prop', 'some_value')
... save_lock_file(cf)
...
>>> used_like_this()
>>> ^Z
C:\temp>type svn.lock
[some_prop_section]
hello = World
some_prop = some_value
C:\temp>
</pre>
| 1 | 2009-09-14T18:58:24Z | [
"python",
"file",
"file-io",
"configuration-files"
] |
How to save a configuration file / python file IO | 1,423,214 | <p>I have this python code for opening a .cfg file, writing to it and saving it:</p>
<pre><code>import ConfigParser
def get_lock_file():
cf = ConfigParser.ConfigParser()
cf.read("svn.lock")
return cf
def save_lock_file(configurationParser):
cf = configurationParser
config_file = open('svn.lock', 'w')
cf.write(config_file)
config_file.close()
</code></pre>
<p>Does this seem normal or am I missing something about how to open-write-save files? Is there a more standard way to read and write config files? </p>
<p>I ask because I have two methods that seem to do the same thing, they get the config file handle ('cf') call cf.set('blah', 'foo' bar) then use the save_lock_file(cf) call above. For one method it works and for the other method the write never takes place, unsure why at this point.</p>
<pre><code>def used_like_this():
cf = get_lock_file()
cf.set('some_prop_section', 'some_prop', 'some_value')
save_lock_file(cf)
</code></pre>
| 0 | 2009-09-14T18:35:35Z | 1,426,555 | <p>Just to note that configuration file handling is simpler with ConfigObj.</p>
<p>To read and then write a config file:</p>
<pre><code>from configobj import ConfigObj
config = ConfigObj(filename)
value = config['entry']
config['entry'] = newvalue
config.write()
</code></pre>
| 12 | 2009-09-15T11:15:19Z | [
"python",
"file",
"file-io",
"configuration-files"
] |
talking between python tcp server and a c++ client | 1,423,251 | <p>I am having an issue trying to communicate between a python TCP server and a c++ TCP client.
After the first call, which works fine, the subsequent calls cause issues. </p>
<p>As far as WinSock is concerned, the send() function worked properly, it returns the proper length and WSAGetLastError() does not return anything of significance.</p>
<p>However, when watching the packets using wireshark, i notice that the first call sends two packets, a PSH,ACK with all of the data in it, and an ACK right after, but the subsequent calls, which don't work, only send the PSH,ACK packet, and not a subsequent ACK packet</p>
<p>the receiving computers wireshark corroborates this, and the python server does nothing, it doesnt have any data coming out of the socket, and i cannot debug deeper, since socket is a native class</p>
<p>when i run a c++ client and a c++ server (a hacked replica of what the python one would do), the client faithfully sends both the PSH,ACk and ACK packets the whole time, even after the first call.</p>
<p>Is the winsock send function supposed to always send a PSH,ACK and an ACK?
If so, why would it do so when connected to my C++ server and not the python server?
Has anyone had any issues similar to this?</p>
| 2 | 2009-09-14T18:44:53Z | 1,423,334 | <p>What size of packets do you send? </p>
<p>If they are small - may be <a href="http://www.stuartcheshire.org/papers/NagleDelayedAck/" rel="nofollow">Nagle's Algorith & Delayed ACK Algorithm</a> is your headache? From what you described think Delayed ACK is involved...</p>
| 0 | 2009-09-14T19:05:44Z | [
"c++",
"python",
"networking",
"sockets",
"winsock"
] |
talking between python tcp server and a c++ client | 1,423,251 | <p>I am having an issue trying to communicate between a python TCP server and a c++ TCP client.
After the first call, which works fine, the subsequent calls cause issues. </p>
<p>As far as WinSock is concerned, the send() function worked properly, it returns the proper length and WSAGetLastError() does not return anything of significance.</p>
<p>However, when watching the packets using wireshark, i notice that the first call sends two packets, a PSH,ACK with all of the data in it, and an ACK right after, but the subsequent calls, which don't work, only send the PSH,ACK packet, and not a subsequent ACK packet</p>
<p>the receiving computers wireshark corroborates this, and the python server does nothing, it doesnt have any data coming out of the socket, and i cannot debug deeper, since socket is a native class</p>
<p>when i run a c++ client and a c++ server (a hacked replica of what the python one would do), the client faithfully sends both the PSH,ACk and ACK packets the whole time, even after the first call.</p>
<p>Is the winsock send function supposed to always send a PSH,ACK and an ACK?
If so, why would it do so when connected to my C++ server and not the python server?
Has anyone had any issues similar to this?</p>
| 2 | 2009-09-14T18:44:53Z | 1,424,893 | <blockquote>
<p>client sends a PSH,ACK and then the
server sends a PSH,ACK and a
FIN,PSH,ACK</p>
</blockquote>
<p>There is a FIN, so could it be that the Python version of your server is closing the connection immediately after the initial read?</p>
<p>If you are not explicitly closing the server's socket, it's probable that the server's remote socket variable is going out of scope, thus closing it (and that this bug is not present in your C++ version)?</p>
<p>Assuming that this is the case, I can cause a very similar TCP sequence with this code for the server:</p>
<pre><code># server.py
import socket
from time import sleep
def f(s):
r,a = s.accept()
print r.recv(100)
s = socket.socket()
s.bind(('localhost',1234))
s.listen(1)
f(s)
# wait around a bit for the client to send it's second packet
sleep(10)
</code></pre>
<p>and this for the client:</p>
<pre><code># client.py
import socket
from time import sleep
s = socket.socket()
s.connect(('localhost',1234))
s.send('hello 1')
# wait around for a while so that the socket in server.py goes out of scope
sleep(5)
s.send('hello 2')
</code></pre>
<p>Start your packet sniffer, then run server.py and then, client.py. Here is the outout of <code>tcpdump -A -i lo</code>, which matches your observations:</p>
<pre><code>tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo, link-type EN10MB (Ethernet), capture size 96 bytes
12:42:37.683710 IP localhost:33491 > localhost.1234: S 1129726741:1129726741(0) win 32792 <mss 16396,sackOK,timestamp 640881101 0,nop,wscale 7>
E..<R.@.@...............CVC.........I|....@....
&3..........
12:42:37.684049 IP localhost.1234 > localhost:33491: S 1128039653:1128039653(0) ack 1129726742 win 32768 <mss 16396,sackOK,timestamp 640881101 640881101,nop,wscale 7>
E..<..@.@.<.............C<..CVC.....Ia....@....
&3..&3......
12:42:37.684087 IP localhost:33491 > localhost.1234: . ack 1 win 257 <nop,nop,timestamp 640881102 640881101>
E..4R.@.@...............CVC.C<......1......
&3..&3..
12:42:37.684220 IP localhost:33491 > localhost.1234: P 1:8(7) ack 1 win 257 <nop,nop,timestamp 640881102 640881101>
E..;R.@.@...............CVC.C<......./.....
&3..&3..hello 1
12:42:37.684271 IP localhost.1234 > localhost:33491: . ack 8 win 256 <nop,nop,timestamp 640881102 640881102>
E..4.(@.@...............C<..CVC.....1}.....
&3..&3..
12:42:37.684755 IP localhost.1234 > localhost:33491: F 1:1(0) ack 8 win 256 <nop,nop,timestamp 640881103 640881102>
E..4.)@.@...............C<..CVC.....1{.....
&3..&3..
12:42:37.685639 IP localhost:33491 > localhost.1234: . ack 2 win 257 <nop,nop,timestamp 640881104 640881103>
E..4R.@.@...............CVC.C<......1x.....
&3..&3..
12:42:42.683367 IP localhost:33491 > localhost.1234: P 8:15(7) ack 2 win 257 <nop,nop,timestamp 640886103 640881103>
E..;R.@.@...............CVC.C<......./.....
&3%W&3..hello 2
12:42:42.683401 IP localhost.1234 > localhost:33491: R 1128039655:1128039655(0) win 0
E..(..@.@.<.............C<......P...b...
9 packets captured
27 packets received by filter
0 packets dropped by kernel
</code></pre>
| 2 | 2009-09-15T02:52:48Z | [
"c++",
"python",
"networking",
"sockets",
"winsock"
] |
Negative lookahead after newline? | 1,423,260 | <p>I have a CSV-like text file that has about 1000 lines. Between each record in the file is a long series of dashes. The records generally end with a \n, but sometimes there is an extra \n before the end of the record. Simplified example:</p>
<pre><code>"1x", "1y", "Hi there"
-------------------------------
"2x", "2y", "Hello - I'm lost"
-------------------------------
"3x", "3y", "How ya
doing?"
-------------------------------
</code></pre>
<p>I want to replace the extra \n's with spaces, i.e. concatenate the lines between the dashes. I thought I would be able to do this (Python 2.5):</p>
<pre><code>text = open("thefile.txt", "r").read()
better_text = re.sub(r'\n(?!\-)', ' ', text)
</code></pre>
<p>but that seems to replace every \n, not just the ones that are not followed by a dash. What am I doing wrong?</p>
<p>I am asking this question in an attempt to improve my own regex skills and understand the mistakes that I made. The end goal is to generate a text file in a format that is usable by a specific VBA for Word macro that generates a styled Word document which will then be digested by a Word-friendly CMS.</p>
| 2 | 2009-09-14T18:48:01Z | 1,423,288 | <p>You need to exclude the line breaks at the end of the separating lines. Try this:</p>
<pre><code>\n(?<!-\n)(?!-)
</code></pre>
<p>This regular expression uses a negative <a href="http://www.regular-expressions.info/lookaround.html#lookbehind" rel="nofollow">look-behind assertion</a> to exclude <code>\n</code> thatâs preceeded by an <code>-</code>.</p>
| 5 | 2009-09-14T18:55:20Z | [
"python",
"regex"
] |
Negative lookahead after newline? | 1,423,260 | <p>I have a CSV-like text file that has about 1000 lines. Between each record in the file is a long series of dashes. The records generally end with a \n, but sometimes there is an extra \n before the end of the record. Simplified example:</p>
<pre><code>"1x", "1y", "Hi there"
-------------------------------
"2x", "2y", "Hello - I'm lost"
-------------------------------
"3x", "3y", "How ya
doing?"
-------------------------------
</code></pre>
<p>I want to replace the extra \n's with spaces, i.e. concatenate the lines between the dashes. I thought I would be able to do this (Python 2.5):</p>
<pre><code>text = open("thefile.txt", "r").read()
better_text = re.sub(r'\n(?!\-)', ' ', text)
</code></pre>
<p>but that seems to replace every \n, not just the ones that are not followed by a dash. What am I doing wrong?</p>
<p>I am asking this question in an attempt to improve my own regex skills and understand the mistakes that I made. The end goal is to generate a text file in a format that is usable by a specific VBA for Word macro that generates a styled Word document which will then be digested by a Word-friendly CMS.</p>
| 2 | 2009-09-14T18:48:01Z | 1,423,323 | <pre><code>re.sub(r'(?<!-)\n(?!-)', ' ', text)
</code></pre>
<p>(Hyphen doesn't need escaping outside of a character class.)</p>
| 1 | 2009-09-14T19:03:04Z | [
"python",
"regex"
] |
Negative lookahead after newline? | 1,423,260 | <p>I have a CSV-like text file that has about 1000 lines. Between each record in the file is a long series of dashes. The records generally end with a \n, but sometimes there is an extra \n before the end of the record. Simplified example:</p>
<pre><code>"1x", "1y", "Hi there"
-------------------------------
"2x", "2y", "Hello - I'm lost"
-------------------------------
"3x", "3y", "How ya
doing?"
-------------------------------
</code></pre>
<p>I want to replace the extra \n's with spaces, i.e. concatenate the lines between the dashes. I thought I would be able to do this (Python 2.5):</p>
<pre><code>text = open("thefile.txt", "r").read()
better_text = re.sub(r'\n(?!\-)', ' ', text)
</code></pre>
<p>but that seems to replace every \n, not just the ones that are not followed by a dash. What am I doing wrong?</p>
<p>I am asking this question in an attempt to improve my own regex skills and understand the mistakes that I made. The end goal is to generate a text file in a format that is usable by a specific VBA for Word macro that generates a styled Word document which will then be digested by a Word-friendly CMS.</p>
| 2 | 2009-09-14T18:48:01Z | 1,423,344 | <p>This is a good place to use a generator function to skip the lines of <code>----</code>'s and yield something that the csv module can read.</p>
<pre><code>def readCleanLines( someFile ):
for line in someFile:
if line.strip() == len(line.strip())*'-':
continue
yield line
reader= csv.reader( readCleanLines( someFile ) )
for row in reader:
print row
</code></pre>
<p>This should handle the line breaks inside quotes seamlessly and silently.</p>
<p><hr /></p>
<p>If you want to do other things with this file, for example, save a copy with the <code>----</code> lines removed, you can do this.</p>
<pre><code>with open( "source", "r" ) as someFile:
with open( "destination", "w" ) as anotherFile:
for line in readCleanLines( someFile ):
anotherFile.write( line )
</code></pre>
<p>That will make a copy with the <code>----</code> lines removed. This isn't really worth the effort, since reading and skipping the lines is very, very fast and doesn't require any additional storage.</p>
| 7 | 2009-09-14T19:08:25Z | [
"python",
"regex"
] |
Negative lookahead after newline? | 1,423,260 | <p>I have a CSV-like text file that has about 1000 lines. Between each record in the file is a long series of dashes. The records generally end with a \n, but sometimes there is an extra \n before the end of the record. Simplified example:</p>
<pre><code>"1x", "1y", "Hi there"
-------------------------------
"2x", "2y", "Hello - I'm lost"
-------------------------------
"3x", "3y", "How ya
doing?"
-------------------------------
</code></pre>
<p>I want to replace the extra \n's with spaces, i.e. concatenate the lines between the dashes. I thought I would be able to do this (Python 2.5):</p>
<pre><code>text = open("thefile.txt", "r").read()
better_text = re.sub(r'\n(?!\-)', ' ', text)
</code></pre>
<p>but that seems to replace every \n, not just the ones that are not followed by a dash. What am I doing wrong?</p>
<p>I am asking this question in an attempt to improve my own regex skills and understand the mistakes that I made. The end goal is to generate a text file in a format that is usable by a specific VBA for Word macro that generates a styled Word document which will then be digested by a Word-friendly CMS.</p>
| 2 | 2009-09-14T18:48:01Z | 1,423,449 | <p>A RegEx isn't always the best tool for the job. How about running it through something like "Split" or "Tokenize" first? (I'm sure python has an equivalent) Then you have your records and can assume newlines are just continuations.</p>
| 0 | 2009-09-14T19:29:07Z | [
"python",
"regex"
] |
What is the best design for polling a modem for incoming data? | 1,423,308 | <p>I have a GSM modem connected to my computer, i want to receive text messages sent to it using a python program i have written, am just wondering what is the best technique to poll for data. </p>
<p>Should i write a program that has a infinite loop that continuously checks for incoming sms's i.e within the loop the program sends the AT commands and reads the input data. or do modems have a way of signaling an application of an incoming data(sms). </p>
<p>Am trying to imagine a cellphone is just a GSM modem, and when an sms is received, the phone alerts you of the event, or does the phone software have an infinite loop that polls for incoming data.</p>
| 8 | 2009-09-14T18:59:14Z | 1,423,366 | <p>I have written something similar before. There is a way using AT commands to tell the modem to signal you each time an SMS is received.</p>
<p>For reference, I was using a <a href="http://www.maestro-wireless.com/modules/product.php" rel="nofollow">Maestro 100 GSM Modem</a> in an embedded application.</p>
<p>First you have to initialize the modem properly. I was using text mode for the SMS, but you might be using something different. Pick from these what you want. AT+CNMI is the most important.</p>
<pre><code>AT&F0 # Restore factory defaults
ATE0 # Disable command echo
AT+CMGF=1 # Set message format to text mode
AT+CNMI=1,1,0,1,0 # Set new message indicator
AT+CPMS="SM","SM","SM" # Set preferred message storage to SIM
</code></pre>
<p>You would then wait for a message notification, that will look like this. (Don't match on the index number, that might differ between notifications)</p>
<pre><code>+CMTI: "SM",0 # Message notification with index
</code></pre>
<p>When you get that notification, retrieve the unread SMS's:</p>
<pre><code>AT+CMGL="REC UNREAD" # Retrieve unread messages
</code></pre>
<p>I would recommend you also add a poll, maybe every 5 minutes or so, just in case you miss a notification. With serial comms you can never be sure!</p>
| 3 | 2009-09-14T19:14:09Z | [
"python",
"modem",
"gsm",
"at-command"
] |
What is the best design for polling a modem for incoming data? | 1,423,308 | <p>I have a GSM modem connected to my computer, i want to receive text messages sent to it using a python program i have written, am just wondering what is the best technique to poll for data. </p>
<p>Should i write a program that has a infinite loop that continuously checks for incoming sms's i.e within the loop the program sends the AT commands and reads the input data. or do modems have a way of signaling an application of an incoming data(sms). </p>
<p>Am trying to imagine a cellphone is just a GSM modem, and when an sms is received, the phone alerts you of the event, or does the phone software have an infinite loop that polls for incoming data.</p>
| 8 | 2009-09-14T18:59:14Z | 1,424,253 | <p>I find I can't remember much of the AT command set related to SMS. Andre Miller's answer seems to ring a few bells. Anyway you should read the documentation very carefully, I'm sure there were a few gotchas.</p>
<p>My recommentation for polling is at least every 5 seconds - this is just for robustness and responsiveness in the face of disconnection.</p>
<p>I used a state machine to navigate between initialisation, reading and deleting messages.</p>
| 0 | 2009-09-14T22:39:19Z | [
"python",
"modem",
"gsm",
"at-command"
] |
Can I run a Python script as a service? | 1,423,345 | <p>Is it possible to run a Python script as a background service on a webserver? I want to do this for <a href="http://stackoverflow.com/questions/1422929/socket-communication">socket communication.</a></p>
| 12 | 2009-09-14T19:08:36Z | 1,423,369 | <p>Assuming this is for Windows, see <a href="http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html" rel="nofollow">this recipe based on srvany</a></p>
| 1 | 2009-09-14T19:14:27Z | [
"python",
"web-services",
"sockets",
"webserver"
] |
Can I run a Python script as a service? | 1,423,345 | <p>Is it possible to run a Python script as a background service on a webserver? I want to do this for <a href="http://stackoverflow.com/questions/1422929/socket-communication">socket communication.</a></p>
| 12 | 2009-09-14T19:08:36Z | 1,423,371 | <p>You might want to check out <a href="http://twistedmatrix.com/trac/">Twisted</a>.</p>
| 7 | 2009-09-14T19:14:29Z | [
"python",
"web-services",
"sockets",
"webserver"
] |
Can I run a Python script as a service? | 1,423,345 | <p>Is it possible to run a Python script as a background service on a webserver? I want to do this for <a href="http://stackoverflow.com/questions/1422929/socket-communication">socket communication.</a></p>
| 12 | 2009-09-14T19:08:36Z | 1,423,375 | <p>If you are talking about linux, it is as easy as doing something like ./myscript.py &</p>
| 0 | 2009-09-14T19:15:19Z | [
"python",
"web-services",
"sockets",
"webserver"
] |
Can I run a Python script as a service? | 1,423,345 | <p>Is it possible to run a Python script as a background service on a webserver? I want to do this for <a href="http://stackoverflow.com/questions/1422929/socket-communication">socket communication.</a></p>
| 12 | 2009-09-14T19:08:36Z | 1,423,388 | <p>on XP and later you can use the <strong>sc.exe</strong> program to use any .exe as service:</p>
<pre><code>>sc create
Creates a service entry in the registry and Service Database.
SYNTAX:
sc create [service name] [binPath= ] <option1> <option2>...
CREATE OPTIONS:
NOTE: The option name includes the equal sign.
type= <own|share|interact|kernel|filesys|rec>
(default = own)
start= <boot|system|auto|demand|disabled>
(default = demand)
error= <normal|severe|critical|ignore>
(default = normal)
binPath= <BinaryPathName>
group= <LoadOrderGroup>
tag= <yes|no>
depend= <Dependencies(separated by / (forward slash))>
obj= <AccountName|ObjectName>
(default = LocalSystem)
DisplayName= <display name>
password= <password>
</code></pre>
<p>You can start your pythonscript by starting the python interpreter with your script as argument:</p>
<pre><code>python.exe myscript.py
</code></pre>
| 2 | 2009-09-14T19:18:59Z | [
"python",
"web-services",
"sockets",
"webserver"
] |
Can I run a Python script as a service? | 1,423,345 | <p>Is it possible to run a Python script as a background service on a webserver? I want to do this for <a href="http://stackoverflow.com/questions/1422929/socket-communication">socket communication.</a></p>
| 12 | 2009-09-14T19:08:36Z | 1,423,498 | <p>You can make it a daemon. There is a PEP for a more complete solution, but I have found that this works well.</p>
<pre><code>import os, sys
def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', pidfile='/var/tmp/daemon.pid'):
""" Make the current process a daemon. """
try:
# First fork
try:
if os.fork() > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write('fork #1 failed" (%d) %s\n' % (e.errno, e.strerror))
sys.exit(1)
os.setsid()
os.chdir(our_home_dir)
os.umask(0)
# Second fork
try:
pid = os.fork()
if pid > 0:
# You must write the pid file here. After the exit()
# the pid variable is gone.
fpid = open(pidfile, 'wb')
fpid.write(str(pid))
fpid.close()
sys.exit(0)
except OSError, e:
sys.stderr.write('fork #2 failed" (%d) %s\n' % (e.errno, e.strerror))
sys.exit(1)
si = open('/dev/null', 'r')
so = open(out_log, 'a+', 0)
se = open(err_log, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
except Exception, e:
sys.stderr.write(str(e))
</code></pre>
| 8 | 2009-09-14T19:40:18Z | [
"python",
"web-services",
"sockets",
"webserver"
] |
Can I run a Python script as a service? | 1,423,345 | <p>Is it possible to run a Python script as a background service on a webserver? I want to do this for <a href="http://stackoverflow.com/questions/1422929/socket-communication">socket communication.</a></p>
| 12 | 2009-09-14T19:08:36Z | 1,423,556 | <p>There is the very helpful <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">Pypi package</a> which is the basis for my daemons written in Python.</p>
| 2 | 2009-09-14T19:52:26Z | [
"python",
"web-services",
"sockets",
"webserver"
] |
What is wrong with this python function from "Programming Collective Intelligence"? | 1,423,525 | <p>This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.</p>
<p>When I use this with real user data, it sometimes returns a number greater than 1, like in this example:</p>
<pre><code>def sim_pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]: si[item]=1
if len(si)==0: return 0
n=len(si)
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p2][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
num=pSum-(sum1*sum2/n)
den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
if den==0: return 0
r=num/den
return r
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
print sim_pearson(critics, 'user1', 'user2', )
1.15470053838
</code></pre>
| 4 | 2009-09-14T19:46:12Z | 1,423,580 | <p>It looks like you may be unexpectedly using integer division. I made the following change and your function returned <code>1.0</code>:</p>
<pre><code>num=pSum-(1.0*sum1*sum2/n)
den=sqrt((sum1Sq-1.0*pow(sum1,2)/n)*(sum2Sq-1.0*pow(sum2,2)/n))
</code></pre>
<p>See <a href="http://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator" rel="nofollow">PEP 238</a> for more information on the division operator in Python. An alternate way of fixing your above code is:</p>
<pre><code>from __future__ import division
</code></pre>
| 8 | 2009-09-14T19:56:51Z | [
"python",
"algorithm",
"pearson"
] |
What is wrong with this python function from "Programming Collective Intelligence"? | 1,423,525 | <p>This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.</p>
<p>When I use this with real user data, it sometimes returns a number greater than 1, like in this example:</p>
<pre><code>def sim_pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]: si[item]=1
if len(si)==0: return 0
n=len(si)
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p2][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
num=pSum-(sum1*sum2/n)
den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
if den==0: return 0
r=num/den
return r
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
print sim_pearson(critics, 'user1', 'user2', )
1.15470053838
</code></pre>
| 4 | 2009-09-14T19:46:12Z | 1,423,592 | <p>Well it took me a minute to read over the code but it seems if you change your input data to <strong>floats</strong> it will work</p>
| 2 | 2009-09-14T19:58:46Z | [
"python",
"algorithm",
"pearson"
] |
What is wrong with this python function from "Programming Collective Intelligence"? | 1,423,525 | <p>This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.</p>
<p>When I use this with real user data, it sometimes returns a number greater than 1, like in this example:</p>
<pre><code>def sim_pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]: si[item]=1
if len(si)==0: return 0
n=len(si)
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p2][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
num=pSum-(sum1*sum2/n)
den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
if den==0: return 0
r=num/den
return r
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
print sim_pearson(critics, 'user1', 'user2', )
1.15470053838
</code></pre>
| 4 | 2009-09-14T19:46:12Z | 1,423,611 | <p>Integer division is confusing it. It works if you make <code>n</code> a float:</p>
<pre><code>n=float(len(si))
</code></pre>
| 2 | 2009-09-14T20:02:40Z | [
"python",
"algorithm",
"pearson"
] |
What is wrong with this python function from "Programming Collective Intelligence"? | 1,423,525 | <p>This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.</p>
<p>When I use this with real user data, it sometimes returns a number greater than 1, like in this example:</p>
<pre><code>def sim_pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]: si[item]=1
if len(si)==0: return 0
n=len(si)
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p2][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
num=pSum-(sum1*sum2/n)
den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
if den==0: return 0
r=num/den
return r
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
print sim_pearson(critics, 'user1', 'user2', )
1.15470053838
</code></pre>
| 4 | 2009-09-14T19:46:12Z | 1,423,658 | <p>Well, I wasn't exactly able to find what's wrong with the logic in your function, so I just reimplemented it using the definition of Pearson coefficient:</p>
<pre><code>from math import sqrt
def sim_pearson(p1,p2):
keys = set(p1) | set(p2)
n = len(keys)
a1 = sum(p1[it] for it in keys) / n
a2 = sum(p2[it] for it in keys) / n
# print(a1, a2)
sum1Sq = sum((p1[it] - a1) ** 2 for it in keys)
sum2Sq = sum((p2[it] - a2) ** 2 for it in keys)
num = sum((p1[it] - a1) * (p2[it] - a2) for it in keys)
den = sqrt(sum1Sq * sum2Sq)
# print(sum1Sq, sum2Sq, num, den)
return num / den
critics = {
'user1':{
'item1': 3,
'item2': 5,
'item3': 5,
},
'user2':{
'item1': 4,
'item2': 5,
'item3': 5,
}
}
assert 0.999 < sim_pearson(critics['user1'], critics['user1']) < 1.0001
print('Your example:', sim_pearson(critics['user1'], critics['user2']))
print('Another example:', sim_pearson({1: 1, 2: 2, 3: 3}, {1: 4, 2: 0, 3: 1}))
</code></pre>
<p>Note that in your example the Pearson coefficient is just <code>1.0</code> since vectors (-4/3, 2/3, 2/3) and (-2/3, 1/3, 1/3) are parallel. </p>
| 1 | 2009-09-14T20:12:23Z | [
"python",
"algorithm",
"pearson"
] |
Finding if a python datetime has no time information | 1,423,673 | <p>I want to trap values that are like this (in which there is not 'time info' on the datetime):</p>
<pre><code>datetime.datetime(2009, 4, 6, 0, 0)
</code></pre>
<p>Is there a better way to detect these values other than testing hour/minute/second?</p>
<pre><code>if value.hour == 0 and value.minute == 0 and value.second == 0:
# do stuff
</code></pre>
| 1 | 2009-09-14T20:15:21Z | 1,423,713 | <p>I see nothing wrong with your method, but you could compare it to a 'zeroed' time object.</p>
<pre><code>someDateTime = datetime.datetime(2009, 4, 6, 0, 0)
someDateTime.time() == datetime.time(0)
</code></pre>
| 1 | 2009-09-14T20:24:56Z | [
"python",
"datetime"
] |
Finding if a python datetime has no time information | 1,423,673 | <p>I want to trap values that are like this (in which there is not 'time info' on the datetime):</p>
<pre><code>datetime.datetime(2009, 4, 6, 0, 0)
</code></pre>
<p>Is there a better way to detect these values other than testing hour/minute/second?</p>
<pre><code>if value.hour == 0 and value.minute == 0 and value.second == 0:
# do stuff
</code></pre>
| 1 | 2009-09-14T20:15:21Z | 1,423,724 | <p>Another option:</p>
<pre><code>if not (value.hour or value.minute or value.second):
# do stuff
</code></pre>
| 0 | 2009-09-14T20:25:59Z | [
"python",
"datetime"
] |
Finding if a python datetime has no time information | 1,423,673 | <p>I want to trap values that are like this (in which there is not 'time info' on the datetime):</p>
<pre><code>datetime.datetime(2009, 4, 6, 0, 0)
</code></pre>
<p>Is there a better way to detect these values other than testing hour/minute/second?</p>
<pre><code>if value.hour == 0 and value.minute == 0 and value.second == 0:
# do stuff
</code></pre>
| 1 | 2009-09-14T20:15:21Z | 1,423,730 | <p>You would actually need to check microsecond as well. Another option:</p>
<pre><code>NO_TIME = datetime.time(0) # can be stored as constant
if (value.time() == NO_TIME):
# do stuff
</code></pre>
| 1 | 2009-09-14T20:27:25Z | [
"python",
"datetime"
] |
Finding if a python datetime has no time information | 1,423,673 | <p>I want to trap values that are like this (in which there is not 'time info' on the datetime):</p>
<pre><code>datetime.datetime(2009, 4, 6, 0, 0)
</code></pre>
<p>Is there a better way to detect these values other than testing hour/minute/second?</p>
<pre><code>if value.hour == 0 and value.minute == 0 and value.second == 0:
# do stuff
</code></pre>
| 1 | 2009-09-14T20:15:21Z | 1,423,732 | <p>don't neglect that HMS==0 for 1 in 86,400 fully completed time values! depending on what you're doing, that might not be negligible.</p>
| 3 | 2009-09-14T20:27:29Z | [
"python",
"datetime"
] |
Finding if a python datetime has no time information | 1,423,673 | <p>I want to trap values that are like this (in which there is not 'time info' on the datetime):</p>
<pre><code>datetime.datetime(2009, 4, 6, 0, 0)
</code></pre>
<p>Is there a better way to detect these values other than testing hour/minute/second?</p>
<pre><code>if value.hour == 0 and value.minute == 0 and value.second == 0:
# do stuff
</code></pre>
| 1 | 2009-09-14T20:15:21Z | 1,423,736 | <p>The time method works here. Evaluates as boolean false if there's zero'd-out time info.</p>
<pre><code>if not value.time():
# do stuff
</code></pre>
| 10 | 2009-09-14T20:28:35Z | [
"python",
"datetime"
] |
Writing a connection string when password contains special characters | 1,423,804 | <p>I'm using SQLalchemy for a Python project, and I want to have a tidy connection string to access my database. So for example:</p>
<pre><code>engine = create_engine('postgres://user:pass@host/database')
</code></pre>
<p>The problem is my password contains a sequence of special characters that get interpreted as delimiters when I try to connect. </p>
<p>I realize I could just create an object and then pass my credentials like this:</p>
<pre><code>drivername = 'postgres',
username = 'user',
password = 'pass',
host = 'host',
database = 'database'
</code></pre>
<p>But I'd much rather use a connection string if this is possible. </p>
<p>So to be clear, is it possible to encode my connection string, or the password part of the connection string - so that it can be properly parsed?</p>
| 10 | 2009-09-14T20:41:50Z | 1,424,009 | <p>Backslashes aren't valid escape characters for URL component strings. You need to URL-encode the password portion of the connect string:</p>
<pre><code>from urllib import quote_plus as urlquote
from sqlalchemy.engine import create_engine
engine = create_engine('postgres://user:%s@host/database' % urlquote('badpass'))
</code></pre>
<p>If you look at the implementation of the class used in SQLAlchemy to represent database connection URLs (in <code>sqlalchemy/engine/url.py</code>), you can see that they use the same method to escape passwords when converting the URL instances into strings, and that the parsing code uses the complementary <code>urllib.unquote_plus</code> function to extract the password from a connection string.</p>
| 22 | 2009-09-14T21:26:51Z | [
"python",
"character-encoding",
"sqlalchemy",
"connection-string"
] |
hashlib / md5. Compatibility with python 2.4 | 1,423,861 | <p>python 2.6 reports that the md5 module is obsolete and hashlib should be used. If I change <code>import md5</code> to <code>import hashlib</code> I will solve for python 2.5 and python 2.6, but not for python 2.4, which has no hashlib module (leading to a ImportError, which I can catch).</p>
<p>Now, to fix it, I could do a try/catch, and define a getMd5() function so that a proper one gets defined according to the result of the try block. Is this solution ok? </p>
<p>How would you solve this issue in a more general case, like, for example: you have two different libraries with the same objective but different interface, and you want to use one, but fall back and use the other if the first one is not found.</p>
| 8 | 2009-09-14T20:51:42Z | 1,423,871 | <p>In general the following construct is just fine:</p>
<pre><code>try:
import module
except ImportError:
# Do something else.
</code></pre>
<p>In your particular case, perhaps:</p>
<pre><code>try:
from hashlib import md5
except ImportError:
from md5 import md5
</code></pre>
| 18 | 2009-09-14T20:54:25Z | [
"python",
"import",
"md5",
"backwards-compatibility",
"hashlib"
] |
hashlib / md5. Compatibility with python 2.4 | 1,423,861 | <p>python 2.6 reports that the md5 module is obsolete and hashlib should be used. If I change <code>import md5</code> to <code>import hashlib</code> I will solve for python 2.5 and python 2.6, but not for python 2.4, which has no hashlib module (leading to a ImportError, which I can catch).</p>
<p>Now, to fix it, I could do a try/catch, and define a getMd5() function so that a proper one gets defined according to the result of the try block. Is this solution ok? </p>
<p>How would you solve this issue in a more general case, like, for example: you have two different libraries with the same objective but different interface, and you want to use one, but fall back and use the other if the first one is not found.</p>
| 8 | 2009-09-14T20:51:42Z | 1,423,882 | <p>In the case where the modules have the same interface, as they do here, the solution you described is fine. You could also isolate the import into its own module like this:</p>
<pre><code>hash.py
----
try:
import hashlib.md5 as md5mod
except ImportError:
import md5 as md5mod
-----
prog.py
-----
from hash import md5mod
....
</code></pre>
<p>In the case where they have different interfaces you would need to write an adaptor to align the interfaces as you have specified.</p>
| 2 | 2009-09-14T20:57:09Z | [
"python",
"import",
"md5",
"backwards-compatibility",
"hashlib"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 1,423,938 | <p>Programs can modify what directories they check for libraries uwith <a href="http://perldoc.perl.org/lib.html" rel="nofollow"><code>use lib</code></a>. This lib directory can be relative to the current directory. Libraries from these directories will be used before system libraries, as they are placed at the beginning of the @INC array.</p>
<p>I believe cpan can also install libraries to specific directories. Granted, cpan draws from the <a href="http://www.cpan.org/" rel="nofollow">CPAN site</a> in order to install things, so this may not be the best option.</p>
| 1 | 2009-09-14T21:06:32Z | [
"python",
"perl",
"virtualenv"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 1,423,955 | <p>I am not sure whether this is the same as that <code>virtualenv</code> thing you are talking about, but have a look for the <code>@INC</code> special variable in the <code>perlvar</code> manpage.</p>
| 1 | 2009-09-14T21:11:06Z | [
"python",
"perl",
"virtualenv"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 1,423,961 | <p>There's a tool called <a href="http://search.cpan.org/perldoc/local%3A%3Alib"><code>local::lib</code></a> that wraps up all of the work for you, much like <code>virtualenv</code>. It will:</p>
<ul>
<li>Set up <code>@INC</code> in the process where it's used.</li>
<li>Set <code>PERL5LIB</code> and other such things for child processes.</li>
<li>Set the right variables to convince CPAN, <a href="http://search.cpan.org/perldoc/ExtUtils%3A%3AMakeMaker"><code>MakeMaker</code></a>, <a href="http://search.cpan.org/perldoc/Module%3A%3ABuild"><code>Module::Build</code></a>, etc. to install libraries and store configuration in a local directory.</li>
<li>Set <code>PATH</code> so that installed binaries can be found.</li>
<li>Print environment variables to stdout when used from the commandline so that you can put <code>eval $(perl -Mlocal::lib)</code>
in your <code>.profile</code> and then mostly forget about it.</li>
</ul>
| 20 | 2009-09-14T21:12:15Z | [
"python",
"perl",
"virtualenv"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 1,423,992 | <p>What I do is start the CPAN shell (cpan) and install my own Perl 5.10 from it
(I believe the command is install perl-5.10). This will ask for various configuration
settings; I make sure to make it point to paths under /usr/local
(or some other installation location other than the default).</p>
<p>Then I put its resulting location in my executable $PATH before the standard perl, and use its CPAN shell to install the modules I need (usually, a lot).
My Perl scripts all start with the line</p>
<pre><code>#!/usr/bin/env perl
</code></pre>
<p>Never had a problem with this approach.</p>
| 0 | 2009-09-14T21:23:27Z | [
"python",
"perl",
"virtualenv"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 1,426,824 | <p>I've used <code>schroot</code> for this purpose. It is a bit heavier than virtualenv but you can be sure that nothing will leak in that shouldn't.</p>
<p><code>Schroot</code> manages a chroot environment for you, but mounts your home directory in the chroot so it appears like a normal shell session, just using the binaries and libraries in the chroot.</p>
<p>I think it may be debian/ubuntu only though.</p>
<p>After setting up the <code>schroot</code>, your script above would look like</p>
<pre><code>schroot -c my_perl_dev
wget ...
</code></pre>
<p>See <a href="http://www.debian-administration.org/articles/566" rel="nofollow">http://www.debian-administration.org/articles/566</a> for an interesting article about it</p>
| 1 | 2009-09-15T12:16:37Z | [
"python",
"perl",
"virtualenv"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 1,428,209 | <p>It looks like you just need to use the INSTALL_BASE configuration for Makefile.PL (or the --install_base option for Build.PL)? What exactly do you need the solution to do for you? It sounds like you just need to get the installed module in the right place. You've presented your problem as an <a href="http://www.perlmonks.org/index.pl?node%5Fid=542341" rel="nofollow">XY Problem</a> by specifying what you think is the solution is rather than letting us help you with your task.</p>
<p>See <a href="http://faq.perl.org/perlfaq8.html#How%5Fdo%5FI%5Fkeep%5Fmy%5Fown" rel="nofollow">How do I keep my own module/library directory?</a> in perlfaq8, for instance.</p>
<p>If you are downloading modules from CPAN, the latest <code>cpan</code> command (in <a href="http://search.cpan.org/dist/App-Cpan" rel="nofollow">App::Cpan</a>) has a <code>-j</code> switch to allow you to choose alternate CPAN.pm configuration files. In those configuration files you can set the CPAN.pm options to install wherever you like.</p>
<p>Based on your clarification, it sounds like local::lib might work for you in single, simple cases, but I do this for industrial strength deployments where I set up custom, private CPANs per application, and install directly from those custom CPANs. See my <a href="http://search.cpan.org/dist/MyCPAN-App-DPAN" rel="nofollow">MyCPAN::App::DPAN</a> module, for instance. From that, I use custom CPAN.pm configs that analyze their environment and set the proper values to each application can install everything in a directory just for that application.</p>
<p>You might also consider distributing your application as a Task::. You install it like any other Perl module, but dependencies share that same setup (i.e. INSTALL_BASE).</p>
| 0 | 2009-09-15T16:27:12Z | [
"python",
"perl",
"virtualenv"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 24,569,961 | <p>Also checkout <a href="https://github.com/jizhang/perl-virtualenv" rel="nofollow">perl-virtualenv</a> , this seems to be wrapper around local::lib as suggested by Hobbs, but creates a bin/activate and bin/deactivate so you can use it just like the python tool.</p>
<p>I've been using it quite successfully for a month or so without realising it wasn't as standards as perhaps it should be. </p>
<p>It makes it lot easier to set up a working virtualenv for perl as while local:lib will tell you what variables you need to set, etc. perl-virtualenv creates an activate script which does it for you.</p>
| 0 | 2014-07-04T08:32:17Z | [
"python",
"perl",
"virtualenv"
] |
How can I install specialized environments for different Perl applications? | 1,423,879 | <p>Is there anything equivalent or close in terms of functionality to Python's <a href="http://pypi.python.org/pypi/virtualenv#what-it-does">virtualenv</a>, but for Perl? </p>
<p>I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a huge advantage. Now I have to work on a new project in Perl, and I'm looking for something like virtualenv, but for Perl. Can you suggest any Perl equivalent or replacement for python's virtualenv?</p>
<p>I'm trying to setup X different sets of non-system Perl packages for Y different applications to be deployed. Even worse, these applications may require different versions of the same package, so each of them may require to be installed in a separate module/library environment. You may want to do this manually for X < Y < 3. But you should not do this manually for 10 > Y > X.</p>
<p>Ideally what I'm looking should work like this:</p>
<pre><code>perl virtualenv.pl my_environment
. my_environment/bin/activate
wget http://.../foo-0.1.tar.gz
tar -xzf foo-0.1.tar.gz ; cd foo-0.1
perl Makefile.pl
make install # <-- package foo-0.1 gets installed inside my_environment
perl -MCPAN -e 'install Bar' # <-- now package Bar with all its deps gets installed inside my_environment
</code></pre>
| 17 | 2009-09-14T20:56:34Z | 36,733,772 | <p>While investigating, I discovered this and some other pages (<a href="http://stackoverflow.com/questions/29950300/what-is-the-relationship-between-virtualenv-and-pyenv">this one is too old</a> and misses new technologies, <a href="https://www.reddit.com/r/perl/comments/3hry19/how_do_you_make_something_similar_to_a_python/" rel="nofollow">this reddit post is a slight misdirect</a>).</p>
<p>The problem with perlbrew and plenv is that they seem to be replacements for pyenv, not virtualenv. As noted <a href="http://stackoverflow.com/questions/29950300/what-is-the-relationship-between-virtualenv-and-pyenv">here</a> pyenv is for managing python versions, virtualenv is for managing per-project module versions. So, yes, in some ways similar to <a href="http://search.cpan.org/~haarg/local-lib-2.000019/lib/local/lib.pm#CREATING_A_SELF-CONTAINED_SET_OF_MODULES" rel="nofollow">local::lib</a>, but with better usability. </p>
<p>I've not seen a proper answer to this question yet, but from what I've read, it looks like the best solution is something along the lines of:</p>
<ul>
<li>Perl version management: <a href="https://github.com/tokuhirom/plenv" rel="nofollow">plenv</a>/<a href="http://perlbrew.pl/" rel="nofollow">perlbrew</a> (with most people
favouring the more contemporary bash based plenv over the perl based
perlbrew from what I can see) </li>
<li>Module version management: <a href="https://github.com/perl-carton/carton" rel="nofollow">Carton</a></li>
<li>Module installation: cpan (well, <a href="http://stackoverflow.com/questions/5861292/which-cpan-installer-is-the-right-one-cpan-pm-cpanplus-cpanminus">cpanminus</a> anyway, ymmv)</li>
</ul>
<p>To be honest, this is not an <em>ideal</em> set up, although I'm still learning, so it may yet be superior. It just doesn't feel right. It certainly isn't a like for like replacement for <a href="https://virtualenv.pypa.io/en/latest/" rel="nofollow">virtualenv</a>.</p>
<p>There are a couple of posts I've found saying "<a href="http://blog.polettix.it/parachuting-perl/" rel="nofollow">it</a> <a href="http://www.slideshare.net/pplusdomain/plenv-and-carton" rel="nofollow">is</a> <a href="http://kappataumu.com/articles/modern-perl-toolchain-for-web-apps.html" rel="nofollow">possible</a>" but neither has gone any further.</p>
| 0 | 2016-04-20T04:23:11Z | [
"python",
"perl",
"virtualenv"
] |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | <p>I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:</p>
<pre><code>string_val = 'abcdefghij'
</code></pre>
| 53 | 2009-09-14T21:26:10Z | 1,424,014 | <p>The first ten lowercase letters are <code>string.lowercase[:10]</code> (if you have imported the standard library module <code>string</code> previously, of course;-).</p>
<p>Other ways to "make a string of 10 characters": <code>'x'*10</code> (all the ten characters will be lowercase <code>x</code>s;-), <code>''.join(chr(ord('a')+i) for i in xrange(10))</code> (the first ten lowercase letters again), etc, etc;-).</p>
| 8 | 2009-09-14T21:28:20Z | [
"python",
"string"
] |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | <p>I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:</p>
<pre><code>string_val = 'abcdefghij'
</code></pre>
| 53 | 2009-09-14T21:26:10Z | 1,424,016 | <p>To simply repeat the same letter 10 times:</p>
<pre><code>string_val = "x" * 10 # gives you "xxxxxxxxxx"
</code></pre>
<p>And if you want something more complex, like <code>n</code> random lowercase letters, it's still only one line of code (not counting the import statements and defining <code>n</code>):</p>
<pre><code>from random import choice
from string import lowercase
n = 10
string_val = "".join(choice(lowercase) for i in range(n))
</code></pre>
| 130 | 2009-09-14T21:28:40Z | [
"python",
"string"
] |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | <p>I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:</p>
<pre><code>string_val = 'abcdefghij'
</code></pre>
| 53 | 2009-09-14T21:26:10Z | 1,424,017 | <p>If you can use repeated letters, you can use the <code>*</code> operator:</p>
<pre><code>>>> 'a'*5
'aaaaa'
</code></pre>
| 0 | 2009-09-14T21:29:46Z | [
"python",
"string"
] |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | <p>I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:</p>
<pre><code>string_val = 'abcdefghij'
</code></pre>
| 53 | 2009-09-14T21:26:10Z | 1,424,021 | <p>Why "one line"? You can fit anything onto one line.</p>
<p>Assuming you want them to start with 'a', and increment by one character each time (with wrapping > 26), here's a line:</p>
<pre><code>>>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x))))
>>> mkstring(10)
'abcdefghij'
>>> mkstring(30)
'abcdefghijklmnopqrstuvwxyzabcd'
</code></pre>
| 1 | 2009-09-14T21:30:22Z | [
"python",
"string"
] |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | <p>I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:</p>
<pre><code>string_val = 'abcdefghij'
</code></pre>
| 53 | 2009-09-14T21:26:10Z | 1,424,024 | <p>if you just want any letters:</p>
<pre><code> 'a'*10 # gives 'aaaaaaaaaa'
</code></pre>
<p>if you want consecutive letters (up to 26):</p>
<pre><code> ''.join(['%c' % x for x in range(97, 97+10)]) # gives 'abcdefghij'
</code></pre>
| 0 | 2009-09-14T21:31:14Z | [
"python",
"string"
] |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | <p>I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:</p>
<pre><code>string_val = 'abcdefghij'
</code></pre>
| 53 | 2009-09-14T21:26:10Z | 21,192,936 | <p>This might be a little off the question, but for those interested in the randomness of the generated string, my answer would be:</p>
<pre><code>import os
import string
def _pwd_gen(size=16):
chars = string.letters
chars_len = len(chars)
return str().join(chars[int(ord(c) / 256. * chars_len)] for c in os.urandom(size))
</code></pre>
<p>See <a href="https://stackoverflow.com/a/7480271/421846">these</a> <a href="https://stackoverflow.com/a/12399465/421846">answers</a> and <code>random.py</code>'s source for more insight.</p>
| 1 | 2014-01-17T18:12:25Z | [
"python",
"string"
] |
Komodo Edit - code-completion for Django? | 1,424,392 | <p>I've been using Komodo Edit for a small project in Django.</p>
<p>The code completion features seem to work pretty well for standard python modules, however, it doesn't know anything about Django modules. Is there any way to configure Komodo Edit to use Django modules for autocomplete as well?</p>
| 2 | 2009-09-14T23:26:17Z | 1,424,422 | <p>By sure Django is on your python path and Komodo should pick it up. Alternatively you can add the location of Django to where Komodo looks for its autocomplete.</p>
| 4 | 2009-09-14T23:36:21Z | [
"python",
"django",
"ide",
"code-completion",
"komodo"
] |
Komodo Edit - code-completion for Django? | 1,424,392 | <p>I've been using Komodo Edit for a small project in Django.</p>
<p>The code completion features seem to work pretty well for standard python modules, however, it doesn't know anything about Django modules. Is there any way to configure Komodo Edit to use Django modules for autocomplete as well?</p>
| 2 | 2009-09-14T23:26:17Z | 1,424,443 | <blockquote>
<p>o to Edit > Preferences. Expand the
"Languages" group by clicking the [+]
symbol. Click "Python". Click the
little "Add..." button under
"Additional Python Import
Directories". Add the directory ABOVE
your project and you should have
intellisense enabled.</p>
</blockquote>
<p>This has always worked for me for both Django and my individual projects. </p>
| 8 | 2009-09-14T23:43:24Z | [
"python",
"django",
"ide",
"code-completion",
"komodo"
] |
Komodo Edit - code-completion for Django? | 1,424,392 | <p>I've been using Komodo Edit for a small project in Django.</p>
<p>The code completion features seem to work pretty well for standard python modules, however, it doesn't know anything about Django modules. Is there any way to configure Komodo Edit to use Django modules for autocomplete as well?</p>
| 2 | 2009-09-14T23:26:17Z | 1,424,499 | <p>Hmmm. It's installed by default so my answer probably isn't the right solution. :-)</p>
<p>But here goes...</p>
<p>You can install a Django extension in Komodo edit. I haven't tested it myself but you can test it.</p>
<blockquote>
<p>Tools -> Add-ons -> Extensions</p>
</blockquote>
<p>It's name is "Django Language".</p>
<p>Check if it works.</p>
| 2 | 2009-09-15T00:09:27Z | [
"python",
"django",
"ide",
"code-completion",
"komodo"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 1,424,502 | <p>If you locate the idlelib directory in your Python install, it will have a few files with the .def extension. config-main.def has instructions on where to put the custom config files. However, looking through these I did not find any configurable paths (your install may vary). Looks like you might need to crack open the editor code to alter it.</p>
| 0 | 2009-09-15T00:10:32Z | [
"python",
"python-idle"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 1,424,507 | <p>If you open a module, that sets the default working directory.</p>
<p>Start IDLE.</p>
<p>File -> Open to open your file. And set the current working directory.</p>
| 1 | 2009-09-15T00:12:10Z | [
"python",
"python-idle"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 1,424,618 | <p>In my case, the default directory is set to the directory from which I launched IDLE. For instance, if I launched IDLE from a directory called 'tmp' in my home directory, the default save path is set to <code>~/tmp</code>. So start your IDLE like this:</p>
<pre><code>~/tmp $ idle
[...]
</code></pre>
| 0 | 2009-09-15T00:56:02Z | [
"python",
"python-idle"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 1,424,722 | <p>On Windows (Vista at least, which is what I'm looking at here), shortcut icons on the desktop have a "Start in" field where you can set the directory used as the current working directory when the program starts. Changing that works for me. Anything like that on the Mac? (Starting in the desired directory from the command line works, too.)</p>
| 1 | 2009-09-15T01:45:37Z | [
"python",
"python-idle"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 1,425,092 | <p>On OS X, if you launch <code>IDLE.app</code> (by double-clicking or using <code>open(1)</code>, for example), the default directory is hardwired to <code>~/Documents</code>. If you want to change the default permanently, you'll need to edit the file <code>idlemain.py</code> within the IDLE.app application bundle; depending on which Python(s) you have installed, it will likely be in one of:</p>
<pre><code>/Applications/MacPython 2.x/IDLE.app/Contents/Resources
/Applications/MacPython 2.x/IDLE.app/Contents/Resources
/Applications/MacPorts/Python 2.x/IDLE.app/Contents/Resources
/Applications/Python 2.x/IDLE.app/Contents/Resources
/Applications/Python 3.x/IDLE.app/Contents/Resources
</code></pre>
<p>Edit the line:</p>
<pre><code>os.chdir(os.path.expanduser('~/Documents'))
</code></pre>
<p>On the other hand, if you start IDLE from the command line, for example, with:</p>
<pre><code>$ cd /some/directory
$ /usr/local/bin/idle
</code></pre>
<p>IDLE will use that current directory as the default.</p>
| 6 | 2009-09-15T04:13:58Z | [
"python",
"python-idle"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 5,161,261 | <p>It seems like you can get idle into the directory you want if you run any module from that directory. </p>
<p>I had previously tried opening idlemain.py through the path browser. I was able to open and edit the file, but it seemed like I wasn't able to save my modifications.</p>
<p>I'm just glad to hear other people are having this problem. I just thought I was being stupid. </p>
| 2 | 2011-03-01T22:37:14Z | [
"python",
"python-idle"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 20,500,218 | <p>I actually just discovered the easiest answer, if you use the shortcut link labeled "IDLE (Python GUI)". This is in Windows Vista, so I don't know if it'll work in other OS's.</p>
<p>1) Right-click "Properties".</p>
<p>2) Select "Shortcut" tab.</p>
<p>3) In "Start In", write file path (e.g. "C:\Users...").</p>
<p>Let me know if this works!</p>
| 2 | 2013-12-10T16:44:46Z | [
"python",
"python-idle"
] |
Default save path for Python IDLE? | 1,424,398 | <p>Does anyone know where or how to set the default path/directory on saving python scripts prior to running? </p>
<p>On a Mac it wants to save them in the top level <code>~/Documents directory</code>. I would like to specify a real location. Any ideas?</p>
| 6 | 2009-09-14T23:28:28Z | 35,376,000 | <p>For OS X:</p>
<p>Open a new finder window,then head over to applications.
Locate your Python application. (For my mac,it's Python 3.5)</p>
<p>Double click on it.
Right click on the IDLE icon,show package contents.
Then go into the contents folder,then resources.</p>
<p><strong>Now,this is the important part:</strong></p>
<p>(Note: You must be the administrator or have the administrator's password for the below to work)</p>
<p>Right click on the idlemain.py,Get Info.</p>
<p>Scroll all the way down. Make sure under the Sharing & Permissions tab,your "name"(Me) is on it with the privilege as Read & Write.
If not click on the lock symbol and unlock it.
Then add/edit yourself to have the Read & Write privilege.</p>
<p>Lastly,as per Ned Deily's instructions,edit the line:</p>
<p>os.chdir(os.path.expanduser('~/Documents'))</p>
<p>with your desired path and then save the changes.</p>
<p>Upon restarting the Python IDLE,you should find that your default Save as path to be the path you've indicated.</p>
| 1 | 2016-02-13T04:14:35Z | [
"python",
"python-idle"
] |
How do scripting languages use sockets? | 1,424,511 | <p>Python, Perl and PHP, all support <a href="http://en.wikipedia.org/wiki/Stream%5Fsocket" rel="nofollow">TCP stream sockets</a>. But exactly how do I use sockets in a script file that is run by a webserver (eg Apache), assuming I only have FTP access and not root access to the machine?</p>
<ol>
<li><p>When a client connects to a specific port, how does the script file get invoked?</p></li>
<li><p>Does the script stay "running" for the duration of the connection? (could be hours)</p></li>
<li><p>So will multiple "instances" of the script be running simultaneously?</p></li>
<li><p>Then how can method calls be made from one instance of the script to another?</p></li>
</ol>
| 1 | 2009-09-15T00:14:40Z | 1,424,517 | <p>Scripting languages utilize sockets exactly the same way as compiled languages.</p>
<p>1) The script typically opens and uses the socket. It's not "run" or "invoked" by the socket, but directly controls it via libraries (typically calling into the native C API for the OS).</p>
<p>2) Yes.</p>
<p>3) Not necessarily. Most modern scripting langauges can handle multiple sockets in one "script" application.</p>
<p>4) N/A, see 3)</p>
<p><hr /></p>
<p>Edit in response to change in question and comments:</p>
<p>This is now obvious that you are trying to run this in the context of a hosted server. Typically, if you're using scripting within Apache or a similar server, things work a bit differently. A socket is opened up and maintained by Apache, and it executes your script, passing the relevant data (POST/GET results, etc.) to your script to process. Sockets usually don't come into play when you're dealing with scripting for CGI, etc.</p>
<p>However, this typically happens using the same concepts as <a href="http://httpd.apache.org/docs/2.0/mod/mod%5Fcgi.html" rel="nofollow">mod_cgi</a>. This pretty much means that the script running is nothing but an executable as far as the server is concerned, and the executable's output is what gets returned to the client. In this case, (provided you have permissions and the correct libraries on the server), your python script can actually launch a separate script that does its own socket work completely outside of Apache's context.</p>
<p>It's (usually) not a good idea to run a full socket implementation directly inside of the CGI script, however. CGI will expect the executable to run to completion before it returns results to the client. Apache will sit there and "hang" a bit waiting for this to complete. If you're launching a full server (especially if it's a long running process, which they tend to be), Apache will think the script is locked, and probably abort, potentially killing the process (configuration specific, but most hosting companies do this to prevent scripts from taking over CPU on a shared system).</p>
<p>However, if you execute a new script from within your script, and then return (shutting down the CGI executable), the other script can be left running, working as a server. This would be something like (python example, using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> library):</p>
<pre><code>newProccess = Popen("python MyScript", shell=True)
</code></pre>
<p>Note that all of the above really depends a bit on server configuration, though. Many hosting companies don't include some of the socket or shell libraries in their scripting implementations specifically to prevent this, so you often have to revert to making the executable in C. In addition, this is often against terms of service for most hosting companies - you'd have to check yours.</p>
| 6 | 2009-09-15T00:17:44Z | [
"php",
"python",
"perl",
"sockets",
"scripting"
] |
How do scripting languages use sockets? | 1,424,511 | <p>Python, Perl and PHP, all support <a href="http://en.wikipedia.org/wiki/Stream%5Fsocket" rel="nofollow">TCP stream sockets</a>. But exactly how do I use sockets in a script file that is run by a webserver (eg Apache), assuming I only have FTP access and not root access to the machine?</p>
<ol>
<li><p>When a client connects to a specific port, how does the script file get invoked?</p></li>
<li><p>Does the script stay "running" for the duration of the connection? (could be hours)</p></li>
<li><p>So will multiple "instances" of the script be running simultaneously?</p></li>
<li><p>Then how can method calls be made from one instance of the script to another?</p></li>
</ol>
| 1 | 2009-09-15T00:14:40Z | 1,424,526 | <p>The only way I can make sense of what you're asking is if you use <a href="http://en.wikipedia.org/wiki/Inetd" rel="nofollow">inetd</a> or a similar meta-server, which is configured to invoke your "service a single client" program for a specific listening port, forwarding your "single client servicer" program's stdin/stdout to the remote client.</p>
<p>If that's the case:</p>
<p>1) inetd runs it</p>
<p>2) yes</p>
<p>3) yes</p>
<p>4) <a href="http://en.wikipedia.org/wiki/Named%5Fpipe" rel="nofollow">named pipes</a> are one possibility</p>
| 1 | 2009-09-15T00:21:29Z | [
"php",
"python",
"perl",
"sockets",
"scripting"
] |
How do scripting languages use sockets? | 1,424,511 | <p>Python, Perl and PHP, all support <a href="http://en.wikipedia.org/wiki/Stream%5Fsocket" rel="nofollow">TCP stream sockets</a>. But exactly how do I use sockets in a script file that is run by a webserver (eg Apache), assuming I only have FTP access and not root access to the machine?</p>
<ol>
<li><p>When a client connects to a specific port, how does the script file get invoked?</p></li>
<li><p>Does the script stay "running" for the duration of the connection? (could be hours)</p></li>
<li><p>So will multiple "instances" of the script be running simultaneously?</p></li>
<li><p>Then how can method calls be made from one instance of the script to another?</p></li>
</ol>
| 1 | 2009-09-15T00:14:40Z | 1,424,574 | <p>As a prior answer notes, scripting languages have operate in this regard in exactly the same way as compiled programs. Where they differ (potentially) is in the API that they use. The operating system (Windows or Unix-based) offers an API (e.g., <a href="http://en.wikipedia.org/wiki/Bsd%5Fsockets" rel="nofollow">BSD sockets</a>) that compiled programs will call directly (typically). Interpreted languages like PHP or Python may offer a different API such as Python's <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket API</a> which may simplify some parts of the underlying API.</p>
<p>Given any of these APIs, there are many ways in which the actual handling of an incoming TCP connection can be structured. A great and detailed overview of such approaches is available on the c10k webpage: <a href="http://www.kegel.com/c10k.html" rel="nofollow">http://www.kegel.com/c10k.html</a> -- in particular, the section on <a href="http://www.kegel.com/c10k.html#strategies" rel="nofollow">IO strategies</a>. In short, the choice of answers to your question is up to the programmer and may affect how the resulting program performs under load.</p>
<p>To focus on your specific questions:</p>
<ol>
<li>Many server programs are started <em>before</em> the connection and are running to listen for incoming connections. A special case is inetd which is a superserver: it listens for connections and then hands off those connections to programs that it starts (specified in a config file).</li>
<li>Typically, yes, the script remains running for the duration of the connection. However, depending on the larger system architecture, the script could conceivably pass the connection off to another program for handling and then exit.</li>
<li>This is a choice, again as enumerated on the <a href="http://www.kegel.com/c10k.html#strategies" rel="nofollow">c10k</a> page.</li>
<li>This is another choice; operating systems offer a variety of <a href="http://en.wikipedia.org/wiki/Inter-process%5Fcommunication" rel="nofollow">Interprocess Communication (IPC)</a> mechanisms to programs.</li>
</ol>
| 2 | 2009-09-15T00:40:24Z | [
"php",
"python",
"perl",
"sockets",
"scripting"
] |
How do scripting languages use sockets? | 1,424,511 | <p>Python, Perl and PHP, all support <a href="http://en.wikipedia.org/wiki/Stream%5Fsocket" rel="nofollow">TCP stream sockets</a>. But exactly how do I use sockets in a script file that is run by a webserver (eg Apache), assuming I only have FTP access and not root access to the machine?</p>
<ol>
<li><p>When a client connects to a specific port, how does the script file get invoked?</p></li>
<li><p>Does the script stay "running" for the duration of the connection? (could be hours)</p></li>
<li><p>So will multiple "instances" of the script be running simultaneously?</p></li>
<li><p>Then how can method calls be made from one instance of the script to another?</p></li>
</ol>
| 1 | 2009-09-15T00:14:40Z | 1,426,746 | <blockquote>
<p>When a client connects to a specific
port, how does the script file get
invoked?</p>
</blockquote>
<p>The script should be already invoked in order to receive any connects from any client. You will need script to be hanging on there forever (infinie loop) and setup Apache not to kill it on timeout. Basically, PHP is not a good choice for writting server applications. Why do you need this?</p>
| 1 | 2009-09-15T12:03:04Z | [
"php",
"python",
"perl",
"sockets",
"scripting"
] |
exposing or hiding objects of dependencies? | 1,424,534 | <p>Common scenario: I have a library that uses other libraries. For example, a math library (let's call it foo) that uses numpy.</p>
<p>Functions of foo can either:</p>
<ul>
<li>return a numpy object (either pure or an inherited reimplementation)</li>
<li>return a list</li>
<li>return a foo-implemented object that behaves like numpy (performing delegation)</li>
</ul>
<p>The three solutions can be also restated as:</p>
<ul>
<li>foo passes through the internally used object, clearly stating that its library dependency is also a API dependency (since it returns objects obeying the interface of the numpy library)</li>
<li>foo makes use of a common subset of objects that are part of the basis of the language.</li>
<li>foo completely hides what it uses internally. Nothing about the underlying libraries escapes from the foo library to the client code.</li>
</ul>
<p>We are of course in a pros-cons scenario. Transparent or opaque? strong coupling with the underlying tools or not? I know the drill but I am in the process of having to do this choice, and I want to share opinions before taking a decision. Suggestions, ideas, personal experience are greatly appreciated.</p>
| 1 | 2009-09-15T00:24:27Z | 1,424,582 | <p>The main question I would think about is how much of your library would return numpy objects? If its pervasive I would go with directly returning a numpy as your so tied to numpy you might as well make it explicit. Plus it will probably make it easier to use other numpy based libraries. If on the other hand you only have a few methods that would return numpy I would either go with the numpy like object or a list, probably the numpy like object.</p>
| 2 | 2009-09-15T00:43:54Z | [
"python",
"design"
] |
exposing or hiding objects of dependencies? | 1,424,534 | <p>Common scenario: I have a library that uses other libraries. For example, a math library (let's call it foo) that uses numpy.</p>
<p>Functions of foo can either:</p>
<ul>
<li>return a numpy object (either pure or an inherited reimplementation)</li>
<li>return a list</li>
<li>return a foo-implemented object that behaves like numpy (performing delegation)</li>
</ul>
<p>The three solutions can be also restated as:</p>
<ul>
<li>foo passes through the internally used object, clearly stating that its library dependency is also a API dependency (since it returns objects obeying the interface of the numpy library)</li>
<li>foo makes use of a common subset of objects that are part of the basis of the language.</li>
<li>foo completely hides what it uses internally. Nothing about the underlying libraries escapes from the foo library to the client code.</li>
</ul>
<p>We are of course in a pros-cons scenario. Transparent or opaque? strong coupling with the underlying tools or not? I know the drill but I am in the process of having to do this choice, and I want to share opinions before taking a decision. Suggestions, ideas, personal experience are greatly appreciated.</p>
| 1 | 2009-09-15T00:24:27Z | 1,424,903 | <p>Since you're talking about return values, that's not really about "internal objects" -- you should just document the interfaces your returned objects will support (it's OK if that's a subset of <code>numpy.array</code> or whatever;-). I recommend against returning a reference to your internal mutable attributes and documenting that mutators work to alter your own object indirectly (and NOT documenting it is not much better) -- that leads to way-too-strong coupling down the road.</p>
<p>If you WERE talking about actual internal objects, I'd recommend the <a href="http://en.wikipedia.org/wiki/Law%5Fof%5FDemeter" rel="nofollow">Law of Demeter</a> -- in a simplistic reading, if the client's coding <code>a.b.c.d.e.f()</code>, then something is very wrong ("just one dot" may be sometimes extreme, but, "four are Right Out"). Again, the problem is strong coupling -- making it impossible for you to change your internal implementation in even minor ways without breaking a million clients...!</p>
| 3 | 2009-09-15T02:56:41Z | [
"python",
"design"
] |
Easy, Robust IPC between Python and PHP | 1,424,593 | <p>I have a python program which starts up a PHP script using the <code>subprocess.Popen()</code> function. The PHP script needs to communicate back-and-forth with Python, and I am trying to find an easy but robust way to manage the message sending/receiving.</p>
<p>I have already written a working protocol using basic sockets, but it doesn't feel very robust - I don't have any logic to handle dropped messages, and I don't even fully understand how sockets work which leaves me uncertain about what else could go wrong.</p>
<p><strong>Are there any generic libraries or IPC frameworks which are easier than raw sockets?</strong></p>
<ul>
<li>ATM I need something which supports Python <em>and</em> PHP, but in the future I may want to be able to use C, Perl and Ruby also.</li>
<li>I am looking for something <em>robust</em>, i.e. when the server or client crashes, the other party needs to be able to recover gracefully.</li>
</ul>
| 0 | 2009-09-15T00:47:39Z | 1,424,687 | <p>You could look at shared memory or named pipes, but I think there are two more likely options, assuming at least one of these languages is being used for a webapp:</p>
<p>A. Use your database's atomicity. In python, begin a transaction, put a message into a table, and end the transaction. From php, begin a transaction, take a message out of the table or mark it "read", and end the transaction. Make your PHP and/or python self-aware enough not to post the same messages twice. Voila; reliable (and scaleable) IPC, using existing web architecture.</p>
<p>B. Make your webserver (assuming as webapp) capable of running both php and python, locking down any internal processes to just localhost access, and then call them using xmlrpc or soap from your other language using standard libraries. This is also scalable, as you can change your URLs and security lock-downs later.</p>
| 0 | 2009-09-15T01:33:18Z | [
"php",
"python",
"ipc"
] |
Easy, Robust IPC between Python and PHP | 1,424,593 | <p>I have a python program which starts up a PHP script using the <code>subprocess.Popen()</code> function. The PHP script needs to communicate back-and-forth with Python, and I am trying to find an easy but robust way to manage the message sending/receiving.</p>
<p>I have already written a working protocol using basic sockets, but it doesn't feel very robust - I don't have any logic to handle dropped messages, and I don't even fully understand how sockets work which leaves me uncertain about what else could go wrong.</p>
<p><strong>Are there any generic libraries or IPC frameworks which are easier than raw sockets?</strong></p>
<ul>
<li>ATM I need something which supports Python <em>and</em> PHP, but in the future I may want to be able to use C, Perl and Ruby also.</li>
<li>I am looking for something <em>robust</em>, i.e. when the server or client crashes, the other party needs to be able to recover gracefully.</li>
</ul>
| 0 | 2009-09-15T00:47:39Z | 1,424,691 | <p>It sounds like you want a generic RPC framework.</p>
<p>You should take a look at:</p>
<ul>
<li>Thrift <a href="http://incubator.apache.org/thrift/" rel="nofollow">http://incubator.apache.org/thrift/</a></li>
<li>XML RPC <a href="http://docs.python.org/library/xmlrpclib.html" rel="nofollow">http://docs.python.org/library/xmlrpclib.html</a> and <a href="http://phpxmlrpc.sourceforge.net/" rel="nofollow">http://phpxmlrpc.sourceforge.net/</a></li>
<li>AMQP e.g. <a href="http://en.wikipedia.org/wiki/Advanced%5FMessage%5FQueuing%5FProtocol" rel="nofollow">http://en.wikipedia.org/wiki/Advanced%5FMessage%5FQueuing%5FProtocol</a></li>
</ul>
<p>Thrift is probably more what you're looking for. It's used by Facebook internally.</p>
| 2 | 2009-09-15T01:35:20Z | [
"php",
"python",
"ipc"
] |
Pad python floats | 1,424,638 | <p>I want to pad some percentage values so that there are always 3 units before the decimal place. With ints I could use '%03d' - is there an equivalent for floats? </p>
<p>'%.3f' works for after the decimal place but '%03f' does nothing.</p>
| 12 | 2009-09-15T01:07:56Z | 1,424,656 | <p>'%03.1f' works (1 could be any number, or empty string):</p>
<pre><code>>>> "%06.2f"%3.3
'003.30'
>>> "%04.f"%3.2
'0003'
</code></pre>
<p>Note that the field width includes the decimal and fractional digits.</p>
| 28 | 2009-09-15T01:18:13Z | [
"python",
"floating-point",
"zero",
"pad"
] |
Pad python floats | 1,424,638 | <p>I want to pad some percentage values so that there are always 3 units before the decimal place. With ints I could use '%03d' - is there an equivalent for floats? </p>
<p>'%.3f' works for after the decimal place but '%03f' does nothing.</p>
| 12 | 2009-09-15T01:07:56Z | 1,424,666 | <p>You could use zfill as well,.</p>
<pre><code>str(3.3).zfill(5)
'003.3'
</code></pre>
| 6 | 2009-09-15T01:21:24Z | [
"python",
"floating-point",
"zero",
"pad"
] |
Turn off Pygame alpha | 1,424,734 | <p>I have a computer game I'm working on, and I'm wanting to give the user an option to turn off alpha compositing for speed purposes. Rather than doing checks everywhere, does Pygame have a global option to say "Don't use alpha" such that it would just ignore all my calls to set_alpha and the likes? </p>
| 1 | 2009-09-15T01:49:17Z | 1,429,443 | <p>Considering the pygame docs I would say <em>"no, there is no global way to disable alpha"</em>.<br />
However there are at least two <em>'local'</em> ways to do it: </p>
<ul>
<li><p>First would be to subclass pygame.Surface and provide your own implementation of set_alpha
which in turn could honor your global alpha settings. </p></li>
<li><p>Second one is a bit more tricky as it depends on the pixel-format in use.
To quote the pygame docs: </p></li>
</ul>
<blockquote>
<p><strong>Surface.set_alpha</strong><br />
<em>set the alpha value for the whole surface</em><br />
<em>[...]</em><br />
This value is different than the per pixel Surface alpha. If the Surface format contains
per pixel alphas, then this alpha value will be ignored. If the Surface contains per pixel
alphas, setting the alpha value to None will disable the per pixel transparency.<br />
<em>[...]</em></p>
</blockquote>
<p>With this you could provide two sets of textures: </p>
<ul>
<li>one with an opaque (per-pixel) alpha channel which will overwrite all your calls to <strong>*set_alpha()*</strong></li>
<li>one which has no per-pixel alpha and thus will honor your <strong>*set_alpha()*</strong></li>
</ul>
<p>Hope this will help!</p>
| 1 | 2009-09-15T20:29:25Z | [
"python",
"pygame",
"alphablending"
] |
Turn off Pygame alpha | 1,424,734 | <p>I have a computer game I'm working on, and I'm wanting to give the user an option to turn off alpha compositing for speed purposes. Rather than doing checks everywhere, does Pygame have a global option to say "Don't use alpha" such that it would just ignore all my calls to set_alpha and the likes? </p>
| 1 | 2009-09-15T01:49:17Z | 15,567,788 | <p>I have read that the convert()-function disables image's alpha.
What I know is: </p>
<p>Using the convert()-function speeds up blitting the image for screen-big images on my computer to around 150 FPS with a colour depth of 16 bit.</p>
<pre><code>image = image.convert()#video system has to be initialed
</code></pre>
| 0 | 2013-03-22T10:15:10Z | [
"python",
"pygame",
"alphablending"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 1,425,056 | <p>I believe xmpp implementation is one which is being use by a lot of big companies but the common thing is to use a comet server as well.</p>
<p>a lot of implementation in python for thoses you can google around.</p>
| 1 | 2009-09-15T03:57:08Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 1,425,061 | <p>How about <a href="http://orbited.org" rel="nofollow">Orbited</a>, it's very good and being used by <a href="http://echowaves.com" rel="nofollow">Echowaves</a></p>
| 3 | 2009-09-15T03:58:23Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 1,425,072 | <p>I'm using Orbited right now, it's great!</p>
<p>If you are doing chat or subscription type stuff use <code>stompservice</code> and orbited.</p>
<p>If you are doing 1 to 1 client mapping use <code>TCPSocket</code>.</p>
<p>I can give you some code examples if you want.</p>
| 3 | 2009-09-15T04:05:21Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 1,425,078 | <p>Comet is the protocol you want. What Comet implementation is best, is a harder call.</p>
<p>If you're OK with Java (or, I guess, Jython), or .NET (where IronPython's a possibility), I suspect (<em>not</em> having extensively tried them all!-) that <a href="http://www.stream-hub.com/" rel="nofollow">stream hub</a> must be a major contender. It'a typical "freemium" product -- you can get a free ("as in free beer";-) version, or you can try the pricey Web Edition, or the even-pricier Enterprise Edition; feature comparison is <a href="http://www.stream-hub.com/features.html" rel="nofollow">here</a> (e.g., free edition: no https, no more than 10 concurrent users, no .NET).</p>
| 3 | 2009-09-15T04:07:12Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 1,425,133 | <p>What about <a href="http://www.ape-project.org/" rel="nofollow">Ajax Push Engine</a>? </p>
| 2 | 2009-09-15T04:36:15Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 1,507,086 | <p>Have you tried <a href="http://www.stream-hub.com/" rel="nofollow">StreamHub Push Server</a>?</p>
| 0 | 2009-10-01T23:49:12Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 2,037,689 | <p>I'm personally biased, but I like <a href="http://www.frozenmountain.com/websync" rel="nofollow">WebSync, for IIS/.NET</a>. It integrates with IIS, so no other server software necessary, just a dll to add to your project.</p>
| 2 | 2010-01-10T16:51:04Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Implementing Server Push | 1,425,048 | <p>Read about Server push <a href="http://en.wikipedia.org/wiki/Push%5Ftechnology">here</a>.<br />
I want to push data to client from my web application in real time.<br />
I was looking at TCP sockets as one of the options.<br />
For HTTP I found a variety of frameworks for Java, PHP, Python and others over <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks">here</a>.
However I don't know whether any of these support Push. </p>
<ul>
<li>What options and frameworks would you
suggest for implementing Server push?</li>
<li>What language would you advocate for implementing the same and why?</li>
</ul>
| 6 | 2009-09-15T03:54:17Z | 3,756,542 | <p>Ok, I'm using ASP.NET with <a href="http://pokein.com" rel="nofollow">PokeIn</a> comet ajax library on my project. Also, I tried <a href="https://atmosphere.dev.java.net/" rel="nofollow">Atmosphere</a> under JAVA.. My last choice was PokeIn.. Because, only server push support is not solving the problems. You will need some kind of client to server object serialization and object life time management. PokeIn covered all these needs for me.</p>
| 3 | 2010-09-21T00:42:01Z | [
"java",
"php",
"python",
"ruby",
"server-push"
] |
Reverse Geocoding Without Web Access | 1,425,149 | <p>I am working on an application where one of the requirements is that I be able to perform realtime reverse geocoding operations based on GPS data. In particular, I must be able to determine the state/province to which a latitude, longitude pair maps and detect when we have moved from one state/province to another.</p>
<p>I have a couple ideas so far but wondered if anyone had any ideas on either of the following:</p>
<ul>
<li>What is the best approach for tackling this problem in an efficient manner?</li>
<li>Where is a good place to find and what is the appropriate format for North American state/province boundaries</li>
</ul>
<p>As a starter, here are the two main ideas I have:</p>
<ol>
<li>Break North America into a grid with each rectangle in the grid mapping to a particular state province. Do a lookup on this table (which grows quickly the more precise you would like to be) based on the latitude and then the longitude (or vice versa).</li>
<li>Define polygons for each of the states and do some sort of calculation to determine in which polygon a lat/lon pair lies. I am not sure exactly how to go about this. HTML image maps come to mind as one way of defining the bounds for a state/province.</li>
</ol>
<p>I am working in python for the interested or those that might have a nice library they would like to suggest.</p>
<p><strong>To be clear... I do not have web access available to me, so using an existing reverse geocoding service is not an option at runtime</strong></p>
| 7 | 2009-09-15T04:42:17Z | 1,425,312 | <p>I have a database with all of this data and some access tools. I made mine from the census tiger data. I imagine it'd basically be an export of my database to sqlite and a bit of code translation.</p>
| 0 | 2009-09-15T05:38:49Z | [
"python",
"gps",
"geocoding",
"reverse-geocoding"
] |
Reverse Geocoding Without Web Access | 1,425,149 | <p>I am working on an application where one of the requirements is that I be able to perform realtime reverse geocoding operations based on GPS data. In particular, I must be able to determine the state/province to which a latitude, longitude pair maps and detect when we have moved from one state/province to another.</p>
<p>I have a couple ideas so far but wondered if anyone had any ideas on either of the following:</p>
<ul>
<li>What is the best approach for tackling this problem in an efficient manner?</li>
<li>Where is a good place to find and what is the appropriate format for North American state/province boundaries</li>
</ul>
<p>As a starter, here are the two main ideas I have:</p>
<ol>
<li>Break North America into a grid with each rectangle in the grid mapping to a particular state province. Do a lookup on this table (which grows quickly the more precise you would like to be) based on the latitude and then the longitude (or vice versa).</li>
<li>Define polygons for each of the states and do some sort of calculation to determine in which polygon a lat/lon pair lies. I am not sure exactly how to go about this. HTML image maps come to mind as one way of defining the bounds for a state/province.</li>
</ol>
<p>I am working in python for the interested or those that might have a nice library they would like to suggest.</p>
<p><strong>To be clear... I do not have web access available to me, so using an existing reverse geocoding service is not an option at runtime</strong></p>
| 7 | 2009-09-15T04:42:17Z | 1,425,330 | <p>I would stay away from implementing your own solution from scratch. This is a pretty big undertaking and there are already tools out there to do this. If you're looking for an open source approach (read: free), take a look at this blog post: <a href="http://www.macgeekery.com/hacks/software/using%5Fpostgis%5Freverse%5Fgeocode" rel="nofollow">Using PostGIS to Reverse Geocode</a>.</p>
| 4 | 2009-09-15T05:45:16Z | [
"python",
"gps",
"geocoding",
"reverse-geocoding"
] |
Reverse Geocoding Without Web Access | 1,425,149 | <p>I am working on an application where one of the requirements is that I be able to perform realtime reverse geocoding operations based on GPS data. In particular, I must be able to determine the state/province to which a latitude, longitude pair maps and detect when we have moved from one state/province to another.</p>
<p>I have a couple ideas so far but wondered if anyone had any ideas on either of the following:</p>
<ul>
<li>What is the best approach for tackling this problem in an efficient manner?</li>
<li>Where is a good place to find and what is the appropriate format for North American state/province boundaries</li>
</ul>
<p>As a starter, here are the two main ideas I have:</p>
<ol>
<li>Break North America into a grid with each rectangle in the grid mapping to a particular state province. Do a lookup on this table (which grows quickly the more precise you would like to be) based on the latitude and then the longitude (or vice versa).</li>
<li>Define polygons for each of the states and do some sort of calculation to determine in which polygon a lat/lon pair lies. I am not sure exactly how to go about this. HTML image maps come to mind as one way of defining the bounds for a state/province.</li>
</ol>
<p>I am working in python for the interested or those that might have a nice library they would like to suggest.</p>
<p><strong>To be clear... I do not have web access available to me, so using an existing reverse geocoding service is not an option at runtime</strong></p>
| 7 | 2009-09-15T04:42:17Z | 1,425,334 | <p>I suggest using a variant of your first idea: Use a <a href="http://en.wikipedia.org/wiki/Spatial%5Findex">spatial index</a>. A spatial index is a data structure built from rectangles, mapping lat/long to the payload. In this case you will probably map rectangles to state-province pairs. An <a href="http://en.wikipedia.org/wiki/R-tree">R-tree</a> may be a good option. Here's an <a href="http://pypi.python.org/pypi/Rtree/">R-tree python package</a>. You could detect roaming by comparing the results of consecutive searches.</p>
| 6 | 2009-09-15T05:46:24Z | [
"python",
"gps",
"geocoding",
"reverse-geocoding"
] |
Reverse Geocoding Without Web Access | 1,425,149 | <p>I am working on an application where one of the requirements is that I be able to perform realtime reverse geocoding operations based on GPS data. In particular, I must be able to determine the state/province to which a latitude, longitude pair maps and detect when we have moved from one state/province to another.</p>
<p>I have a couple ideas so far but wondered if anyone had any ideas on either of the following:</p>
<ul>
<li>What is the best approach for tackling this problem in an efficient manner?</li>
<li>Where is a good place to find and what is the appropriate format for North American state/province boundaries</li>
</ul>
<p>As a starter, here are the two main ideas I have:</p>
<ol>
<li>Break North America into a grid with each rectangle in the grid mapping to a particular state province. Do a lookup on this table (which grows quickly the more precise you would like to be) based on the latitude and then the longitude (or vice versa).</li>
<li>Define polygons for each of the states and do some sort of calculation to determine in which polygon a lat/lon pair lies. I am not sure exactly how to go about this. HTML image maps come to mind as one way of defining the bounds for a state/province.</li>
</ol>
<p>I am working in python for the interested or those that might have a nice library they would like to suggest.</p>
<p><strong>To be clear... I do not have web access available to me, so using an existing reverse geocoding service is not an option at runtime</strong></p>
| 7 | 2009-09-15T04:42:17Z | 1,425,355 | <p>If you can get hold of state boundaries as polygons (for example, via OpenStreetMap), determining the current state is just a point-in-polygon test. </p>
<p>If you need address data, an offline solution would be to use Microsoft Mappoint. </p>
| 1 | 2009-09-15T05:53:00Z | [
"python",
"gps",
"geocoding",
"reverse-geocoding"
] |
Reverse Geocoding Without Web Access | 1,425,149 | <p>I am working on an application where one of the requirements is that I be able to perform realtime reverse geocoding operations based on GPS data. In particular, I must be able to determine the state/province to which a latitude, longitude pair maps and detect when we have moved from one state/province to another.</p>
<p>I have a couple ideas so far but wondered if anyone had any ideas on either of the following:</p>
<ul>
<li>What is the best approach for tackling this problem in an efficient manner?</li>
<li>Where is a good place to find and what is the appropriate format for North American state/province boundaries</li>
</ul>
<p>As a starter, here are the two main ideas I have:</p>
<ol>
<li>Break North America into a grid with each rectangle in the grid mapping to a particular state province. Do a lookup on this table (which grows quickly the more precise you would like to be) based on the latitude and then the longitude (or vice versa).</li>
<li>Define polygons for each of the states and do some sort of calculation to determine in which polygon a lat/lon pair lies. I am not sure exactly how to go about this. HTML image maps come to mind as one way of defining the bounds for a state/province.</li>
</ol>
<p>I am working in python for the interested or those that might have a nice library they would like to suggest.</p>
<p><strong>To be clear... I do not have web access available to me, so using an existing reverse geocoding service is not an option at runtime</strong></p>
| 7 | 2009-09-15T04:42:17Z | 1,591,032 | <p>You can get data for the entire united states from <a href="http://www.openstreetmap.org/" rel="nofollow">open street map</a> You could then extract the data you need such as city or state locations into what ever format works best for your application. Note although data quality is good it isn't guaranteed to be completely accurate so if you need complete accuracy you may have to look somewhere else.</p>
| 1 | 2009-10-19T20:43:17Z | [
"python",
"gps",
"geocoding",
"reverse-geocoding"
] |
Reverse Geocoding Without Web Access | 1,425,149 | <p>I am working on an application where one of the requirements is that I be able to perform realtime reverse geocoding operations based on GPS data. In particular, I must be able to determine the state/province to which a latitude, longitude pair maps and detect when we have moved from one state/province to another.</p>
<p>I have a couple ideas so far but wondered if anyone had any ideas on either of the following:</p>
<ul>
<li>What is the best approach for tackling this problem in an efficient manner?</li>
<li>Where is a good place to find and what is the appropriate format for North American state/province boundaries</li>
</ul>
<p>As a starter, here are the two main ideas I have:</p>
<ol>
<li>Break North America into a grid with each rectangle in the grid mapping to a particular state province. Do a lookup on this table (which grows quickly the more precise you would like to be) based on the latitude and then the longitude (or vice versa).</li>
<li>Define polygons for each of the states and do some sort of calculation to determine in which polygon a lat/lon pair lies. I am not sure exactly how to go about this. HTML image maps come to mind as one way of defining the bounds for a state/province.</li>
</ol>
<p>I am working in python for the interested or those that might have a nice library they would like to suggest.</p>
<p><strong>To be clear... I do not have web access available to me, so using an existing reverse geocoding service is not an option at runtime</strong></p>
| 7 | 2009-09-15T04:42:17Z | 24,887,665 | <p>I created an offline reverse geocoding module for countries: <a href="https://bitbucket.org/richardpenman/reverse_geocode" rel="nofollow">https://bitbucket.org/richardpenman/reverse_geocode</a></p>
<pre><code>>>> import reverse_geocode
>>> coordinates = (-37.81, 144.96), (31.76, 35.21)
>>> reverse_geocode.search(coordinates)
[{'city': 'Melbourne', 'code': 'AU', 'country': 'Australia'},
{'city': 'Jerusalem', 'code': 'IL', 'country': 'Israel'}]
</code></pre>
<p>I will see if I can add data for states.</p>
| 2 | 2014-07-22T12:38:55Z | [
"python",
"gps",
"geocoding",
"reverse-geocoding"
] |
Symmetrically adressable matrix | 1,425,162 | <p>I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?</p>
| 1 | 2009-09-15T04:48:36Z | 1,425,181 | <p>You only need to store the lower triangle of the matrix. Typically this is done with one n(n+1)/2 length list. You'll need to overload the <code>__getitem__</code> method to interpret what the entry means.</p>
| 1 | 2009-09-15T04:55:10Z | [
"python",
"data-structures",
"matrix"
] |
Symmetrically adressable matrix | 1,425,162 | <p>I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?</p>
| 1 | 2009-09-15T04:48:36Z | 1,425,298 | <p>Golub and Van Loan's "Matrix Computations" book outlines a feasible addressing scheme:</p>
<p>You pack the data in to a vector and access as follows, assuming i >= j:</p>
<pre><code>a_ij = A.vec((j-1)n - j(j-1)/2 + i)
</code></pre>
| 3 | 2009-09-15T05:34:22Z | [
"python",
"data-structures",
"matrix"
] |
Symmetrically adressable matrix | 1,425,162 | <p>I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?</p>
| 1 | 2009-09-15T04:48:36Z | 1,425,305 | <p>You're probably better off using a full square numpy matrix. Yes, it wastes half the memory storing redundant values, but rolling your own symmetric matrix in Python will waste even more memory and CPU by storing and processing the integers as Python objects. </p>
| 2 | 2009-09-15T05:36:33Z | [
"python",
"data-structures",
"matrix"
] |
Symmetrically adressable matrix | 1,425,162 | <p>I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?</p>
| 1 | 2009-09-15T04:48:36Z | 1,430,312 | <p>A simpler and cleaner way is to just use a dictionary with sorted tuples as keys. The tuples correspond with your matrix index. Override <code>__getitem__</code> and <code>__setitem__</code> to access the dictionary by sorted tuples; here's an example class:</p>
<pre><code>class Matrix(dict):
def __getitem__(self, index):
return super(Matrix, self).__getitem__(tuple(sorted(index)))
def __setitem__(self, index, value):
return super(Matrix, self).__setitem__(tuple(sorted(index)), value)
</code></pre>
<p>And then use it like this:</p>
<pre><code>>>> matrix = Matrix()
>>> matrix[2,3] = 1066
>>> print matrix
{(2, 3): 1066}
>>> matrix[2,3]
1066
>>> matrix[3,2]
1066
>>> matrix[1,1]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "z.py", line 3, in __getitem__
return super(Matrix, self).__getitem__(tuple(sorted(index)))
KeyError: (1, 1)
</code></pre>
| 1 | 2009-09-16T00:33:48Z | [
"python",
"data-structures",
"matrix"
] |
PHP equivalent for a python decorator? | 1,425,303 | <p>I want to be able to wrap a PHP function by another function, but leaving its original name/parameter list intact.</p>
<p>For instance:</p>
<pre><code>function A() {
print "inside A()\n";
}
function Wrap_A() {
print "Calling A()\n";
A();
print "Finished calling A()\n";
}
// <--- Do some magic here (effectively "A = Wrap_A")
A();
</code></pre>
<p>Output:</p>
<pre><code>Calling A()
inside A()
Finished calling A()
</code></pre>
| 7 | 2009-09-15T05:36:03Z | 1,425,364 | <p>maybe youâre looking for <a href="http://php.net/call%5Fuser%5Ffunc%5Farray" rel="nofollow"><code>call_user_func_array</code></a>:</p>
<pre><code>function wrapA() {
$args = func_get_args();
return call_user_func_array('A', $args);
}
</code></pre>
<p>since PHP 5.3 you could even say:</p>
<pre><code>return call_user_func_array('A', func_get_args());
</code></pre>
<p><hr /></p>
<p>after youâve edited your question i would say, no, this is not possible, but there are some ways, see this question: <a href="http://stackoverflow.com/questions/948443/how-to-implement-a-decorator-in-php">http://stackoverflow.com/questions/948443/how-to-implement-a-decorator-in-php</a></p>
| 1 | 2009-09-15T05:54:06Z | [
"php",
"python",
"function",
"decorator",
"wrapper"
] |
PHP equivalent for a python decorator? | 1,425,303 | <p>I want to be able to wrap a PHP function by another function, but leaving its original name/parameter list intact.</p>
<p>For instance:</p>
<pre><code>function A() {
print "inside A()\n";
}
function Wrap_A() {
print "Calling A()\n";
A();
print "Finished calling A()\n";
}
// <--- Do some magic here (effectively "A = Wrap_A")
A();
</code></pre>
<p>Output:</p>
<pre><code>Calling A()
inside A()
Finished calling A()
</code></pre>
| 7 | 2009-09-15T05:36:03Z | 1,425,417 | <p>You can't do this with functions in PHP. In other dynamic languages, such as Perl and Ruby, you can redefine previously defined functions, but PHP throws a fatal error when you attempt to do so.</p>
<p>In 5.3, you can create an <a href="http://us2.php.net/manual/en/functions.anonymous.php" rel="nofollow">anonymous function</a> and store it in a variable:</p>
<pre><code><?php
$my_function = function($args, ...) { ... };
$copy_of_my_function = $my_function;
$my_function = function($arg, ...) { /* Do something with the copy */ };
?>
</code></pre>
<p>Alternatively, you can use the traditional decorator pattern and/or a factory and work with classes instead.</p>
| 1 | 2009-09-15T06:11:10Z | [
"php",
"python",
"function",
"decorator",
"wrapper"
] |
PHP equivalent for a python decorator? | 1,425,303 | <p>I want to be able to wrap a PHP function by another function, but leaving its original name/parameter list intact.</p>
<p>For instance:</p>
<pre><code>function A() {
print "inside A()\n";
}
function Wrap_A() {
print "Calling A()\n";
A();
print "Finished calling A()\n";
}
// <--- Do some magic here (effectively "A = Wrap_A")
A();
</code></pre>
<p>Output:</p>
<pre><code>Calling A()
inside A()
Finished calling A()
</code></pre>
| 7 | 2009-09-15T05:36:03Z | 1,425,420 | <p>Apparently <a href="http://php.net/runkit">runkit</a> might <a href="http://php.net/manual/en/function.runkit-function-redefine.php">help you</a>.</p>
<p>Also, you can always do this the OO way. Put the original fun in a class, and the decorator into an extended class. Instantiate and go.</p>
| 6 | 2009-09-15T06:12:14Z | [
"php",
"python",
"function",
"decorator",
"wrapper"
] |
PHP equivalent for a python decorator? | 1,425,303 | <p>I want to be able to wrap a PHP function by another function, but leaving its original name/parameter list intact.</p>
<p>For instance:</p>
<pre><code>function A() {
print "inside A()\n";
}
function Wrap_A() {
print "Calling A()\n";
A();
print "Finished calling A()\n";
}
// <--- Do some magic here (effectively "A = Wrap_A")
A();
</code></pre>
<p>Output:</p>
<pre><code>Calling A()
inside A()
Finished calling A()
</code></pre>
| 7 | 2009-09-15T05:36:03Z | 34,095,650 | <p>Here is my method of mimicking decorators from python in php.</p>
<pre><code>function call_decorator ($decorator, $function, $args, $kwargs) {
// Call the decorator and pass the function to it
$decorator($function, $args, $kwargs);
}
function testing ($args, $kwargs) {
echo PHP_EOL . 'test 1234' . PHP_EOL;
}
function wrap_testing ($func, $args, $kwargs) {
// Before call on passed function
echo 'Before testing';
// Call the passed function
$func($args, $kwargs);
// After call on passed function
echo 'After testing';
}
// Run test
call_decorator('wrap_testing', 'testing');
</code></pre>
<p>Output:</p>
<pre><code>Before testing
testing 1234
After testing
</code></pre>
<p>With this implementation you can also do something like this with an anonymous function:</p>
<pre><code>// Run new test
call_decorator('wrap_testing', function($args, $kwargs) {
echo PHP_EOL . 'Hello!' . PHP_EOL;
});
</code></pre>
<p>Output:</p>
<pre><code>Before testing
Hello!
After testing
</code></pre>
<p>And lastly you can even do something like this, if you are so inclined.</p>
<pre><code>// Run test
call_decorator(function ($func, $args, $kwargs) {
echo 'Hello ';
$func($args, $kwargs);
}, function($args, $kwargs) {
echo 'World!';
});
</code></pre>
<p>Output:</p>
<pre><code>Hello World!
</code></pre>
<p>With this construction above, you can pass variables to the inner function or wrapper, if need be. Here is that implementation with an anonymous inner function:</p>
<pre><code>$test_val = 'I am accessible!';
call_decorator('wrap_testing', function($args, $kwargs){
echo $args[0];
}, array($test_val));
</code></pre>
<p>It will work exactly the same without an anonymous function:</p>
<pre><code>function test ($args, $kwargs) {
echo $kwargs['test'];
}
$test_var = 'Hello again!';
call_decorator('wrap_testing', 'test', array(), array('test' => $test_var));
</code></pre>
<p>Lastly, if you need to modify the variable inside either the wrapper or the wrappie, you just need to pass the variable by reference.</p>
<p>Without reference: </p>
<pre><code>$test_var = 'testing this';
call_decorator(function($func, $args, $kwargs) {
$func($args, $kwargs);
}, function($args, $kwargs) {
$args[0] = 'I changed!';
}, array($test_var));
</code></pre>
<p>Output:</p>
<pre><code>testing this
</code></pre>
<p>With reference:</p>
<pre><code>$test_var = 'testing this';
call_decorator(function($func, $args, $kwargs) {
$func($args, $kwargs);
}, function($args, $kwargs) {
$args[0] = 'I changed!';
// Reference the variable here
}, array(&$test_var));
</code></pre>
<p>Output:</p>
<pre><code>I changed!
</code></pre>
<p>That is all I have for now, it is a pretty useful in a lot of cases, and you can even wrap them multiple times if you want to.</p>
| 1 | 2015-12-04T19:04:29Z | [
"php",
"python",
"function",
"decorator",
"wrapper"
] |
Reverse engineer SQLAlchemy declarative class definition from existing MySQL database? | 1,425,412 | <p>I have a pre-existing mysql database containing around 50 tables.</p>
<p>Rather than hand code a declarative style SqlAlchemy class (<a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively">as shown here</a>) for each table, is there a tool/script/command I can run against the mysql database that will <em>generate</em> a python class in the declarative style for each table in the database?</p>
<p>To take just one table as an example (would generate for all 50 ideally) as follows:</p>
<pre><code>+---------+--------------------+
| dept_no | dept_name |
+---------+--------------------+
| d009 | Customer Service |
| d005 | Development |
| d002 | Finance |
| d003 | Human Resources |
| d001 | Marketing |
| d004 | Production |
| d006 | Quality Management |
| d008 | Research |
| d007 | Sales |
+---------+--------------------+
</code></pre>
<p>Is there a tool/script/command that can generate a text file containing something like:</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
__tablename__ = 'departments'
dept_no = Column(String(5), primary_key=True)
dept_name = Column(String(50))
def __init__(self, dept_no, dept_name):
self.dept_no = dept_no
self.dept_name = dept_name
def __repr__(self):
return "<Department('%s','%s')>" % (self.dept_no, self.dept_name)
</code></pre>
| 20 | 2009-09-15T06:09:40Z | 1,425,452 | <p><a href="http://www.sqlalchemy.org/trac/wiki/SqlSoup" rel="nofollow">SqlSoup</a> can perform introspective mapping of an existing SQL schema.</p>
| 4 | 2009-09-15T06:24:43Z | [
"python",
"mysql",
"sqlalchemy"
] |
Reverse engineer SQLAlchemy declarative class definition from existing MySQL database? | 1,425,412 | <p>I have a pre-existing mysql database containing around 50 tables.</p>
<p>Rather than hand code a declarative style SqlAlchemy class (<a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively">as shown here</a>) for each table, is there a tool/script/command I can run against the mysql database that will <em>generate</em> a python class in the declarative style for each table in the database?</p>
<p>To take just one table as an example (would generate for all 50 ideally) as follows:</p>
<pre><code>+---------+--------------------+
| dept_no | dept_name |
+---------+--------------------+
| d009 | Customer Service |
| d005 | Development |
| d002 | Finance |
| d003 | Human Resources |
| d001 | Marketing |
| d004 | Production |
| d006 | Quality Management |
| d008 | Research |
| d007 | Sales |
+---------+--------------------+
</code></pre>
<p>Is there a tool/script/command that can generate a text file containing something like:</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
__tablename__ = 'departments'
dept_no = Column(String(5), primary_key=True)
dept_name = Column(String(50))
def __init__(self, dept_no, dept_name):
self.dept_no = dept_no
self.dept_name = dept_name
def __repr__(self):
return "<Department('%s','%s')>" % (self.dept_no, self.dept_name)
</code></pre>
| 20 | 2009-09-15T06:09:40Z | 1,426,387 | <p>use <a href="http://code.google.com/p/sqlautocode/">sqlautocode</a>:</p>
<p>It is a flexible tool to autogenerate a model from an existing database.</p>
<p>This is a slightly different approach to <a href="http://www.sqlalchemy.org/trac/wiki/SqlSoup">SqlSoup</a>, which lets you use tables without explicitly defining them. On the other hand, sqlalutocode will generate actual python code.</p>
| 27 | 2009-09-15T10:42:34Z | [
"python",
"mysql",
"sqlalchemy"
] |
Reverse engineer SQLAlchemy declarative class definition from existing MySQL database? | 1,425,412 | <p>I have a pre-existing mysql database containing around 50 tables.</p>
<p>Rather than hand code a declarative style SqlAlchemy class (<a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively">as shown here</a>) for each table, is there a tool/script/command I can run against the mysql database that will <em>generate</em> a python class in the declarative style for each table in the database?</p>
<p>To take just one table as an example (would generate for all 50 ideally) as follows:</p>
<pre><code>+---------+--------------------+
| dept_no | dept_name |
+---------+--------------------+
| d009 | Customer Service |
| d005 | Development |
| d002 | Finance |
| d003 | Human Resources |
| d001 | Marketing |
| d004 | Production |
| d006 | Quality Management |
| d008 | Research |
| d007 | Sales |
+---------+--------------------+
</code></pre>
<p>Is there a tool/script/command that can generate a text file containing something like:</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
__tablename__ = 'departments'
dept_no = Column(String(5), primary_key=True)
dept_name = Column(String(50))
def __init__(self, dept_no, dept_name):
self.dept_no = dept_no
self.dept_name = dept_name
def __repr__(self):
return "<Department('%s','%s')>" % (self.dept_no, self.dept_name)
</code></pre>
| 20 | 2009-09-15T06:09:40Z | 1,429,686 | <p>Keep in mind declarative can be used with reflected tables. So if startup time weren't a huge issue you could do this:</p>
<pre><code>engine = create_engine('mysql://...')
meta = MetaData()
meta.reflect(bind=engine)
for table in meta.tables.values():
print """
class %s(Base):
__table__ = Table(%r, Base.metadata, autoload=True)
""" % (table.name, table.name)
</code></pre>
<p>other than that autocode is probably the way to go. </p>
| 6 | 2009-09-15T21:20:53Z | [
"python",
"mysql",
"sqlalchemy"
] |
Reverse engineer SQLAlchemy declarative class definition from existing MySQL database? | 1,425,412 | <p>I have a pre-existing mysql database containing around 50 tables.</p>
<p>Rather than hand code a declarative style SqlAlchemy class (<a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively">as shown here</a>) for each table, is there a tool/script/command I can run against the mysql database that will <em>generate</em> a python class in the declarative style for each table in the database?</p>
<p>To take just one table as an example (would generate for all 50 ideally) as follows:</p>
<pre><code>+---------+--------------------+
| dept_no | dept_name |
+---------+--------------------+
| d009 | Customer Service |
| d005 | Development |
| d002 | Finance |
| d003 | Human Resources |
| d001 | Marketing |
| d004 | Production |
| d006 | Quality Management |
| d008 | Research |
| d007 | Sales |
+---------+--------------------+
</code></pre>
<p>Is there a tool/script/command that can generate a text file containing something like:</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
__tablename__ = 'departments'
dept_no = Column(String(5), primary_key=True)
dept_name = Column(String(50))
def __init__(self, dept_no, dept_name):
self.dept_no = dept_no
self.dept_name = dept_name
def __repr__(self):
return "<Department('%s','%s')>" % (self.dept_no, self.dept_name)
</code></pre>
| 20 | 2009-09-15T06:09:40Z | 28,328,981 | <p>Now (in 2015) you probably would want to use <a href="https://pypi.python.org/pypi/sqlacodegen" rel="nofollow">https://pypi.python.org/pypi/sqlacodegen</a> instead!</p>
| 4 | 2015-02-04T18:43:36Z | [
"python",
"mysql",
"sqlalchemy"
] |
Method assignment and objects | 1,425,414 | <p>i've got a problem with python:
I want to assign a method to an object form another class, but in this method use its own attributes. Since i have many container with different use methods in my project (not in that example) i dont want to use inheritance, thad would force me to create a custom class for each instance. </p>
<pre><code>class container():
def __init__(self):
self.info = "undefiend info attribute"
def use(self):
print self.info
class tree():
def __init__(self):
# create container instance
b = container()
# change b's info attribute
b.info = "b's info attribute"
# bound method test is set as use of b and in this case unbound, i think
b.use = self.test
# should read b's info attribute and print it
# should output: test: b's info attribute but test is bound in some way to the tree object
print b.use()
# bound method test
def test(self):
return "test: "+self.info
if __name__ == "__main__":
b = tree()
</code></pre>
<p>Thank you very much for reading this, and perhaps helping me! :)</p>
| 3 | 2009-09-15T06:09:52Z | 1,425,472 | <p>Looks like you are trying to use inheritance? The tree inherits from the container?</p>
| 1 | 2009-09-15T06:34:44Z | [
"python"
] |
Method assignment and objects | 1,425,414 | <p>i've got a problem with python:
I want to assign a method to an object form another class, but in this method use its own attributes. Since i have many container with different use methods in my project (not in that example) i dont want to use inheritance, thad would force me to create a custom class for each instance. </p>
<pre><code>class container():
def __init__(self):
self.info = "undefiend info attribute"
def use(self):
print self.info
class tree():
def __init__(self):
# create container instance
b = container()
# change b's info attribute
b.info = "b's info attribute"
# bound method test is set as use of b and in this case unbound, i think
b.use = self.test
# should read b's info attribute and print it
# should output: test: b's info attribute but test is bound in some way to the tree object
print b.use()
# bound method test
def test(self):
return "test: "+self.info
if __name__ == "__main__":
b = tree()
</code></pre>
<p>Thank you very much for reading this, and perhaps helping me! :)</p>
| 3 | 2009-09-15T06:09:52Z | 1,425,475 | <p>Here you go. You should know that self.test is already bound since by the time you are in __init__ the instance has already been created and its methods are bound. Therefore you must access the unbound member by using the im_func member, and binding it with MethodType.</p>
<pre><code>import types
class container():
def __init__(self):
self.info = "undefiend info attribute"
def use(self):
print self.info
class tree():
def __init__(self):
# create container instance
b = container()
# change b's info attribute
b.info = "b's info attribute"
# bound method test is set as use of b and in this case unbound, i think
b.use = types.MethodType(self.test.im_func, b, b.__class__)
# should read b's info attribute and print it
# should output: test: b's info attribute but test is bound in some way to the tree object
print b.use()
# bound method test
def test(self):
return "test: "+self.info
if __name__ == "__main__":
b = tree()
</code></pre>
| 2 | 2009-09-15T06:35:42Z | [
"python"
] |
Method assignment and objects | 1,425,414 | <p>i've got a problem with python:
I want to assign a method to an object form another class, but in this method use its own attributes. Since i have many container with different use methods in my project (not in that example) i dont want to use inheritance, thad would force me to create a custom class for each instance. </p>
<pre><code>class container():
def __init__(self):
self.info = "undefiend info attribute"
def use(self):
print self.info
class tree():
def __init__(self):
# create container instance
b = container()
# change b's info attribute
b.info = "b's info attribute"
# bound method test is set as use of b and in this case unbound, i think
b.use = self.test
# should read b's info attribute and print it
# should output: test: b's info attribute but test is bound in some way to the tree object
print b.use()
# bound method test
def test(self):
return "test: "+self.info
if __name__ == "__main__":
b = tree()
</code></pre>
<p>Thank you very much for reading this, and perhaps helping me! :)</p>
| 3 | 2009-09-15T06:09:52Z | 1,425,478 | <p>Use tree.test instead of self.test. The method attributes of an instance are bound to that instance.</p>
| 1 | 2009-09-15T06:35:52Z | [
"python"
] |
Method assignment and objects | 1,425,414 | <p>i've got a problem with python:
I want to assign a method to an object form another class, but in this method use its own attributes. Since i have many container with different use methods in my project (not in that example) i dont want to use inheritance, thad would force me to create a custom class for each instance. </p>
<pre><code>class container():
def __init__(self):
self.info = "undefiend info attribute"
def use(self):
print self.info
class tree():
def __init__(self):
# create container instance
b = container()
# change b's info attribute
b.info = "b's info attribute"
# bound method test is set as use of b and in this case unbound, i think
b.use = self.test
# should read b's info attribute and print it
# should output: test: b's info attribute but test is bound in some way to the tree object
print b.use()
# bound method test
def test(self):
return "test: "+self.info
if __name__ == "__main__":
b = tree()
</code></pre>
<p>Thank you very much for reading this, and perhaps helping me! :)</p>
| 3 | 2009-09-15T06:09:52Z | 1,426,466 | <p>Do not move methods around dynamically.</p>
<p>Just Use Delegation. Avoid Magic.</p>
<p>Pass the "Tree" object to the Container. It saves trying to move methods around.</p>
<pre><code>class Container( object ):
def use( self, context ):
print context.info
context.test()
class Tree( object ):
def __init__( self, theContainerToUse ):
b= theContinerToUse( self )
print b.use()
def test( self ):
print "test"+self.info
</code></pre>
| 1 | 2009-09-15T10:58:52Z | [
"python"
] |
Convert hex to binary | 1,425,493 | <p>I have ABC123EFFF.</p>
<p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p>
<p>How?</p>
| 49 | 2009-09-15T06:41:37Z | 1,425,500 | <pre><code>import binascii
binary_string = binascii.unhexlify(hex_string)
</code></pre>
<p>Read</p>
<p><a href="http://docs.python.org/library/binascii.html#binascii.unhexlify">binascii.unhexlify</a></p>
<p>Return the binary data represented by the hexadecimal string specified as the parameter.</p>
| 35 | 2009-09-15T06:45:15Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] |
Convert hex to binary | 1,425,493 | <p>I have ABC123EFFF.</p>
<p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p>
<p>How?</p>
| 49 | 2009-09-15T06:41:37Z | 1,425,506 | <p>Replace each hex digit with the corresponding 4 binary digits:</p>
<pre><code>1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111
</code></pre>
| 0 | 2009-09-15T06:46:10Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] |
Convert hex to binary | 1,425,493 | <p>I have ABC123EFFF.</p>
<p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p>
<p>How?</p>
| 49 | 2009-09-15T06:41:37Z | 1,425,558 | <pre><code>bin(int("abc123efff", 16))[2:]
</code></pre>
| 26 | 2009-09-15T06:59:24Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] |
Convert hex to binary | 1,425,493 | <p>I have ABC123EFFF.</p>
<p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p>
<p>How?</p>
| 49 | 2009-09-15T06:41:37Z | 1,427,846 | <p>Here's a fairly raw way to do it using bit fiddling to generate the binary strings.</p>
<p>The key bit to understand is:</p>
<pre><code>(n & (1 << i)) and 1</code></pre>
<p>Which will generate either a 0 or 1 if the i'th bit of n is set.</p>
<pre><code>
import binascii
def byte_to_binary(n):
return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8)))
def hex_to_binary(h):
return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h))
print hex_to_binary('abc123efff')
>>> 1010101111000001001000111110111111111111
</code></pre>
<p>Edit: using the "new" ternary operator this:</p>
<pre><code>(n & (1 << i)) and 1</code></pre>
<p>Would become:</p>
<pre><code>1 if n & (1 << i) or 0</code></pre>
<p>(Which TBH I'm not sure how readable that is)</p>
| 9 | 2009-09-15T15:22:44Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.