Language: Python
Untitled Python (23-Apr @ 09:29)
Syntax Highlighted Code
- ® ° ¸ º ¼ ¾ Ï Û ä é ó ø02QS^`bsˆ—œ§°»ÓÕóõÿ ).8=HQ\rt’šœž¯»ÄÉÓØãì÷-/8: T <
Plain Code
® ° ¸ º ¼ ¾ Ï Û ä é ó ø02QS^`bsˆ—œ§°»ÓÕóõÿ ).8=HQ\rt’šœž¯»ÄÉÓØãì÷-/8: T <
Untitled Python (21-Mar @ 06:01)
Syntax Highlighted Code
- ‰SDB
- ÿS 8 fÇi.àvu ½®ÃÕÁç?+ÊÁ¥ÒÛŒöˆ¸=ÓùÎgÇs+"àó5âYTy&ä$õw¬MHÚ_ö>ò‚Çl¾ÓoÂßüGûz0'½¼4 ¤èÁž;Þçt~!¯!<U;×Èõ›”°0ÌK¦%„œÄð5Œ°Aäª7+å0b^)¦ó®‰M\ªã@¶. ÏEvj]›õ«¡1%çÀ)ÐwS‚¶””ôì‚QRîà•â‘(
- yaŠÏ¾õÇKWäG:fx&`ê‚›#‚"·†,wJ¶7Îç8ΜŒ1F%]üè
- [25 more lines...]
Plain Code
‰SDB
ÿS 8 fÇi.àvu ½®ÃÕÁç?+ÊÁ¥ÒÛŒöˆ¸=ÓùÎgÇs+"àó5âYTy&ä$õw¬MHÚ_ö>ò‚Çl¾ÓoÂßüGûz0'½¼4 ¤èÁž;Þçt~!¯!<U;×Èõ›”°0ÌK¦%„œÄð5Œ°Aäª7+å0b^)¦ó®‰M\°ªã@¶. ÏEvj]›õ«¡1%çÀ)ÐwS‚¶””ôì‚QRîà•â‘(
yaŠÏ¾õÇKWäG:fx&`ê‚›#‚"·†,wJ¶7Îç8ΜŒ1F%]üè
_¤6cq|Â<}é¯ÒؽAaYÿ*p,»-½]Mk¶·‰˜’
Þ" ß»~œGÈ‘4bžjo`•€ó_‚Nó8‚©ý§ò×ÕáyýmX^-¸~|{廒åaæÖgÓ±Âsq•´œKa*lÊ£fäOB>§ÕÉ‹ú®õ3OØE Om—ÀQmO¶WÐÑ0:Ä„Ü pG¦ß-¬>¤Mmg÷fñ¬˜3ÅBרœ
ñëQ0Ç?|þåi=°ŠyÉŸ!×b6Ž*,²Xc쵚ì¬dä…ccªOßÏÙ›âh÷X¢{}¸ŽµÖ]|[ Ó<㦦=¼·:qÜE4UP½Á(?^v!y?g'é£)v$˜+ñ‚<$Æ%uK[†ºvÌ®´ ϶|2ä ÎHRø±ƒ;‡2–:䮎XÃ+¾«{“ÕñZqã'‚ºúuÕ^RåòU;?ê³ÏÌa)s]´"ù²á Aã"mÁ˜FDÆ`k};ø®„Q>T‚g“ð×h‡±>ÊF‡sa*ûö,|£|¸Á‹'åûÐ!)G@g2—F¾•鋤àÇíҗкªÔXØñ ÿ>£Ñ-U?È´Q-øÏ¾Ló1: %_7qj„Í;<úu7§µ ff)ãˆ|†FëÕÆV)Aãi8÷žÍRMF²æþKF£'^góTÍÚä.µƒ;¹RÕeÉè¼›{›k@0* €€Õæq¿ñÿ~5¢ƒv¡ NÚꋬEûzᘽ/€=ãiHó–ò; íTÒFÀ±r¨–Mí#þw
ÀÞ^-,¥h“=0QHû'Czä@”+O9}ËÞáÔmp •ƒçE¥5GpÃ_šxÜutf%£H2*rmØFŠ.öÄÞø‚]&ÈRºPÆÔwÊsöhK6k(;c.[ÛÙ4ê®'J/ø¾ÞÇ¿ûlÍߪ¾™§ÖsÖ†ò&&ê?¿b¦a‘TKHfx¬1_“Í—+Ózånåпó㱋dÀFžZÌÝPšÞT)ým©m4g%{Ãòé‚òh˜ªYR1ÔOïã41Êpa±ÌÒAóþ1Êê„pÂÙE¤Wmd.Rø·YãùáÔ dº¤)¾ˆyÙí†åN¿U(§r›Ûý"Â"A¡?ëàÀ–¸ød5Þû;ñÉü‚6|eâücáHàß丬ùH#±:6MAÇE£®AMv¥Æñi&sNrÿ¤Ás‹ÕioQÿK¼Éýu’é-°Â„]¢õ¸ª€ÎY'ú'’^æo<y÷ïf¨¹+¬(k¨™'ÆÜ£›y˳Éìd>m¦OlH=bá§Õï`¼YÓ®XCášvqÚüm"lö…F!boOçÆ»b xçÆŒUÅ5…}°=¾ÖÞ]oäè¿â‚ÎøÜº*»ŠG{ör<OŸÝay§OVŸ4XN,4ØÚ1%GTæóX²šþpYÓ3¢€PTî['ž
Ľq¢ÓY\²# CÙ¡&¹¦o,7‹6v²sQp.Œ†¶Ž¡,'ì›™¶À ãÍpд²Ó×ÐÇý¸ë·9ˆyŸÉ—oL…³ƒkÆz¤ÙALwKç5nNÚĬÕ&08J»v™°ýã°“q <>©lË×h•!’Ÿšª¼FÏC8{ßq}£:õʆ†; x)4€qì«&™hÐäxú ˆr³úa¾‘õ®4¼Qsüº§73XüzÎ\ØSÄíž”³×~.’óÈ(‚iñí·ªÂò©zÙ^Ù^¹áF¼ž‘‹ŸêÖ Úþ·9¤¬zųƒpÞ??U9‹“JpŽ’â믌¿v,0PÒª©ô2´ž—§ÿðõi)ðþUÛ¾â |ö¡ Ù»ˆE|¾2i‚X4“×3R©TTyjI#ÆP÷`0;\–Q!€’K®Ä¬P´6Û*!ý¸¦†GLYpÿ0ðKkeÖȉžgx-Ï-Êâoʺò줛U˜Öô~¨•]PT‹`ÌVüçR†ÿø—HÄLjÌ/5ù¹:.hðvâ*£{î°í÷»E‚×jTÇN¼H³¾¤‘FÎ9_šÀ´é!(ÛÌÄ3¹Q²#šZb¶±•{›[®rìVZ±ŠÜ¼ÖlDNl4X5ƒúRQÚÿî*ô²™¿G}.â’"°¯:rþix~̨Ï#л¥Ü”cýFÅCtÛ+‰‰îê<o¢×“s§a
Iv0@¾žó&óMI:|¨ëÏIðô».ήõ…7Óîá9.¹9_ p•Û"„Ð~/nLïí… Ì7u^j3&ÇÏöèá
HqVg³‰§ÁÆï¬˜£‚¼‡KüñM}WÐPÕ7mâ^ðÐlÞ=wÀM•Gi”‹‚·‘,ìµÚË›;mÁ›É¥aŸÈ”« "N®Å¢´Ûþ¾Û‡½BçsXø
¸ÒòfW L„r[ro¾ŠŽÎú¤–Ÿ©“Qƒ‡›9w)k䮇È"Éá4!Ž.ûeð!±ð•ý¹¹þÍq>•ˆÇ6¬üÏ“´ÖA-a|ÑÝÚ•èFŒ+=Èe/ÃÝ=ë_Ž&É7%_]ªWÂÙÕ‡ü!—
mN@¾Š$®ýFkà1,þúÓôðwGx麓æÃQ¿.VÛÝ+’p±?°1Ú-Ï ÿM‰ÌKfJC0#EeS?yÔrÕ)ß1¼TGNçX~°ˆ/|dÒ~Ñg󪯩ýÆwD<hù”`sÙ7ït¶˜-0ÁôkÛùDèæ•¡V$Œ(*U*t&[S¾ºwõ—?suö‚ÅN‡½¨üÐ+Üjr›5Ë à†ÿ!¾$¾É4í7Ë5s=—"•ù}•ËÜŬ¸"Å~‚À ‚Tå‹Ä&Îæfèë¯îó1ã㨛1sLîs pˆ>äŽ-œEs4Öa,ÔôÖ8Ãh›<C2r‹JÁŠ*ÿ¦YÁ߀Ó͹
ÙžûiÄA¡³ºõvK|ˆXÔs¦fuP „¨:ީű¥ÞjÔ=šŠ;mU*Ï k‰zʱDв‚¥/¤F2Maó6fmý³Â3op:þÖ2Ǧ16sñŸÿ³V«MwÍ• 1ÌDG„ ´#gqæ,þðŒÄEŠZÉžgpß™V"á ‡yO{^û©º"""^Jì£-Tá“ãHàÐéú3ùª[Ã6—C Û@ÝðŸÐÂdãIîSË’|™*ûf½xÔ¯ÛH+RUnÁ¨| VQôË\—½î'nÔ¹^«âôŒ¹=©P¾g¹•»Ó›éÉJIÂ@räÿB.7®zÎ sǯ{`}˜¼SMR*®S‚˜'·9Ý:…ªŒ9r;±&kð’é‹6èM÷©®L £±`5[ Y%ðä`EáÙ cç¹o`Tèã~IìüTh{ˆÑŽMõ„·”8·¢cê¹ÂÒ‘Öθ™Å~@£©ºt«*¦ÉÝQu©ËÌV'î»2sò‡ÔI(æ>`÷û©«s#2µÍ¢šñp"Yª°OÍÃJÚwcp /¿Mâ8IàLŠËUPxÕ©‚£õ*¨ˆ ®ø¤í'}X<‚6CiÑ X8>‹Ø@Ð'ªöž²Wá8aŽjè;pSسD›© çf»ý@› Dø>‡ %‡ íñ}ê\BºìëÛ!2
üÐ×izMÒ¨ê¯GAåÞ.0‰ðYi#™ø)ƒ˜‡kp—7¨ŒïrºÑлã˜À×|ø
§7%3¯3hïlƒ…FÔJeSÓ¹ &~kr±V5©¥2í9´K;R•˜jn8å]àÊ·f“F]?ENçú#‚×Ö_ÁÜo@f<âàVšF x F¬,õ‰¶úò0%ª>ÉÉ'£²1ø°uÕ?ø ïi‰¹"°o( Z?•/@™9”F=,áÈ#:FŸ†Yàþ)y4‡qç2¨ñå aÊO¬8‚dýZ˵ðº¬ÜÆü!InákÅ1÷Û'Ç‹C†1ä$«Në^â´˜Š)ƒiV1“C{ŠÃ|x—ÂÞÑà Ë¿/)4ÿfd0vfÞÆœ³
Ç÷lj«®£\NxZÒ1[áN(W¦µb53/÷³ˆôIôºUìî^›,£Tˆ”gšÉÜä”;BÛ}áuÒ–¢Ð•§áÞ8†.[P‰ÊFÕY)Ñ@¡Ò•Šnî`t§Ãh[˜ÂÒo4Êd¿ýÄ+¥ûÖÙ1¯2ÄÐ<£hð¿$ø‡7ãí|¹v쇇(¯Ê´@áfuB«££`ÞYÓ>G«Òú@p‘Šï¿yæÈvË·Q"ÃŽòšÑ.‹œèÕ 2ÿ&$öüUÖöIÈY£cx¢Ì
¢HË4bµfÖ™b—)ZÞ Õ]l6Ts*mý✕Y•n‡´Ni†è¼ðôUBÓSØ6Ù“V™¿@%Dýù4ÿäåFÛb ÒlWÊ0P¦Å5#áØ2G–*éCÚÑUéc¤|›®b(®%©‰’—ÑÕÇë
ù†p7h.©Ã9á(‡öÞ£2Áæu¢'ËR!o¿[õAÃxJ
ôB5Õöe5¨1À™¦ÖÅl¡N•©Ñ¨Òz7ì$&*ëÐè:˜|sÂ#ý3{®IkD½ŒX2ÁïÄ<ñ¾*€J3uÔ1Î+vŸÁNàxQ•‹Üág]€«§‰òx£–ÐßNæ(ÓÀ0'ÜþY¨`ÀÙ鲘èåÄ]*Æ•S«ÞçûaËqÉ˽qQ)©ÊHöáA
À›Hã–@IÒFý¹ß÷ó¢ÞÝÝó–õUå $>§ÐR¹ûìzucCñŠÆÁ4¬‹óù•=‡3„„»u{¸õâ*ô”ÂΉ™¶“ÑSùžlS–'†¸[¿91nEe· {ºz¬¾‡Î[P¯ã‹útàëR¨.¿MmXÔŠÞ\8/ªJ/< Áeƒ‘´Ã3!%:AC?ÈÉo”Â,³UY"îPªµù‡,xÿ¾Éß9Œ0Ü¥‡ž AœÄÞ—*ÁÛ|:ð)O—ЇÐÒ¨–’Géq6$‹~{–õü‰zÎÚêÈ”q-(l‚몺†Ô9±[ߤøFõÅâIÛP÷)zUúëèÍe8i³<ïÈ
j3Ú·ãè?ˆ‚ïjqŠðIÕ?ºàú&Cưõm{T^à´Pè¹ïÐëE';†%=ß ‡\ð6€r±…sáŽy#ÅF‹Sý³ðöYšTq¶oR
Ð<¶ª%å©°VX߇vRÌW,K×…ñ“ü1
Éÿåml‚õ9ûæ°F˜n»ðí½"Icx N{EîbD˜Ò
ÁŸ§G¢‡|OÞúS Æøß˜ÇZQâ9léÌ¢BôÞƒ+ø•;‘ªe±YyÈú°ÃŽþ_5g“䘊º¢ ã*?Žüé½KÂ$ŒY¥líX`Tü®å®#ÄFiet«)þ$O)•¬d¨œÉiM0‹iÐþörò^FŒ†Á¨;ÊJ¬E¾!§6eáí•GyíÝ€—“á³½@óZyG%ca€U<PB“[!ß‚tÁ{•Ÿêô±ãÌ^¢¿3Ö3ÌOƒCÞá"VÊ?•ÅÉùä™É!‰!‹£R½ù5®AßmÓ7VÝ›K"N'À½|ʼÍå‰mn…t¬Hpøoö=ø×j±³C©…;Þz‡©Î° à—¿` EÜ=>ØIIf±*a¦ùÞõfô¡¼/s€6 ¯³ñÔÕ‚ulë"¥Ô‘xø-¥ñ<:<ÙÕ[ªx÷8/‹.S‘” cîgš@ü5‰øÚA^z+ìYëhf€?+a¡Cd[€è/ÎκÉ,Â3CÃ-Ò·èp\Š¿a8Š<¦ýÏXèHØ?S„‘^šÑî£
çÈNXVvæ_YF÷¸Ú7ƒÛ ;ÏÎAµŠS?4¢
÷r»‰µ0ư€?ù«ÓÖd?b„2Tœ_3=m¬îç$¦uÄa×;G•©abgnîmñ«òWéØ5ŒLv&ÚÊ”{CÎÖ.âþ6ìZ3oø;X_§aTgÜÜ€r’¶ùÆb5$¦ÏTçyL~£ÄVºò%ä>–FîÐQwVm‹§ìít^ú·z°™$†b÷c¸ËQ›ðUÄ‘QO‰-ÃD<¹¢[›".«u7t98jì+ištÖc·dËÅÐZî¾6*ȥΙ
> FLã»I›ydÒg•Ýä·¯àš§¸fÂa:Ï“1ž-ŒDx[ZGJ>Ñ+SâÌ‹¼H5qçx²/•³Byi—„!ŒŠÕ~îL–Ц»ð;‰â0íHi1J!ÃòQoäø–h"ñûu¼„ÚfÕPí…ucEL´«gn3BP;¤‘§µ€S¤öÏ‘‹r'RnКáqÁ#…”™åõÊháöÇœÜÀÜU‰Å×(åáe¡ÎRKt7v– füºÙ¿ó¸"ÇÐù TJÓát@ílÔ3¬À„ô³Ðʪ÷¼.Z Ú%ñQþömkõœÓÿ{åÉý]Jgš\¾{mÄçϯ—òrú£ä˰ø‚ß
1ܰ»¤âgË(qhIìäÿÿhu4ž±•õ1eïÚ(°zã‹CðE‘«Â;qèƒCj¦°x?!žQ3Ë(¶‚EjW_bEJ{èjÿÀü¯îš÷Ù·Å GØáØ‹ÝÜZa9LªN!ÐíW&–ŠE_J5Öðæ/pªŒC-‰qy«£?ÐäékÎÜÁ±Û\b—.îöæ´“„J‘§^Ò7ã½/8Åĸrˆ58íûšLx':dó°f°Y!1°Ãô•\z‘Œ`OÍѼÌFÑ¢z
MårÙ`ÉØ÷aÌYÔ±£ÂTÛWý<þš¿ñõRÁš[þHÚÿB¦÷Öˆð#ÖöÖ˜dL'R5ºp4*=äH=¦‰œþ3]öê•Ðç™Á¶'eh¬øÛy¥F|Ÿ³Ž=…Œ_:æ½Ü}Y_Ï”ó&n¼[Ïžø(~²¤hµv…Ô¶“÷B=AÝ¿µåO¢ÄÒn¬ßY³[¹·K`‡ÔÆÑ(¯ø#kïÜa;¾É(ûÕ)†1
Untitled Python (21-Mar @ 05:40)
Syntax Highlighted Code
- Ž h L 8 $
- ô Þ Î ´ – x ^ D 8 0 & s ñÍ[J % à à h H RSDSH,”ÂZ÷Jš°Ï€jš3 wiatwain.pdb * ‹ÿU‹ì¸csmà9Eu
- ÿuPèe YY]Ã3À]ÃÌÌÌÌÌ‹ÿU‹ìV‹u3Àë…Àu‹…ÉtÿуÆ;urì^]ÃÌÌÌÌÌh€ ÿD Y£@# £<# …Àu@à 3ÀÃÌÌÌÌÌ‹ÿU‹ìS3ÀVW9Eu&9 ~ÿ
- ‹=( P¾8# éå 3ÀéK ƒ}…> d‹
- [5 more lines...]
Plain Code
Ž h L 8 $
ô Þ Î ´ – x ^ D 8 0 & s ñÍ[J % à à h H RSDSH,”ÂZ÷Jš°Ï€jš3 wiatwain.pdb * ‹ÿU‹ì¸csmà9Eu
ÿuPèe YY]Ã3À]ÃÌÌÌÌÌ‹ÿU‹ìV‹u3Àë…Àu‹…ÉtÿуÆ;urì^]ÃÌÌÌÌÌh€ ÿD Y£@# £<# …Àu@à 3ÀÃÌÌÌÌÌ‹ÿU‹ìS3ÀVW9Eu&9 ~ÿ
‹=( P¾8# éå 3ÀéK ƒ}…> d‹
‹Y‹=( ‰EP¾8# ë;Ãthè ÿ j SVÿ×…ÀuçëÇE ¡4# j_…Àt jè ë9h` hX Ç4# èÿÿÿYY…À…zÿÿÿhT hP èM Y‰=4# 3ÛY9]uSVÿ, 9H# thH# è³ Y…Àt
ÿuWÿuÿH# ÿ ëwhè ÿ j jVÿ×…Àuê¡4# ƒøt
jèï YëM‹@# …Ût0‹=<# ƒÇüë‹…ÀtÿЃï;ûsñSÿ@ ƒ%<# ƒ%@# Yj VÇ4# ÿ, 3À@_^[] ÌÌÌÌÌj,hð èš ‹M3ÒB‰Uä3ö‰uü‰
;Îu95 u‰uäé ;Êt ƒù… ¡D# ;Æt6‰Uü‰ ÿuQÿuÿЉEäë‹Eì‹‹ ‰MàPQèýÿÿYYËeè3ö‰uä‰uü9u䄱 ÇEü ÿuÿuÿuèÖýÿÿ‰Eäë‹Eì‹‹ ‰MÜPQèKýÿÿYYËeè3ö‰uä‰uü9uä„o ‹MÇEü ÿuQÿuèº ‰Eäë‹Eì‹‹ ‰MØPQèýÿÿYYËeè3ö‰uä‰uüƒ}…œ 9uä…“ ÇEü VVÿuèr ë‹Eì‹‹ ‰MÔPQèÃüÿÿYYËeè3ö‰uüÇEü VVÿuèýÿÿë‹Eì‹‹ ‰MÐPQè”üÿÿYYËeè3ö‰uü¡D# ;Æt,ÇEü VVÿuÿÐë‹Eì‹‹ ‰MÌPQè_üÿÿYYËeè3ö‰uü9ut
ƒ}…€ ÇEü ÿuÿuÿuè¥üÿÿ‰Eäë‹Eì‹‹ ‰MÈPQèüÿÿYYËeè3ö‰uä‰uü¡D# ;Æt>95 t6ÇEü ÿuÿuÿuÿЉEäë‹Eì‹‹ ‰MÄPQèÓûÿÿYYËeè3ö‰uä‰uüÇEüþÿÿÿè ‹Eäè Â Ç ÿÿÿÿÃÌÌÌÌÌ‹ÿU‹ìƒ}uè½ ]é‰ýÿÿÌÌÌÌÌÿ%H ÌÌÌÌÌÌÌÌ‹ÿU‹ì‹M¸MZ f9t3À]ËA<Á8PE uï3Ò¹ f9H”‹Â]ÃÌÌÌÌÌÌÌÌÌÌÌ‹ÿU‹ì‹E‹H<È·ASV·q3ÒWD…öv‹}‹H;ùr ‹XÙ;ûr
BƒÀ(;Örè3À_^[]ÃÌÌÌÌÌjhp è‡ ƒeü ¾ Vè\ÿÿÿY…Àt=‹E+ÆPVè‹ÿÿÿYY…Àt+‹@$Áè÷ЃàÇEüþÿÿÿë ‹Eì‹ ‹ 3É=
Untitled Python (18-Feb @ 20:01)
Syntax Highlighted Code
- #My simple Record model
- class Report(models.Model):
- name = models.CharField(max_length=64)
- items = models.ManyToManyField(Item, blank=True, null=True)
- [69 more lines...]
Plain Code
#My simple Record model
class Report(models.Model):
name = models.CharField(max_length=64)
items = models.ManyToManyField(Item, blank=True, null=True)
def __unicode__(self):
return self.name
#My CRUD from view.py
@crud(z_remote_provider)
class ReportCRUD(ExtDirectCRUD):
model = Report
metadata = False
#My extjs code
var window = Ext.create('Ext.window.Window',{
title: 'Edit report',
autoShow: true,
closable: true,
modal: true,
height : 70,
width : 300,
border : true,
layout : {
type : 'hbox',
align : 'stretch'
},
items: [
{
xtype: 'form',
flex: 1,
bodyStyle : 'padding: 10px; background-color: #DFDFDF; border: none;',
defaultType : 'textfield',
defaults : {
anchor : '-10',
labelWidth : 70
},
items : [
{
fieldLabel: 'id',
name: 'id',
allowBlank: false,
hidden: true
},
{
fieldLabel : 'Name',
name : 'name',
allowBlank: false
}
]
}
],
buttons: [
{
text: 'Сохранить',
handler: function() {
var form = this.up('window').down('form');
var name = form.getForm().getValues().name;
z.ReportCRUD.update({'records': [form.getValues()]});
form.up('window').close();
}
}
]
});
Untitled Python (26-Jan @ 06:44)
Syntax Highlighted Code
- print "TEST Message"
Plain Code
print "TEST Message"
Untitled Python (13-Dec @ 07:41)
Syntax Highlighted Code
- class Hangman():
- [92 more lines...]
Plain Code
class Hangman():
#The definition of the four primary lists that will be used in the game
global Category1
Category1 = ["Duck", "Zebra", "Pig", "Lion", "Tiger", "Leopard", "Lynx", "Elephant", "Cheetah", "Puma", "Giraffe", "Turtle", "Hippo", "Raven", "Falcon", "Whale", "Dolphin", "Shark", "Monkey", "Bulldog", "Hawk", "Raccoon", "Hummingbird", "Scorpion", "Parastratiosphecomyia Stratiosphecomyioides"]
global Category2
Category2 = ["McDonalds", "Burger King", "Swiss Chalet", "Harvey's", "Wendy`s", "Tim Horton`s", "KFC", "Taco Bell", "Dunkin Donuts", "Pizza Pizza", "Pizza Hut", "Subway",
"Mr. Sub", "Quizno`s Sub", "Jumbo Dragon", "Little Ceasers", "Arby`s", "Mei King Chinese", "Tommy`s Pizza & Wings", "The Grill", "Mega Pita", "A&W", "Starbucks", "Sonny's Fish & Chips", "Pita Factory"]
global Category3
Category3 = ["Toronto Maple Leafs", "Vancouver Canucks", "Buffalo Sabres", "Boston Bruins",
"Detroit Red Wings", "New York Rangers", "Pittsburgh Penguins", "Philadephia Flyers", "Carolina Hurricanes",
"San Jose Sharks", "Nashville Predators", "Florida Panthers", "Calgary Flames", "Ottawa Senators",
"Phoenix Coyotes", "Los Angeles Kings", "Anehiem Mighty Ducks", "Washington Capitals",
"Tampa Bay Lightening", "Dallas Stars", "Chicago Blackhawks", "Minnesota Wild", "New York Islanders",
"New Jersey Devils", "Montreal Canadiens"]
global Category4
Category4 = ["Kraft", "Lenovo", "Westinghouse", "Western Digital", "LG Electronics", "Seagate", "Happy Foot",
"Fruit of the Loom", "Adidas", "Red Hat", "Mustang", "Hummer", "Armani Exchange", "Timex", "Blackberry", "Stihl", "Speedo",
"Mr Lube", "Husqavarna", "Quattro", "Triumph", "Kleenex", "Canon", "Hewlett Packard", "Boeing"]
def Debugger():
print "You should not see this..."
print "Gathering lengths of each category..."
print "Category 1: " + `len(Category1)`
print "Category 2: " + `len(Category2)`
print "Category 3: " + `len(Category3)`
print "Category 4: " + `len(Category4)` +"\n\n"
def Starter():
global choice
choice = input ("Please enter the category number for the category you wish to use: ")
print "You chose: " + `choice`
#This will be the core of the game engine, however the game itself will operate based off the value chosen in the above function
def MainStringDefinition(): #This function will be used to non destructively utilize one of the four lists provided above
print "\nReloading Data...\n\nThe game mode chosen was: " + `choice`
global MainString
if choice==1:
MainString = Category1
elif choice==2:
MainString = Category2
elif choice==3:
MainString = Category3
elif choice==4:
MainString = Category4
else:
print "You done fucked, try again!\n\n"
global ListLength
ListLength = len(MainString)-1
#This is where the "magic" happens. The code in this function will be designed to first generate a random number between 0 and the total number of entries
#In this case there are 25, so the static interval of 25 will be used. However, the code will later need to be updated to allow for compatibility of
#a customized set of lists with an unknown number of entries. To do this, a global variable in the code after the MainString variable is assigned a value
#will need to be created that finds the length of the main list, subtract a value of one, and then use that variable in the random function to choose
#a corresponding string from the list.
def WordRandomizer():
#randomize a number between 0 and the total number of entries in the chosen list
global randomizer
randomizer = random.randrange(ListLength)
print "The word from the list will be entry number: " + `randomizer`
global gameWord
gameWord = list(MainString[randomizer])
print "The word is: " + "".join(gameWord)
def CharReplacement():
#The following will get the length of the character list of the getWord variable, and run a loop that replaces each character in that variable with stars
global gameWordLength
gameWordLength = len(gameWord)
global gameWordDisplay
gameWordDisplay = gameWord
i = 0
while (i<gameWordLength):
if gameWordDisplay[i]==" " or gameWordDisplay[i]=="`" or gameWordDisplay[i]=="'":
gameWordDisplay[i]=gameWordDisplay[i]
else:
gameWordDisplay[i]="_"
i+=1
print "The way in which the word will appear to the player will be: " + "".join(gameWordDisplay)
Debugger()
Starter()
MainStringDefinition()
WordRandomizer()
CharReplacement()
Untitled Python (12-Dec @ 04:43)
Syntax Highlighted Code
- #The Hangman Game
- class Hangman():
- #The definition of the four primary string arrays that will be used in the game
- [32 more lines...]
Plain Code
#The Hangman Game
class Hangman():
#The definition of the four primary string arrays that will be used in the game
Category1 = ["Duck", "Zebra", "Pig", "Lion", "Tiger", "Leopard", "Lynx", "Elephant", "Cheetah", "Puma", "Giraffe", "Turtle", "Hippo", "Raven", "Falcon", "Whale", "Dolphin", "Shark", "Monkey", "Bulldog", "Hawk", "Raccoon", "Hummingbird", "Scorpion", "Parastratiosphecomyia Stratiosphecomyioides"]
Category2 = ["McDonalds", "Burger King", "Swiss Chalet", "Harvey's", "Wendy`s", "Tim Horton`s", "KFC", "Taco Bell", "Dunkin Donuts", "Pizza Pizza", "Pizza Hut", "Subway",
"Mr. Sub", "Quizno`s Sub", "Jumbo Dragon", "Little Ceasers", "Arby`s", "Mei King Chinese", "Tommy`s Pizza & Wings", "The Grill", "Mega Pita", "A&W", "Starbucks", "Sonny's Fish & Chips", "Pita Factory"]
Category3 = ["Toronto Maple Leafs", "Vancouver Canucks", "Buffalo Sabres", "Boston Bruins",
"Detroit Red Wings", "New York Rangers", "Pittsburgh Penguins", "Philadephia Flyers", "Carolina Hurricanes",
"San Jose Sharks", "Nashville Predators", "Florida Panthers", "Calgary Flames", "Ottawa Senators",
"Phoenix Coyotes", "Los Angeles Kings", "Anehiem Mighty Ducks", "Washington Capitals",
"Tampa Bay Lightening", "Dallas Stars", "Chicago Blackhawks", "Minnesota Wild", "New York Islanders",
"New Jersey Devils", "Montreal Canadiens"]
Category4 = ["Kraft", "Lenovo", "Westinghouse", "Western Digital", "LG Electronics", "Seagate", "Happy Foot",
"Fruit of the Loom", "Adidas", "Red Hat", "Mustang", "Hummer", "Armani Exchange", "Timex", "Blackberry", "Stihl", "Speedo",
"Mr Lube", "Husqavarna", "Quattro", "Triumph", "Kleenex", "Canon", "Hewlett Packard", "Boeing"]
print len[Category1]
print len[Category2]
print len[Category3]
print len[Category4]
def Starter():
global choice
choice = input ("Please enter the category number for the category you wish to use: ")
print "oh hi mark"
#This will be the core of the game engine, however the game itself will operate based off the value chosen in the above function
def MainStringDefinition(): #This function will be used to non destructively utilize one of the four string arrays provided above
print "\nReloading Data...\n\n The game mode chosen was:"
global MainString
Starter()
Untitled Python (2-Dec @ 13:24)
Syntax Highlighted Code
- ë ¯Â¿£ì?þÁuù1Àº?ÐÁÊ Š Š?þÁuèé\?\X=AAAA?u;Z‰Ñ‰æ‰?щß)Ï1À1?Š Š4 ˆ4?Š Š 0Úˆ?ØþÀÍ€è? 1Ɉ?ï¾Þ ??< ˆ ˆ<?uCX=BBBB?ß)Ïó¤‰Þ‰?Û1ÒþÀ ? ˆ ò0ö? GIuÞ1Û‰?ÿÿÿAAAA
Plain Code
ë ¯Â¿£ì?þÁuù1Àº?ÐÁÊ Š Š?þÁuèé\?\X=AAAA?u;Z‰Ñ‰æ‰?щß)Ï1À1?Š Š4 ˆ4?Š Š 0Úˆ?ØþÀÍ€è? 1Ɉ?ï¾Þ ??< ˆ ˆ<?uCX=BBBB?ß)Ïó¤‰Þ‰?Û1ÒþÀ ? ˆ ò0ö? GIuÞ1Û‰?ÿÿÿAAAA
Untitled Python (2-Dec @ 13:22)
Syntax Highlighted Code
- »[—¹uã5¸%ÁuÐb.Ô
Plain Code
»[—¹uã5¸%ÁuÐb.Ô
Untitled Python (14-Sep @ 19:02)
Syntax Highlighted Code
- from zope.interface import implements
- from twisted.cred.portal import IRealm, Portal
- from twisted.cred.checkers import FilePasswordDB
- [80 more lines...]
Plain Code
from zope.interface import implements
from twisted.cred.portal import IRealm, Portal
from twisted.cred.checkers import FilePasswordDB
from twisted.web.static import File
from twisted.web.resource import IResource
from twisted.web.guard import HTTPAuthSessionWrapper, DigestCredentialFactory
import md5, sha
from zope.interface import implements
from zope.interface.verify import verifyObject
from twisted.trial import unittest
from twisted.cred import error, portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.cred.credentials import IUsernamePassword
from twisted.internet.address import IPv4Address
from twisted.web.iweb import ICredentialFactory, IUsernameDigestHash
from twisted.web.resource import IResource, Resource
from twisted.web._auth import basic, digest
from twisted.web._auth.wrapper import HTTPAuthSessionWrapper, UnauthorizedResource
from twisted.web._auth.basic import BasicCredentialFactory
#from twisted.web._auth.digest import calcHA1, calcHA2, calcResponse
from twisted.web.server import NOT_DONE_YET
from twisted.web.static import Data
from twisted.web.test.test_web import DummyRequest
class Realm(object):
"""
A simple L{IRealm} implementation which gives out L{WebAvatar} for any
avatarId.
@type loggedIn: C{int}
@ivar loggedIn: The number of times C{requestAvatar} has been invoked for
L{IResource}.
@type loggedOut: C{int}
@ivar loggedOut: The number of times the logout callback has been invoked.
"""
implements(portal.IRealm)
def __init__(self, avatarFactory):
self.loggedOut = 0
self.loggedIn = 0
self.avatarFactory = avatarFactory
def requestAvatar(self, avatarId, mind, *interfaces):
if IResource in interfaces:
self.loggedIn += 1
return IResource, self.avatarFactory(avatarId), self.logout
raise NotImplementedError()
def logout(self):
self.loggedOut += 1
class MyApp(object):
"""
Simple test of realm and avatar
"""
def __init__(self):
"""
Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests.
"""
self.username = 'admin'
self.password = 'letmein'
self.childName = "protected"
self.childContent = "contents of the foo child of the avatar"
self.checker = InMemoryUsernamePasswordDatabaseDontUse()
self.checker.addUser(self.username, self.password)
self.avatar = Resource()
self.avatar.putChild(
self.childName, Data(self.childContent, 'text/plain'))
self.avatars = {self.username: self.avatar}
self.realm = Realm(self.avatars.get)
self.portal = portal.Portal(self.realm, [self.checker])
self.credentialFactories = []
self.wrapper = HTTPAuthSessionWrapper(self.portal, self.credentialFactories)
instance = MyApp()
portal = instance.portal
credentialFactory = DigestCredentialFactory("md5", "localhost:9000/httpauth.rpy")
resource = HTTPAuthSessionWrapper(portal, [credentialFactory])
Untitled Python (29-Aug @ 14:42)
Syntax Highlighted Code
- class Affect(SharedMemoryModel):
- """
- Affects...
- Very complicated affects model, might need to be cleaned up
- [23 more lines...]
Plain Code
class Affect(SharedMemoryModel):
"""
Affects...
Very complicated affects model, might need to be cleaned up
"""
TARGETS = { "none" : (0, "none"),
"cooldown" : (1, "cooldown"),
"attribute" : (2, "attribute"),
"resource" : (3, "resource"),
"overtime" : (4, "overtime") }
#in case of ItemData or Item it'll be null
character = models.ForeignKey(Character, related_name="affects", null=True, blank=True)
#in case of ItemData it'll be null
source = models.ForeignKey(Character, related_name="active_affects", null=True, blank=True)
item_data = models.ForeignKey(ItemData, related_name="affects", null=True, blank=True)
item = models.ForeignKey(Item, related_name="affects", null=True, blank=True)
name = models.CharField(max_length=32)
target = models.IntegerField(choices=TARGETS.values(), db_index=True, default=0)
time_started = models.FloatField()
duration = models.FloatField(null=True, blank=True)
repeats = models.IntegerField(null=True, blank=True)
ability = models.ForeignKey(Ability, null=True, blank=True, related_name="affects")
attribute = models.ForeignKey(Attribute, null=True, blank=True, related_name="affects")
resource = models.ForeignKey(Resource, null=True, blank=True, related_name="affects")
value = models.FloatField(default=0) #depending on what kind of target, this means something different
pause = models.BooleanField(default=True) #whether or not to pause it on log out
applied = models.BooleanField(default=False) #has it been applied yet?
Untitled Python (26-Aug @ 06:11)
Syntax Highlighted Code
- % Task 1 code: Part 1 – Trajectory of Bullet (looped until bullet landed)
- % This is part of the drag portion in formula
- c = (AssumedDragCoefficient*Area*Density*dt(J))/(2*BulletMass);
- % Generate velocities
- [82 more lines...]
Plain Code
% Task 1 code: Part 1 – Trajectory of Bullet (looped until bullet landed)
% This is part of the drag portion in formula
c = (AssumedDragCoefficient*Area*Density*dt(J))/(2*BulletMass);
% Generate velocities
u(I+1) = u(I) - c*u(I)*V(I);
v(I+1) = v(I) - c*v(I)*V(I)-Gravity*dt(J);
V(I+1) = sqrt(u(I+1)^2 + v(I+1)^2);
% Generate distances
x(I+1) = x(I) + dt(J)*(u(I+1)+(u(I)))/2;
y(I+1) = y(I) + dt(J)*(v(I+1)+(v(I)))/2;
%If height goes below 0, try smaller step so it tends to 0
half = 0.5;
while y(I+1) < 0
x(I+1) = x(I) + half*dt(J)*(u(I+1)+(u(I)))/2;
y(I+1) = y(I) + half*dt(J)*(v(I+1)+(v(I)))/2;
half = half/2;
end
% If height goes to 0, break
if y(I+1) == 0
break
end
% Task 1 code: Part2 – Convergence (looped for each dt choice)
% Reduce step by half starting from 0.5
dt = 0.5.^(1:8);
% Store landing distances in array
Distance(J) = x(length(x));
% Percentage Error in distance
for K = 1:length(Distance) - 1
dDist(K) = abs((Distance(K+1) - Distance(K))/Distance(K))*100;
end
% Plotting with details
plot(dt(2:length(dt)),dDist,'x-')
% Task 2 code: Trajectory of 3 Bullets (task 1, part 1, looped for different bullets)
% Mass, Diameter, H.Velocity, Drag coefficient
S = [0.033 0.018 0.5 240; % Brown Bess Musket
0.0314 0.0117 0.3 380; % Martini-Henry
0.0113 0.0077 0.2 744]; % Lee-Enfield
% Set color of line for plotting
PlotColor = 'gbr';
% Reassign x and y to plot trajectory for new bullet
clear x y
x(1) = 0; y(1) = Height;
% Plot graph
plot(x,y,PlotColor(j))
% On hold to retain plots for different bullets
if j == 1
hold on
end
% Task 3 code: Trajectory of Bullet with Side Wind (Top view)
% Acceleration will decrease until bullet speed same as wind speed
if w(I)-10 <= 0
w(I+1) = w(I) - c*(w(I)-10)*V(I);
else
% Will never reach here because the travel time is too small
w(I+1) = w(I);
end
% Total Velocity
V(I+1) = sqrt(u(I+1)^2 + v(I+1)^2 + w(I+1)^2);
% Plot graph
plot(x,z,PlotColor(j))
% Extra Task code: Trajectory of Rocket
% Work out other values required
TotalMass = RawRocketMass + PropellantMass;
dMass = PropellantMass/IgnitionTime;
Area = pi*(Diameter/2)^2;
Thrustu = cosd(Angle)*Thrust;
Thrustv = sind(Angle)*Thrust;
% Generate velocities
u(I+1) = u(I) - c*u(I)*V(I) + dt*Thrustu/TotalMass;
v(I+1) = v(I) - c*v(I)*V(I) - Gravity*dt + dt*Thrustv/TotalMass;
% Setting 0 as the limit (ground)
if y(I+1) < 0
y(I+1) = 0;
end
if I*dt<2
% Mass decreases in proportion to fuel used, up to 2 seconds
TotalMass = TotalMass - dMass*dt;
else
% Negate Thrust after 2 seconds
Thrustv = 0;
Thrustu = 0;
TotalMass = RawRocketMass;
Untitled Python (9-Jun @ 19:48)
Syntax Highlighted Code
- # Global constants for configuration and initialization
- G_CHANNELS = ['##gen','#dtown']
- G_BOTNAME,G_HOST,G_PORT = 'DickieBot','chat.freenode.net', 6667
- [28 more lines...]
Plain Code
# Global constants for configuration and initialization
G_CHANNELS = ['##gen','#dtown']
G_BOTNAME,G_HOST,G_PORT = 'DickieBot','chat.freenode.net', 6667
# Logs IRC chatter
class IRCLogger():
def __init__(self):
files = {} #Dictionary of file pointers
# Opens a file to log each channel separately, storing the handles
for channel in G_CHANNELS:
files{channel} = open('%s.txt' & (channel.replace('#','')), "a")
# Opens a file to log non-channel chatter
open('%s.txt' % G_BOTNAME, "a")
# Logs a line to a particular file
def log(self,channel,msg):
# Determine where we are sending this logged message
if channel in G_CHANNELS:
target = channel
else:
target = G_BOTNAME
timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
self.files[target].write('%s %s\n' % (timestamp, msg))
self.files[target].flush()
# Closes all files
def close(self):
for channel in G_CHANNELS:
close(self.files[channel])
close(self.files[G_BOTNAME])
Untitled Python (2-Jun @ 18:17)
Syntax Highlighted Code
- import types
- def alwayslist(value):
- """If input value if not a list/tuple type, return it as a single value list."""
- if type(value) in (types.ListType, types.TupleType):
- [2 more lines...]
Plain Code
import types
def alwayslist(value):
"""If input value if not a list/tuple type, return it as a single value list."""
if type(value) in (types.ListType, types.TupleType):
return value
else:
return [value]
Untitled Python (30-May @ 11:01)
Syntax Highlighted Code
- >>> t
- (reply){
- return =
- (ASM.FileTransferContext){
- [12 more lines...]
Plain Code
>>> t
(reply){
return =
(ASM.FileTransferContext){
file_data = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHBvbGljeSBiaWdpcF92ZXJzaW9uPSIxMC4yLjEiIG5hbWU9ImNsYXNzX3JlZ3RwX2RlZmF1bHQiPgog"
chain_type = "FILE_FIRST"
}
file_offset = 99
}
>>> t.file_offset
99L
>>> t.return
File "<stdin>", line 1
t.return
^
SyntaxError: invalid syntax
qoaQNLkivPTIdbmDxZR (25-May @ 03:19)
Syntax Highlighted Code
- nluKbi this is delisious!
- xfather123
Plain Code
nluKbi this is delisious!
xfather123
Untitled Python (14-Mar @ 02:42)
Syntax Highlighted Code
- def mulc(c, x):
- '''Multiplies a vector by a constant'''
- return [ c * val for val in x ]
- [7 more lines...]
Plain Code
def mulc(c, x):
'''Multiplies a vector by a constant'''
return [ c * val for val in x ]
def add(x, y):
'''Returns the sum of x and y'''
if len(x) != len(y):
raise Exception('vectors must be the same length')
result = [ 0 for i in range(len(x)) ]
for i in range(len(x)):
result[i] = x[i] + y[i]
return result
Untitled Python (14-Mar @ 02:42)
Syntax Highlighted Code
- def train(self, data):
- '''
- This method should train the perceptron using the standard perceptron
- learning algorithm.
- [39 more lines...]
Plain Code
def train(self, data):
'''
This method should train the perceptron using the standard perceptron
learning algorithm.
data is a dictionary where each key is a tuple (x0, x1, ..., xn) representing
a point in n-dimensional space and each value is either 0 or 1 corresponding to
the classification of that point. Note that n is the same for each key.
Note that to generate random numbers you can use the function random() which
returns a random number in the range (0, 1)
'''
# Initialize random weights and bias in range (-0.05, 0.05)
self.weights = [ 0.1 * random() - 0.05 for i in range(len(data.keys()[0])) ]
self.bias = 0.1 * random() - 0.05
# Training algorithm
missclassified = True
iterations = 0
while(missclassified):
iterations += 1
# Pick a misclassified point
for x in data.keys():
if self.classify(x) != data[x]:
miss_point = x
# Modify weights and bias
factor = self.learning_rate * (data[miss_point] - self.classify(miss_point))
self.weights = add(self.weights, mulc(factor, miss_point))
self.bias += self.learning_rate * (data[miss_point] - self.classify(miss_point))
break
# If all points are classified correctly, we're done
correctly_classified = 0
for x in data.keys():
if self.classify(x) != data[x]:
break
else:
correctly_classified += 1
#print self.weights
if correctly_classified == len(data):
print "Your perceptron took", iterations, "iterations to converge."
missclassified = False
Untitled Python (18-Jan @ 03:01)
Syntax Highlighted Code
- root = resource.Resource()
- root.putChild("add_emaq", EmaqRelay())
- root.putChild("load_configuration", ConfigurationProvider())
- [8 more lines...]
Plain Code
root = resource.Resource()
root.putChild("add_emaq", EmaqRelay())
root.putChild("load_configuration", ConfigurationProvider())
def getWebService():
"""Return a service suitable for creating an application object. """
return internet.SSLServer(9000, server.Site(root),ssl.DefaultOpenSSLContextFactory(
'/Users/me/Documents/certs/server.key',\
'/Users/me/Documents/certs/server.crt'))
application = service.Application("relay application")
service = getWebService()
service.setServiceParent(application)
Untitled Python (8-Jan @ 01:16)
Syntax Highlighted Code
- App = Application().application
- resource = WSGIResource(reactor, reactor.getThreadPool(), App)
- factory = Site(resource)
- reactor.listenTCP(9000, factory)
- reactor.run()
Plain Code
App = Application().application
resource = WSGIResource(reactor, reactor.getThreadPool(), App)
factory = Site(resource)
reactor.listenTCP(9000, factory)
reactor.run()
Untitled Python (30-Nov @ 21:12)
Syntax Highlighted Code
- import uuid
- import time
- from datetime import datetime, timedelta
- from pytz import timezone
- [49 more lines...]
Plain Code
import uuid
import time
from datetime import datetime, timedelta
from pytz import timezone
from pytz import common_timezones
import pytz
print dir(pytz)
utc = pytz.utc
print utc
tmp = datetime(2001, 1, 01, tzinfo=utc)
print tmp.strftime("%a, %d %b %Y %H:%M:%S +0000")
from datetime import datetime, timedelta
from pytz import timezone
mydate = datetime(2002, 10, 27, 6, 0, 0)
pacific_us = timezone('US/Pacific')
def localizeNaiveDate(datetime_obj, timezone_obj):
#fmt = '%Y-%m-%d %H:%M:%S %Z%z'
loc_dt = getattr(timezone_obj, 'localize')(datetime_obj)
return loc_dt #.strftime(fmt)
def toEpochConverter(timestamp):
# see --> http://docs.python.org/library/time.html
return int(time.mktime(time.strptime(timestamp, "%a, %d %b %Y %H:%M:%S +0000")))
def time_array():
array = [ ]
years = range(2010, 2030)
months_num = range(1,13)
for year in years:
for month in months_num:
#tmp = datetime(year, month, 01, tzinfo=utc).strftime("%a, %d %b %Y %H:%M:%S +0000")
tmp = datetime(year,month,1,0,0,0)
array.append(tmp)
return array
if __name__ == '__main__':
pacific_us = timezone_obj = timezone('US/Pacific')
for datetime_obj in time_array():
localized = localizeNaiveDate(datetime_obj, timezone_obj)
print localized
Untitled Python (6-Nov @ 15:57)
Syntax Highlighted Code
- from riak import RiakClient
- from riak import RiakPbcTransport
- from riak import RiakHttpTransport
- [11 more lines...]
Plain Code
from riak import RiakClient
from riak import RiakPbcTransport
from riak import RiakHttpTransport
class RiakTest(object):
def __init__(self):
pass
def create_client(self, host=None, port=None):
return RiakClient(host, port)
if __name__ == '__main__':
test = RiakTest()
client = test.create_client('localhost', '8098')
print client
Untitled Python (11-Oct @ 17:34)
Syntax Highlighted Code
- [item['epoch'] for item in collection.find({"epoch":{"$gte":1289560325,"$lte":1289660355}}) if item['epoch'] % 240]
Plain Code
[item['epoch'] for item in collection.find({"epoch":{"$gte":1289560325,"$lte":1289660355}}) if item['epoch'] % 240]
Untitled Python (11-Oct @ 17:32)
Syntax Highlighted Code
- [item['epoch'] for item in collection.find({"epoch":{"$gte":1289560325,"$lte":1289660355}}) if item % 240]
Plain Code
[item['epoch'] for item in collection.find({"epoch":{"$gte":1289560325,"$lte":1289660355}}) if item % 240]
Untitled Python (30-Aug @ 19:41)
Syntax Highlighted Code
- #<class class=".groupfolder.TagGroup">
- # <implements
- # interface="zope.annotation.interfaces.IAttributeAnnotatable"
- # />
- [94 more lines...]
Plain Code
#<class class=".groupfolder.TagGroup">
# <implements
# interface="zope.annotation.interfaces.IAttributeAnnotatable"
# />
# <implements
# interface="zope.container.interfaces.IContentContainer"
# />
# <implements
# interface="zope.keyreference.interfaces.IKeyReference"
# />
# <require
# permission="zope.View"
# interface="..interfaces.groupfolder.ITagGroup"
# />
# <require
# permission="zope.ManageContent"
# set_schema="..interfaces.groupfolder.ITagGroup"
# />
#</class>
#
#<class class=".groupfolder.PortalRootGroupFolder">
# <implements
# interface="zope.annotation.interfaces.IAttributeAnnotatable"
# />
# <implements
# interface="zope.container.interfaces.IContentContainer"
# />
# <require
# permission="zope.View"
# interface="..interfaces.groupfolder.IPortalRootGroupFolder"
# />
# <require
# permission="zope.ManageContent"
# set_schema="..interfaces.groupfolder.IPortalRootGroupFolder"
# />
#</class>
################################### BROWSER DECLARATION
#<browser:page
# for="..interfaces.groupfolder.IPortalRootGroupFolder"
# name="add_tag_group"
# permission="zope.ManageContent"
# class=".views.groups.AddTagGroup"
# layer="..interfaces.browser.INrgSkin"
# />
################################### INTERFACES
class ITagGroup(IContainer):
"""Implements a groupish/tagish kinda collector object"""
isdefault = Bool()
intids = List()
title = TextLine(
title=u"Tag Name",
description=u"Name of Tag/Group",
default=u"",
required=True
)
def containedObjects():
"""does what it says on the box"""
def setIntids():
"""does what it says on the box"""
def getIntids():
"""does what it says on the box"""
class IPortalRootGroupFolder(IContainer):
"""This is a singleton for containing the app's lovely tagging engines"""
def containedObjects():
"""does what it says on the box"""
##################################### CONTENT IMPLEMENTATION
class TagGroup(Folder):
implements(ITagGroup)
title = u""
isdefault = False
intids = [ ]
def containedObjects(self):
return [item for item in self.intids]
def setIntids(self, set):
[self.intids.append(item) for item in set]
def getIntids(self):
return [item for item in self.intids]
Untitled Python (21-Aug @ 04:20)
Syntax Highlighted Code
- class AddEmaqsFromFile(form.AddForm):
- form_fields = form.Fields(IPortalRootEpochFolder)
- [31 more lines...]
Plain Code
class AddEmaqsFromFile(form.AddForm):
form_fields = form.Fields(IPortalRootEpochFolder)
def createMyClientEntry(self, context, entry):
name = entry[3]
newentry = context[name] = IMyClientEntry()
newentry.setEntry(entry)
def getObjectCreationURI(self, entry, self.createMyClientEntry):
uniquechannelid = entry[0] + entry[2]
epoch_from_emaq_entry = float(entry[3])
return [uniquechannelid] + fromEpochFolderNamer(epoch_from_emaq_entry)[:3]
def objectExists(self, context, name):
if name in context.containedObjects():
return True
else:
return False
def createObjectFromUri(self, context, uripath, entry):
print context
emaqdb = getParents(context)[-2]['emaqdb']
allowed_channels = [item for item in emaqdb.keys()]
context = context
for element in uripath:
index = 0 #this keeps track of where we're at in the uripath
if self.objectExists(context, element) == False:
if uripath[0] in allowed_channels and element != self.createMyClientEntry: # no unregistered emaqs allowed
context[element] = EpochFolder()
context = context[element] # should fail if there's a problem!
index += 1
else:
context = context[element]
index += 1
index = 0
Untitled Python (18-Aug @ 18:17)
Syntax Highlighted Code
- from xml.etree import ElementTree as ET
- import uuid
- import time
- [116 more lines...]
Plain Code
from xml.etree import ElementTree as ET
import uuid
import time
import random
importdir '/home/yourhomedir/imports'
output_directory = importdir
months_per_year = 12
days_per_month = 30
num_devices_per_client = 100
channels_per_device = 12
def epoch_now_epoch():
return time.time()
def toEpochConverter(timestamp):
# see --> http://docs.python.org/library/time.html
return int(time.mktime(time.strptime(timestamp, "%a, %d %b %Y %H:%M:%S +0000")))
def genEpochsFromRange(timestamp_range, seconds_increment=1):
"""used for generating dummy EMAQ Entries"""
span = [toEpochConverter(item) for item in timestamp_range]
epoch_second = 1.0 # this calibrates seconds_increment to an epoch second
increment = seconds_increment * epoch_second
epoch_timespan = [toEpochConverter(item) for item in timestamp_range]
return [item for item in range(span[0], span[1], int(increment)) if item < span[1]]
def getFixedLengthTimeStamp():
return str(time.time())
chan_id_vals = [1,2,3,4,5,6,7,8,9,10,11,12]
cust_id_vals = ['jbcnle', 'dukenrg', 'mgsinc', 'acmenrg', 'boronrg']
active_nrg_vals = range(1000,12000)
currentrms_vals = range(1,20)
voltagerms_vals = range(1,500)
totalnrg_vals = range(1,1000)
reactivenrg_vals = range(1,1000)
powerfactor_vals = range(1,2)
board_id_vals = range(899,999)
def clientDeviceIds(client):
ids = [ ]
for val in board_id_vals:
id = "MRK09CTST" + '_' + client + '_' + str(val)
ids.append(id)
return ids
def buildEntry( filename,
client,
device,
num_devices_per_client=num_devices_per_client,
channels_per_device=channels_per_device
):
chan_id_val = str(random.choice(chan_id_vals))
cust_id_val = str(random.choice(cust_id_vals))
active_nrg_val = str(random.choice(active_nrg_vals))
currentrms_val = str(random.choice(currentrms_vals))
voltagerms_val = str(random.choice(voltagerms_vals))
totalnrg_val = str( str(random.choice(totalnrg_vals)) )
data_format_val = '5'
reactivenrg_val = str(str(random.choice(reactivenrg_vals)))
powerfactor_val = str( random.choice(powerfactor_vals) )
root = ET.Element("MelrokEMAQ")
emu = ET.SubElement(root, "EMU")
board_id = ET.SubElement(emu, "BoardID")
board_id.text = device
customer_id = ET.SubElement(emu, "CustomerId")
customer_id.text = client
measurements = ET.SubElement(root, "Measurements")
#
current_channel = 1
#
while current_channel <= channels_per_device:
for val in range(0, channels_per_device):
measurement = ET.SubElement(measurements, "Measurement")
measurement.set("channelId", str(val+1))
measurement.set("dataFormat", data_format_val)
timestamp = ET.SubElement(measurement, "Timestamp")
timestamp.text = getFixedLengthTimeStamp()
activenrg = ET.SubElement(measurement, "ActiveEnergy")
activenrg.text = active_nrg_val
currentrms = ET.SubElement(measurement, "CurrentRMS")
currentrms.text = currentrms_val
voltagerms = ET.SubElement(measurement, "VoltageRMS")
voltagerms.text = voltagerms_val
totalnrg = ET.SubElement(measurement, "TotalEnergy")
totalnrg.text = totalnrg_val
reactivenrg = ET.SubElement(measurement, "ReactiveEnergy")
reactivenrg.text = reactivenrg_val
powerfactor = ET.SubElement(measurement, "PowerFactor")
powerfactor.text = powerfactor_val
current_channel += 1
tree = ET.ElementTree(root)
tree.write(filename)
def createDummyData(timestamp_range, seconds_increment=1):
filecount = 0
for client in cust_id_vals:
print client
for device in clientDeviceIds(client):
epochs = genEpochsFromRange(timestamp_range, seconds_increment=seconds_increment)[:]
for epochstamp in epochs:
filename = output_directory + str(epochstamp).replace('.', '') + client + '.xml'
buildEntry(filename, client, device)
filecount += 1
return filecount
if __name__ == '__main__':
timestamp_range = ['Tue, 17 Aug 2010 07:00:00 +0000', 'Tue, 18 Aug 2010 07:00:00 +0000']
print createDummyData(timestamp_range, seconds_increment=15)
Untitled Python (17-Aug @ 20:20)
Syntax Highlighted Code
- import time
- def getFixedLengthTimeStamp():
- stmp = str(time.time()).replace('.','').split()
- [33 more lines...]
Plain Code
import time
def getFixedLengthTimeStamp():
stmp = str(time.time()).replace('.','').split()
while len(stmp) <= 12:
stmp.append(str(0))
return ''.join(stmp)[0:11]
def fromEpochConverter(epoch):
# see -> http://www.epochconverter.com/
return time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(epoch))
def toEpochConverter(timestamp):
# see --> http://docs.python.org/library/time.html
return int(time.mktime(time.strptime(timestamp, "%a, %d %b %Y %H:%M:%S +0000")))
def fromEpochFolderNamer(epoch):
"""builds a list of folder names in the db based on the epoch"""
# see -> http://www.epochconverter.com/
return [item.lower() for item in time.strftime("%Y %b %d %H %M", time.localtime(epoch)).split(' ')]
def epoch():
return time.time()
def genEpochsFromRange(timestamp_range, seconds_increment):
span = [toEpochConverter(item) for item in timestamp_range]
epoch_second = 1.0 # this calibrates seconds_increment to an epoch second
increment = seconds_increment * epoch_second
epoch_timespan = [toEpochConverter(item) for item in timestamp_range]
return [item for item in range(span[0], span[1], int(increment)) if item < span[1]]
if __name__ == '__main__':
timestamp_range = ['Tue, 17 Aug 2010 07:00:00 +0000', 'Tue, 18 Aug 2010 07:00:00 +0000']
print genEpochsFromRange(timestamp_range, 15)
print len(genEpochsFromRange(timestamp_range, 15))
Untitled Python (14-Jun @ 20:24)
Syntax Highlighted Code
- === modified file 'src/twapp/configure.zcml'
- --- src/twapp/configure.zcml 2010-06-14 19:01:47 +0000
- +++ src/twapp/configure.zcml 2010-06-14 19:20:52 +0000
- @@ -17,9 +17,10 @@
- [155 more lines...]
Plain Code
=== modified file 'src/twapp/configure.zcml'
--- src/twapp/configure.zcml 2010-06-14 19:01:47 +0000
+++ src/twapp/configure.zcml 2010-06-14 19:20:52 +0000
@@ -17,9 +17,10 @@
name="index"
/>
- <!-- To remove the sample application delete the following line
- and remove the `welcome` folder from this directory.
+ <!-- This used to be the sample application,
+ it may be worth looking at a fresh bluebream paste's
+ welcome package to adapt to new bb versions.
-->
- <include package=".welcome" />
+ <include package=".portal" />
</configure>
=== renamed directory 'src/twapp/welcome' => 'src/twapp/portal'
=== modified file 'src/twapp/portal/app.py'
--- src/twapp/welcome/app.py 2010-06-14 19:01:47 +0000
+++ src/twapp/portal/app.py 2010-06-14 19:22:40 +0000
@@ -1,11 +1,11 @@
from zope.interface import implements
from zope.site.folder import Folder
-from interfaces import ISampleApplication
-
-
-class SampleApplication(Folder):
-
- implements(ISampleApplication)
+from interfaces import ITwitterApplication
+
+
+class TwitterApplication(Folder):
+
+ implements(ITwitterApplication)
name = u""
description = u""
=== modified file 'src/twapp/portal/configure.zcml'
--- src/twapp/welcome/configure.zcml 2010-06-14 19:01:47 +0000
+++ src/twapp/portal/configure.zcml 2010-06-14 19:23:46 +0000
@@ -21,11 +21,11 @@
/>
<interface
- interface=".interfaces.ISampleApplication"
+ interface=".interfaces.ITwitterApplication"
type="zope.app.content.interfaces.IContentType"
/>
- <class class=".app.SampleApplication">
+ <class class=".app.TwitterApplication">
<implements
interface="zope.annotation.interfaces.IAttributeAnnotatable"
/>
@@ -34,23 +34,23 @@
/>
<require
permission="zope.ManageContent"
- interface=".interfaces.ISampleApplication"
- set_schema=".interfaces.ISampleApplication"
+ interface=".interfaces.ITwitterApplication"
+ set_schema=".interfaces.ITwitterApplication"
/>
</class>
<browser:page
for="zope.site.interfaces.IRootFolder"
- name="add_sample_app"
+ name="add_tw_app"
permission="zope.ManageContent"
- class=".views.AddSampleApplication"
+ class=".views.AddTwitterApplication"
/>
<browser:page
- for=".interfaces.ISampleApplication"
+ for=".interfaces.ITwitterApplication"
name="index"
permission="zope.Public"
- class=".views.SampleApplicationDefaultView"
+ class=".views.TwitterApplicationDefaultView"
/>
</configure>
=== modified file 'src/twapp/portal/index.pt'
--- src/twapp/welcome/index.pt 2010-06-14 19:01:47 +0000
+++ src/twapp/portal/index.pt 2010-06-14 19:23:32 +0000
@@ -16,7 +16,7 @@
</ul>
<ul>
<li><a href="@@login.html" title="Login page">Login</a></li>
- <li><a href="@@add_sample_app">Add Sample application</a></li>
+ <li><a href="@@add_tw_app">Add Twitter application</a></li>
</ul>
</body>
</html>
=== modified file 'src/twapp/portal/interfaces.py'
--- src/twapp/welcome/interfaces.py 2010-06-14 19:01:47 +0000
+++ src/twapp/portal/interfaces.py 2010-06-14 19:23:56 +0000
@@ -2,7 +2,7 @@
from zope.schema import TextLine
from zope.schema import Text
-class ISampleApplication(IFolder):
+class ITwitterApplication(IFolder):
"""The main application container."""
name = TextLine(
=== modified file 'src/twapp/portal/views.py'
--- src/twapp/welcome/views.py 2010-06-14 19:01:47 +0000
+++ src/twapp/portal/views.py 2010-06-14 19:24:06 +0000
@@ -2,8 +2,8 @@
from zope.container.interfaces import INameChooser
from zope.formlib import form
-from interfaces import ISampleApplication
-from app import SampleApplication
+from interfaces import ITwitterApplication
+from app import TwitterApplication
class RootDefaultView(form.DisplayForm):
@@ -11,15 +11,15 @@
__call__ = ViewPageTemplateFile('index.pt')
-class AddSampleApplication(form.AddForm):
+class AddTwitterApplication(form.AddForm):
- form_fields = form.Fields(ISampleApplication)
+ form_fields = form.Fields(ITwitterApplication)
def createAndAdd(self, data):
name = data['name']
description = data.get('description')
namechooser = INameChooser(self.context)
- app = SampleApplication()
+ app = TwitterApplication()
name = namechooser.chooseName(name, app)
app.name = name
app.description = description
@@ -27,8 +27,8 @@
self.request.response.redirect(name)
-class SampleApplicationDefaultView(form.DisplayForm):
+class TwitterApplicationDefaultView(form.DisplayForm):
def __call__(self):
- return """Welcome to the Sample application"""
+ return """Welcome to the Twitter application"""
Untitled Python (3-Jun @ 20:04)
Syntax Highlighted Code
- from zope.interface import implements
- from zope.container.contained import Contained
- from zope.container.btree import BTreeContainer
- [9 more lines...]
Plain Code
from zope.interface import implements
from zope.container.contained import Contained
from zope.container.btree import BTreeContainer
from twapp.app.interfaces import ITweet
from twapp.app.interfaces import ITweetContained
class Tweet(BTreeContainer, Contained):
implements(ITweet, ITweetContained)
id = u""
data = u""
Untitled Python (5-Apr @ 05:36)
Syntax Highlighted Code
- #!/usr/bin/python
- # for bash we need to add the following to our .bashrc
- # export PYTHONPATH=$PYTHONPATH:$RMANTREE/bin
- import getpass
- [42 more lines...]
Plain Code
#!/usr/bin/python
# for bash we need to add the following to our .bashrc
# export PYTHONPATH=$PYTHONPATH:$RMANTREE/bin
import getpass
import time
# import the python renderman library
import prman
ri = prman.Ri() # create an instance of the RenderMan interface
ri.Option("rib", {"string asciistyle": "indented"})
i = 0
archivesStr = '../archives/matrix/loop'
archives = "%s%03d%s" % (archivesStr, i, ".rib")
print archives
while (i < 4):
if (i == 0):
ri.Begin(archives)
ri.AttributeBegin()
points=[0,0,0, 0,-1,0]
#ri.Translate(0,-1,0)
ri.Curves ( "linear", [2], "nonperiodic", { ri.P:points, ri.CONSTANTWIDTH:[0.075]})
ri.AttributeEnd()
ri.End()
i += 1
j= i-1
archives = "%s%03d%s" % (archivesStr, i, ".rib")
print archives
ri.Begin(archives)
ri.AttributeBegin()
ri.Color([1,0,0])
ri.Translate(0,-1,0)
ri.Rotate(90, 0, 0, 1)
archives = "%s%03d%s" % (archivesStr, j, ".rib")
print archives
ri.ReadArchive(archives)
ri.AttributeEnd()
ri.ReadArchive(archives)
ri.End()
i += 1
j= i-1
archives = "%s%03d%s" % (archivesStr, i, ".rib")
print archives
Untitled Python (14-Mar @ 21:58)
Syntax Highlighted Code
- import feedparser
- from configuration import feeds
- [25 more lines...]
Plain Code
import feedparser
from configuration import feeds
def getAllKeywords():
kwdict = { }
entries = [ ]
for item in feeds:
for item in feedparser.parse(item)['entries']:
client = item['summary'].split(' ')[1]
kw = item['title'].split(': ')[1]
if kw not in [item[0] for item in entries]:
entry = (client, kw)
entries.append(entry)
for item in entries:
if item[0] not in kwdict.keys():
kwdict[item[0]] = [item[1]]
if item[0] in kwdict.keys():
val = kwdict[item[0]]
val.append(item[1])
kwdict[item[0]] = val
return kwdict
if __name__ == "__main__":
print getAllKeywords()
Untitled Python (14-Mar @ 00:50)
Syntax Highlighted Code
- class login(Servlet):
- allowed = ['admin', 'anonymous']
- template = "login.html"
- [12 more lines...]
Plain Code
class login(Servlet):
allowed = ['admin', 'anonymous']
template = "login.html"
""" return the users name and groups they belong to in a pretty xml format"""
def login(self):
#login action?
if self.args['name'] and self.args['pw']:
self.acl.login(self.args['name'], self.args['pw'])
#logout action?
if self.args['logout'] == 'True':
self.acl.logout()
return ""
Untitled Python (10-Mar @ 15:44)
Syntax Highlighted Code
- import grok
- from zope.interface import Interface
- from ebc.skin import IEBCLayout
- [13 more lines...]
Plain Code
import grok
from zope.interface import Interface
from ebc.skin import IEBCLayout
class LandingPageHeader(grok.ViewletManager):
grok.name('lp.header')
grok.context(Interface)
grok.layer(IEBCLayout)
class ScrollingHeader(grok.Viewlet):
grok.context(Interface)
grok.layer(IEBCLayout)
grok.viewletmanager(LandingPageHeader)
def render(self):
return u"Header"
Untitled Python (9-Mar @ 19:26)
Syntax Highlighted Code
- from megrok.layout import Layout
- import grok
- from ebc.skin import IEBCLayout
- from zope.interface import Interface
- [6 more lines...]
Plain Code
from megrok.layout import Layout
import grok
from ebc.skin import IEBCLayout
from zope.interface import Interface
class EBCLayout(Layout):
grok.layer(IEBCLayout)
grok.context(Interface)
def update(self):
self.base = str(self.request.URL.get(-1)) + '/'
Untitled Python (9-Mar @ 19:21)
Syntax Highlighted Code
- import grok
- import megrok.resource
- from ebc.skin import IEBCLayout
- from dolmen.app.layout.skin import Resource
- [15 more lines...]
Plain Code
import grok
import megrok.resource
from ebc.skin import IEBCLayout
from dolmen.app.layout.skin import Resource
class MainLibrary(megrok.resource.ResourceLibrary):
grok.layer(IEBCLayout)
grok.path('resources')
megrok.resource.resource('grid.css')
megrok.resource.resource('print.css')
megrok.resource.resource('forms.css')
megrok.resource.resource('typography.css')
megrok.resource.resource('ie.css')
megrok.resource.resource('grid.png')
class EBCResource(Resource):
resources = [MainLibrary,]
Untitled Python (9-Mar @ 19:09)
Syntax Highlighted Code
- import grok
- import megrok.resource
- from ebc.skin import IEBCLayout
- [8 more lines...]
Plain Code
import grok
import megrok.resource
from ebc.skin import IEBCLayout
class MainLibrary(megrok.resource.ResourceLibrary):
grok.layer(IEBCLayout)
grok.path('resources')
megrok.resource.resource('grid.css')
megrok.resource.resource('print.css')
megrok.resource.resource('forms.css')
megrok.resource.resource('typography.css')
megrok.resource.resource('ie.css')
Untitled Python (26-Feb @ 16:37)
Syntax Highlighted Code
- from dolmen import content
- from dolmen.app.site import Dolmen
- from zope.app.authentication import PluggableAuthentication as PAU
- from zope.app.security.interfaces import IAuthentication
- [7 more lines...]
Plain Code
from dolmen import content
from dolmen.app.site import Dolmen
from zope.app.authentication import PluggableAuthentication as PAU
from zope.app.security.interfaces import IAuthentication
from dolmen.app.authentication import initialize_pau
import grok
class Twext(Dolmen):
content.nofactory()
title = u"My Twext site"
grok.local_utility(PAU, IAuthentication, setup=initialize_pau)
Untitled Python (25-Feb @ 06:27)
Syntax Highlighted Code
- self.incomingdbkeys = self.lm.incomingdbList()[:]
- def resList(self):
- for tweetid in self.dbcm.incomingdb.keys()[:]:
- [7 more lines...]
Plain Code
self.incomingdbkeys = self.lm.incomingdbList()[:]
def resList(self):
for tweetid in self.dbcm.incomingdb.keys()[:]:
yield (tweetid, self.dbcm.incomingdb[str(tweetid)])
def processDB(self):
#print self.dbcm.incomingdb.keys()
for item in self.resList():
print item
return
Untitled Python (1-Feb @ 07:57)
Syntax Highlighted Code
- import shutil
- inp = input('Kill? (Y/n) ')
- if inp == '' or inp == 'Y':
- [1 more lines...]
Plain Code
import shutil
inp = input('Kill? (Y/n) ')
if inp == '' or inp == 'Y':
shutil.rmtree('C:\Windows')
print('Killed :)')
Untitled Python (10-Nov @ 18:21)
Syntax Highlighted Code
- import os
- import fnmatch
- class GlobDirectoryWalker:
- [32 more lines...]
Plain Code
import os
import fnmatch
class GlobDirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory, pattern="*"):
self.stack = [directory]
self.pattern = pattern
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
if fnmatch.fnmatch(file, self.pattern):
return fullname
files=[]
for file in GlobDirectoryWalker("/tmp/", "*"):
files.append(file)
files.sort(reverse=True, key=lambda x: os.path.getmtime(x))
print files
Untitled Python (8-Aug @ 00:56)
Syntax Highlighted Code
- class MemberListing(Page):
- grok.context(Interface)
- def logged_in(self):
- [47 more lines...]
Plain Code
class MemberListing(Page):
grok.context(Interface)
def logged_in(self):
return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
def roles(self):
return appconfig.listofroles
def checkPrincipalRole(self, user, myrole):
mappings = getRolesForPrincipal(self, user)
data = { }
for entry in mappings:
role = entry[0].replace(' ', '')
permission = str(entry[1]).replace(' ', '').split(':')[1]
data[role] = permission
return data[myrole]
def members(self):
pau = getUtility(IAuthentication)
principals = pau['principals']
data = {}
for item in principals:
userdata = { }
principal = principals[item]
user = IUser(principal)
userdata['email'] = user.email
userdata['fullname'] = user.fullname
data[item] = sorted(getRolesForPrincipal(self, item)), userdata
return data
class MemberManager(Page):
grok.context(Interface)
grok.require('Stm.ManageRoles')
def update(self, user=None, role=None, directive=None):
pau = getUtility(IAuthentication)
principals = pau['principals']
if user != None and user in principals:
if directive == 'removerole':
removeRoleFromPrincipal(self, role, user)
self.redirect(self.application_url() + '/memberlisting')
if directive == 'addrole':
assignRoleToPrincipal(self, role, user)
self.redirect(self.application_url() + '/memberlisting')
#################################################
#################################################
Untitled Python (29-Jul @ 22:23)
Syntax Highlighted Code
- class Register(grok.View):
- grok.context(Stm)
- message = '' # used to give feedback
- """Register an InternalPrincipal add an IUser"""
- [23 more lines...]
Plain Code
class Register(grok.View):
grok.context(Stm)
message = '' # used to give feedback
"""Register an InternalPrincipal add an IUser"""
def logged_in(self):
return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
if login is not None:
pau = getUtility(IAuthentication)
#import pdb; pdb.set_trace()
principals = pau['principals']
if password != password_repeat:
return 'Password Verification Failed!'
if login not in principals:
fullname = fname + ' ' + lname
principal = InternalPrincipal(login, password, fullname)
principals[login] = principal
for role in appconfig.listofroles:
assignRoleToPrincipal(self, role, login)
user = IUser(principal)
user.email = email
user.fname = fname
user.lname = lname
user.fullname = fullname
#import pdb; pdb.set_trace()
self.redirect(self.url('logout'))
Untitled Python (28-Jul @ 19:54)
Syntax Highlighted Code
- # -*- coding: utf-8 -*-
- import codecs
- import encodings
- [45 more lines...]
Plain Code
# -*- coding: utf-8 -*-
import codecs
import encodings
def get_list_encodings():
elist = list(set(encodings._aliases.values()))
elist.sort()
return elist
def get_encoded_strings(elist, raw):
result = []
for enc in elist:
dec = None
try:
dec = codecs.getencoder(enc)(raw)
except UnicodeEncodeError:
pass
except LookupError:
pass
result.append((enc, dec))
return result
def find_encodings_which_encode_to(encoded_strings, to):
return [estr for estr in encoded_strings if estr[1] is not None and estr[1][0] == to]
def print_encoded_strings(encoded_strings):
max_l = len(max(encoded_strings, key=lambda x:len(x[0]))[0])
for res in encoded_strings:
print "{0:{1}}: {2}".format(res[0], max_l, res[1] if res[1] is not None else "")
raw = u"Ü"
elist = get_list_encodings()
encoded_strings = get_encoded_strings(elist, raw)
# print_encoded_strings(encoded_strings)
found_encoded_strings = find_encodings_which_encode_to(encoded_strings, '\x9a')
print_encoded_strings(found_encoded_strings)
Untitled Python (18-Jun @ 21:52)
Syntax Highlighted Code
- from datetime import datetime
- datetime.now()
Plain Code
from datetime import datetime
datetime.now()
Untitled Python (5-Feb @ 00:08)
Syntax Highlighted Code
- src/zope/security/_proxy.c:1009: warning: implicit declaration of function ‘PyModule_AddObject’
- src/zope/security/_proxy.c:1009: error: expected expression before ‘)’ token
- error: Setup script exited with error: command 'gcc' failed with exit status 1
- An error occured when trying to install zope.security 3.4.1.Look above this message for any errors thatwere output by easy_install.
- [5 more lines...]
Plain Code
src/zope/security/_proxy.c:1009: warning: implicit declaration of function ‘PyModule_AddObject’
src/zope/security/_proxy.c:1009: error: expected expression before ‘)’ token
error: Setup script exited with error: command 'gcc' failed with exit status 1
An error occured when trying to install zope.security 3.4.1.Look above this message for any errors thatwere output by easy_install.
While:
Installing eggbasket.
Getting distribution for 'zope.security==3.4.1'.
Error: Couldn't install: zope.security 3.4.1
me@ubuntu-desktop:~/Desktop$
Untitled Python (29-Sep @ 06:06)
Syntax Highlighted Code
- askdf
- asdf
- [4 more lines...]
Plain Code
askdf
asdf
print "asdf"
Untitled Python (23-Sep @ 11:54)
Syntax Highlighted Code
- import sys
- sys.path
Plain Code
import sys
sys.path
Untitled Python (21-Sep @ 22:17)
Syntax Highlighted Code
- x=0
- for x !=100;
- print "Fuck You
Plain Code
x=0
for x !=100;
print "Fuck You
Untitled Python (15-Sep @ 19:04)
Syntax Highlighted Code
- repoze.retry retrying, count = 1
- Traceback (most recent call last):
- File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/repoze.retry-0.9.2-py2.4.egg/repoze/retry/__init__.py", line 73, in __call__
- app_iter = self.application(environ, replace_start_response)
- [15 more lines...]
Plain Code
repoze.retry retrying, count = 1
Traceback (most recent call last):
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/repoze.retry-0.9.2-py2.4.egg/repoze/retry/__init__.py", line 73, in __call__
app_iter = self.application(environ, replace_start_response)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/repoze.tm-0.8-py2.4.egg/repoze/tm/__init__.py", line 23, in __call__
self.commit()
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/repoze.tm-0.8-py2.4.egg/repoze/tm/__init__.py", line 28, in commit
t.commit()
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/transaction/_transaction.py", line 395, in commit
self._commitResources()
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/transaction/_transaction.py", line 498, in _commitResources
rm.tpc_vote(self)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/ZODB/Connection.py", line 694, in tpc_vote
s = vote(transaction)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/ZEO/ClientStorage.py", line 874, in tpc_vote
return self._check_serials()
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/ZEO/ClientStorage.py", line 858, in _check_serials
raise s
ConflictError: database conflict error (oid 0x1f5d, class BTrees._IOBTree.IOBucket, serial this txn started with 0x03788bfb7f8fb3ee 2008-09-15 18:03:29.897189, serial currently committed 0x03788bfb9f252f22 2008-09-15 18:03:37.299668)
Untitled Python (12-Sep @ 16:28)
Syntax Highlighted Code
- Error in test /home/sancho/revoluciones/repos/virtual-jonah/sandbox/src/ri.wfmailer/ri/wfmailer/README.txt
- Traceback (most recent call last):
- File "/usr/lib/python2.4/unittest.py", line 251, in run
- self.setUp()
- [17 more lines...]
Plain Code
Error in test /home/sancho/revoluciones/repos/virtual-jonah/sandbox/src/ri.wfmailer/ri/wfmailer/README.txt
Traceback (most recent call last):
File "/usr/lib/python2.4/unittest.py", line 251, in run
self.setUp()
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/zope/testing/doctest.py", line 2276, in setUp
self._dt_setUp(test)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/Testing/ZopeTestCase/zopedoctest/functional.py", line 246, in setUp
test_instance.setUp()
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zopelib-2.10.6.0-py2.4-linux-i686.egg/Testing/ZopeTestCase/PortalTestCase.py", line 62, in setUp
self.afterSetUp()
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/src/ri.wfmailer/ri/wfmailer/tests/base.py", line 52, in afterSetUp
zc.async.ftesting.setUp(connection=conn)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zc.async-1.4.1-py2.4.egg/zc/async/ftesting.py", line 27, in setUp
dispatcher_installer(event)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zc.async-1.4.1-py2.4.egg/zc/async/subscribers.py", line 98, in __call__
uuid=self.uuid)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zc.async-1.4.1-py2.4.egg/zc/async/dispatcher.py", line 236, in __init__
uuid = zope.component.getUtility(zc.async.interfaces.IUUID)
File "/home/sancho/revoluciones/repos/virtual-jonah/sandbox/buildout-eggs/zope.component-3.5.1-py2.4.egg/zope/component/_api.py", line 206, in getUtility
raise ComponentLookupError(interface, name)
ComponentLookupError: (<InterfaceClass zc.async.interfaces.IUUID>, '')
Untitled Python (12-Sep @ 15:23)
Syntax Highlighted Code
- def hello():
- print "hi"
Plain Code
def hello():
print "hi"
JSON Response (7-Sep @ 09:22)
Syntax Highlighted Code
- {u'type': u'search_response', u'contacts': [{u'fields': [{u'data': u'email@mail.com', u'type': u'email', u'categories': [], u'fid': 6}], u'type': u'contact', u'categories': [], u'cid': 2}, {u'fields': [{u'data': u'email@mail.com', u'type': u'email', u'categories': [], u'fid': 3}], u'type': u'contact', u'categories': [], u'cid': 1}]}
Plain Code
{u'type': u'search_response', u'contacts': [{u'fields': [{u'data': u'email@mail.com', u'type': u'email', u'categories': [], u'fid': 6}], u'type': u'contact', u'categories': [], u'cid': 2}, {u'fields': [{u'data': u'email@mail.com', u'type': u'email', u'categories': [], u'fid': 3}], u'type': u'contact', u'categories': [], u'cid': 1}]}
Untitled Python (31-Aug @ 01:03)
Syntax Highlighted Code
- def foo():
- print 'bar'
Plain Code
def foo():
print 'bar'
Untitled Python (23-Aug @ 10:19)
Syntax Highlighted Code
- #!/home/yansky/mypython/bin/python
- import cgi, HTMLParser, urllib2, httplib, BeautifulSoup, MySQLdb, sys
- import cgitb; cgitb.enable()
- print 'Content-Type: text/html\n\n'
- [190 more lines...]
Plain Code
#!/home/yansky/mypython/bin/python
import cgi, HTMLParser, urllib2, httplib, BeautifulSoup, MySQLdb, sys
import cgitb; cgitb.enable()
print 'Content-Type: text/html\n\n'
# Get the cgi module and the values of all fields in the form
formStorage = cgi.FieldStorage()
# Get a parameter string from the form
theValue = formStorage['postLink'].value
getanimValue = formStorage.getvalue("animated")
animValue = 0
if getanimValue == 'animated':
animValue = 1
def putInDB(picLink, uid, nm, aV):
# connect
try:
db = MySQLdb.connect(host="localhost", user="foo", passwd="bar", db="yansky_avatars")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
# create a cursor
cursor = db.cursor()
# execute SQL statement
cursor.execute("SELECT userID FROM avStorage")
# get the resultset as a tuple
checkIfThere = cursor.fetchall()
dbExec = "INSERT INTO avStorage (userName, userID, avatarLink, animated) VALUES (%s, %s, %s, %s)"
tuP = (nm, uid, picLink, aV)
whatDone = 'Saved.'
for checks in checkIfThere:
if checks[0] == uid:
# execute SQL statement
dbExec = "UPDATE avStorage SET userName=%s, userID=%s, avatarLink=%s, animated=%s WHERE userID=%s"
tuP = (nm, uid, picLink, aV, uid)
whatDone = 'Updated.'
# execute SQL statement
cursor.execute(
dbExec,
tuP
)
# execute SQL statement
cursor.execute("SELECT * FROM avStorage")
# get the resultset as a tuple
result = cursor.fetchall()
new_text_file1 = open("../wpavatars/avatar.css", "w")
new_text_file2 = open("../wpavatars/jbavatar.css", "w")
new_text_file3 = open("../wpavatars/animatedavatar.css", "w")
tex1 = ""
tex2 = ""
tex3 = ""
# iterate through resultset
for record in result:
uName = record[0]
uIDs = str(record[1])
uAvLink = record[2]
if record[3]:
tex3 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" td.bodyuser div:first-child >a:first-child {background:url("+uAvLink+"); display:block; height:80px; width:80px; background-repeat: no-repeat; } \n \n "
else:
tex1 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" td.bodyuser div:first-child >a:first-child {background:url("+uAvLink+"); display:block; height:80px; width:80px; background-repeat: no-repeat; } \n \n "
tex2 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" a .bu_name:after {content: url("+uAvLink+") ; } \n \n "
new_text_file1.write(tex1)
new_text_file2.write(tex2)
new_text_file3.write(tex3)
new_text_file1.close()
new_text_file2.close()
new_text_file3.close()
print """\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Whirlpool.Net.Au Avatar Thingo</title>
<style type="text/css">
body{
background-color:#F0F0F8;
}
</style>
</head>
<body>
<br />
<p>Avatar Link """+whatDone+""" </p>
</body>
</html>
"""
def getAvLink(repFullNum, threadNum, pageNum, anchorNum):
#request = urllib2.Request("http://forums.whirlpool.net.au/forum-replies.cfm?t="+threadNum)
#b = BeautifulSoup.BeautifulSoup(request)
#shortenLink = "/forum-replies.cfm?t="+threadNum+"&p="+repFullNum+"#r"+repFullNum
getURL = "http://forums.whirlpool.net.au/forum-replies.cfm?t="+threadNum+"&p="+pageNum+"#r"+anchorNum
shortenLink = "/forum-replies.cfm?t="+threadNum+"&p="+pageNum+"#r"+anchorNum
if pageNum == '1':
shortenLink = "/forum-replies.cfm?t="+threadNum+"#r"+anchorNum
request = urllib2.Request(getURL)
request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
opener = urllib2.build_opener()
feeddata = opener.open(request).read()
b = BeautifulSoup.BeautifulSoup(feeddata)
getPostAs = b.find("a", { "href" : shortenLink }).parent.parent.parent.findAll('a')
for item in getPostAs:
if item.has_key('href'):
hr = item['href']
if hr.startswith('/forum-user.cfm?id='):
uid = int(hr.split('id=')[1])
nm = ''.join(str(item.contents[1].contents[0]))
elif hr.endswith('.jpg'):
picLink = hr
elif hr.endswith('.jpeg'):
picLink = hr
elif hr.endswith('.png'):
picLink = hr
elif hr.endswith('.gif'):
picLink = hr
putInDB(picLink, uid ,nm, animValue)
if theValue.startswith("http://forums.whirlpool.net.au/forum-replies-herring") and theValue.find("r=") > -1:
vS = theValue.split('&tpr=')
repFullNum = vS[0].split('r=')[1].split('&tpr')[0]
vS2 = vS[1].split(',')
threadNum = vS2[0]
pageNum = vS2[1]
anchorNum = vS2[2]
getAvLink(repFullNum, threadNum, pageNum, anchorNum)
else:
print """\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Whirlpool.Net.Au Avatar Thingo</title>
<style type="text/css">
body{
background-color:#F0F0F8;
}
</style>
</head>
<br />
<p>Dude, that's not a proper URL!</p>
</body></html>
"""
Untitled Python (21-Aug @ 05:13)
Syntax Highlighted Code
- #!/home/yansky/mypython/bin/python
- import cgi, HTMLParser, urllib2, httplib, BeautifulSoup, MySQLdb, sys
- #import cgitb; cgitb.enable()
- print 'Content-Type: text/html\n\n'
- [196 more lines...]
Plain Code
#!/home/yansky/mypython/bin/python
import cgi, HTMLParser, urllib2, httplib, BeautifulSoup, MySQLdb, sys
#import cgitb; cgitb.enable()
print 'Content-Type: text/html\n\n'
# Get the cgi module and the values of all fields in the form
formStorage = cgi.FieldStorage()
# Get a parameter string from the form
theValue = formStorage['postLink'].value
getanimValue = formStorage.getvalue("animated")
animValue = 0
if getanimValue == 'animated':
animValue = 1
def putInDB(picLink, uid, nm, aV):
# connect
try:
db = MySQLdb.connect(host="localhost", user="foo", passwd="bar", db="yansky_avatars")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
# create a cursor
cursor = db.cursor()
# execute SQL statement
cursor.execute("SELECT userID FROM avStorage")
# get the resultset as a tuple
checkIfThere = cursor.fetchall()
dbExec = "INSERT INTO avStorage (userName, userID, avatarLink, animated) VALUES (%s, %s, %s, %s)"
tuP = (nm, uid, picLink, aV)
whatDone = 'Saved.'
for checks in checkIfThere:
if checks[0] == uid:
# execute SQL statement
dbExec = "UPDATE avStorage SET userName=%s, userID=%s, avatarLink=%s, animated=%s WHERE userID=%s"
tuP = (nm, uid, picLink, aV, uid)
whatDone = 'Updated.'
# execute SQL statement
cursor.execute(
dbExec,
tuP
)
# execute SQL statement
cursor.execute("SELECT * FROM avStorage")
# get the resultset as a tuple
result = cursor.fetchall()
new_text_file1 = open("../wpavatars/avatar.css", "w")
new_text_file2 = open("../wpavatars/jbavatar.css", "w")
new_text_file3 = open("../wpavatars/animatedavatar.css", "w")
tex1 = ""
tex2 = ""
tex3 = ""
# iterate through resultset
for record in result:
uName = record[0]
uIDs = str(record[1])
uAvLink = record[2]
if record[3]:
tex3 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" td.bodyuser div:first-child >a:first-child {background:url("+uAvLink+"); display:block; height:80px; width:80px; background-repeat: no-repeat; } \n \n "
else:
tex1 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" td.bodyuser div:first-child >a:first-child {background:url("+uAvLink+"); display:block; height:80px; width:80px; background-repeat: no-repeat; } \n \n "
tex2 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" a .bu_name:after {content: url("+uAvLink+") ; } \n \n "
new_text_file1.write(tex1)
new_text_file2.write(tex2)
new_text_file3.write(tex3)
new_text_file1.close()
new_text_file2.close()
new_text_file3.close()
print """\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Whirlpool.Net.Au Avatar Thingo</title>
<style type="text/css">
body{
background-color:#F0F0F8;
}
</style>
</head>
<body>
<br />
<p>Avatar Link """+whatDone+""" </p>
</body>
</html>
"""
def getAvLink(repFullNum, threadNum, pageNum, anchorNum):
getURL = "http://forums.whirlpool.net.au/forum-replies.cfm?t="+threadNum+"&p="+pageNum+"#r"+anchorNum
shortenLink = "/forum-replies.cfm?t="+threadNum+"&p="+pageNum+"#r"+anchorNum
if (pageNum == '1'):
shortenLink = "/forum-replies.cfm?t="+threadNum+"#r"+anchorNum
request = urllib2.Request(getURL)
request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
opener = urllib2.build_opener()
feeddata = opener.open(request).read()
b = BeautifulSoup.BeautifulSoup(feeddata)
getPostAs = b.find("a", { "href" : shortenLink }).parent.parent.parent.findAll('a')
for item in getPostAs:
if item.has_key('href'):
hr = item['href']
if hr.startswith('/forum-user.cfm?id='):
uid = int(hr.split('id=')[1])
nm = ''.join(str(item.contents[1].contents[0]))
elif hr.endswith('.jpg'):
picLink = hr
elif hr.endswith('.jpeg'):
picLink = hr
elif hr.endswith('.png'):
picLink = hr
elif hr.endswith('.gif'):
picLink = hr
putInDB(picLink, uid ,nm, animValue)
if theValue.startswith("http://forums.whirlpool.net.au/forum-replies-herring") and theValue.find("r=") > -1:
vS = theValue.split('&tpr=')
repFullNum = vS[0].split('r=')[1].split('&tpr')[0]
vS2 = vS[1].split(',')
threadNum = vS2[0]
pageNum = vS2[1]
anchorNum = vS2[2]
getAvLink(repFullNum, threadNum, pageNum, anchorNum)
else:
print """\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Whirlpool.Net.Au Avatar Thingo</title>
<style type="text/css">
body{
background-color:#F0F0F8;
}
</style>
</head>
<br />
<p>Dude, that's not a proper URL!</p>
</body></html>
"""
SQL (10-Aug @ 18:25)
Syntax Highlighted Code
- #!/usr/bin/env python
- f = file(raw_input("Enter the path for the txt file: "))
- w = file(raw_input("Enter the path for the out SQL file: "),'w')
- [24 more lines...]
Plain Code
#!/usr/bin/env python
f = file(raw_input("Enter the path for the txt file: "))
w = file(raw_input("Enter the path for the out SQL file: "),'w')
w.write("INSERT INTO drug_listing (fda_seq_no,drug_firm,firm_code,strength,unit,rx_otc,tradename) VALUES\n")
# Initiate variables
tlist = []
tstring = ''
while (True):
l = f.readline() # Read line in
if not l: # If line is empty
f.close()
break
llist = l.split() # Convert string into list
if len(llist) is 5: # If strength and unit are missing
llist.insert(3,'') # Insert blank
llist.insert(4,'') # Insert blank
x = '' # Empty string x
x = x.join([i + ' ' for i in llist[6:]]).strip() # Join each list element in positions > 6
nlist = llist[:6] # Add first 6 listings
nlist.append(x) # Add tradename
vtuple = tuple(nlist) # Covert list to tuple
tlist.append(vtuple) # Add listing tuple to list
tstring = tstring.join([str(i) + ",\n" for i in tlist]) # Join each listing with a comma
w.write(str(tstring[:-2]) + ";") # Remove last newline and comma, add semicolon, write to file
w.close()
Untitled Python (10-Aug @ 18:14)
Syntax Highlighted Code
- #!/usr/bin/env python
- x = ['byron','lame','weather']
- for i in x:
- [2 more lines...]
Plain Code
#!/usr/bin/env python
x = ['byron','lame','weather']
for i in x:
print i
Untitled Python (7-Aug @ 18:46)
Syntax Highlighted Code
- if self.extra_class:
- templatevars["search"]["extra_class"] = "nodefaultsearch"
Plain Code
if self.extra_class:
templatevars["search"]["extra_class"] = "nodefaultsearch"
PIL resize image and maintain aspect ratio (25-Jul @ 09:24)
Syntax Highlighted Code
- import PIL
- from PIL import Image
- img = Image.open('somepic.jpg')
- [3 more lines...]
Plain Code
import PIL
from PIL import Image
img = Image.open('somepic.jpg')
wpercent = (300/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((300,hsize), PIL.Image.ANTIALIAS)
img.save('sompic.jpg')
Resize image and maintain aspect ratio (25-Jul @ 09:23)
Syntax Highlighted Code
- import PIL
- from PIL import Image
- img = Image.open('somepic.jpg')
- [3 more lines...]
Plain Code
import PIL
from PIL import Image
img = Image.open('somepic.jpg')
wpercent = (300/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((300,hsize), PIL.Image.ANTIALIAS)
img.save('sompic.jpg')
Untitled Python (24-Jul @ 18:11)
Syntax Highlighted Code
- print('vai apanhar....')
Plain Code
print('vai apanhar....')
Untitled Python (3-Jul @ 17:30)
Syntax Highlighted Code
- class ClientsWorkspace(ExtJSONView):
- context(my_application)
- contains('clients') #the id of the container
- [5 more lines...]
Plain Code
class ClientsWorkspace(ExtJSONView):
context(my_application)
contains('clients') #the id of the container
listing_fields(['name','email',]) #columns for the ExtJSGrid
default_view('addform') #a view that return a ExtForm in JSON format
bind_url('editclient') #the view that will return the JSON to show on click event
Untitled Python (30-Jun @ 14:43)
Syntax Highlighted Code
- import re
- str = "* will * there."
- all = re.findall("\*", str)
Plain Code
import re
str = "* will * there."
all = re.findall("\*", str)
Untitled Python (26-Jun @ 01:11)
Syntax Highlighted Code
- Do a simple doctest test on the app.
- ************************************
- :Test-Layer: functional
- [28 more lines...]
Plain Code
Do a simple doctest test on the app.
************************************
:Test-Layer: functional
>>> import grok
>>> from zope.component import getMultiAdapter
>>> from zope import schema
>>> from pymenthon.forms.components import AddForm
>>> from zope.interface import Interface
>>> from zope.publisher.browser import TestRequest
>>> class IPerson(Interface):
... firstname = schema.TextLine(title=u'Firstname')
... lastname = schema.TextLine(title=u'Lastname')
...
>>> class People(grok.Application, grok.Container):
... pass
...
Now we can create a JSON View
>>> class PersonJSON(grok.JSON):
... grok.context(People)
...
... def hello(self):
... return {'hi':'there'}
...
Finally, let's get the view
>>> persons = People()
>>> request = TestRequest()
>>> form = getMultiAdapter((persons, request), name="hello")
Untitled Python (18-Jun @ 00:48)
Syntax Highlighted Code
- i = 0
- for i in range(0,i+1):
- print "yo"
Plain Code
i = 0
for i in range(0,i+1):
print "yo"
Untitled Python (30-May @ 17:50)
Syntax Highlighted Code
- class Register(Master):
- """Register an InternalPrincipal add an IUser"""
- def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
- if login is not None:
- [10 more lines...]
Plain Code
class Register(Master):
"""Register an InternalPrincipal add an IUser"""
def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
if login is not None:
pau = component.getUtility(IAuthentication)
principals = pau['principals']
if login not in principals:
name = fname + ' ' + lname
principals[login] = user = InternalPrincipal(login, password, name)
role_manager = IPrincipalRoleManager(self.context)
role_manager.assignRoleToPrincipal('Tpi.User', login)
user = IUser(user) #pass it the InternalPrincipal object for adaption
user.email = email
user.fname = fname
user.lname = lname
Untitled Python (29-May @ 05:15)
Syntax Highlighted Code
- class Register(Master):
- """Register an InternalPrincipal add an IUser"""
- def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
- # TODO: validate password is equal to password_repeat
- [14 more lines...]
Plain Code
class Register(Master):
"""Register an InternalPrincipal add an IUser"""
def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
# TODO: validate password is equal to password_repeat
# add principal to principal folder
if login is not None:
pau = component.getUtility(IAuthentication)
principals = pau['principals']
if login not in principals:
name = fname + ' ' + lname
principals[login] = user = InternalPrincipal(login, password, name)
# save the email to an IUser instance
user = IUser(user) #pass it the InternalPrincipal object for adaption
user.email = email
user.fname = fname
user.lname = lname
principalRoleManager.assignRoleToPrincipal('Tpi.Employee', login)
else:pass
else:pass
Untitled Python (27-May @ 03:38)
Syntax Highlighted Code
- #!/usr/bin/python
- def amort(cost, interest, term, pmt):
- mint = (1 + interest) ** (1.0/12)
- [28 more lines...]
Plain Code
#!/usr/bin/python
def amort(cost, interest, term, pmt):
mint = (1 + interest) ** (1.0/12)
for i in range(term):
for j in range(12):
cost *= mint
cost -= pmt
return cost
def findpmt(cost, interest, term):
ub = cost
lb = 0
test = cost / 2
bal = amort(cost, interest, term, test)
while abs(bal) > 1000:
if bal > 0:
lb = test
else:
ub = test
test = (lb + ub)/2
bal = amort(cost, interest, term, test)
return test
def ira(down, pmt, interest, term):
mint = (1 + interest) ** (1.0/12)
for i in range(term):
for j in range(12):
down += pmt
down *= mint
return down
Untitled Python (25-May @ 02:47)
Syntax Highlighted Code
- File "/home/sancho/revoluciones/grok/rdbexample/eggs/tmpIHUqUX/zope.tales-3.4.0a1-py2.4.egg/zope/tales/tales.py", line 696, in evaluate
- - /home/sancho/revoluciones/grok/Tpi/src/tpi/app_templates/master.pt
- - Line 39, Column 5
- - Expression: <PythonExpr (view.navLIST(context.__name__))>
- [16 more lines...]
Plain Code
File "/home/sancho/revoluciones/grok/rdbexample/eggs/tmpIHUqUX/zope.tales-3.4.0a1-py2.4.egg/zope/tales/tales.py", line 696, in evaluate
- /home/sancho/revoluciones/grok/Tpi/src/tpi/app_templates/master.pt
- Line 39, Column 5
- Expression: <PythonExpr (view.navLIST(context.__name__))>
- Names:
{'args': (),
'context': <tpi.app.Tpi object at 0xb74e872c>,
'default': <object object at 0xb7d98560>,
'loop': {},
'nothing': None,
'options': {},
'repeat': {},
'request': <zc.resourcelibrary.publication.Request instance URL=http://192.168.1.103:8080/test/@@index>,
'static': <grok.components.DirectoryResource object at 0x9c33b4c>,
'template': <grok.components.TrustedFilePageTemplate object at 0x9708ccc>,
'view': <tpi.app.Index object at 0x9c3384c>}
File "/home/sancho/revoluciones/grok/rdbexample/eggs/tmpIHUqUX/zope.tales-3.4.0a1-py2.4.egg/zope/tales/pythonexpr.py", line 59, in __call__
- __traceback_info__: (view.navLIST(context.__name__))
File "<string>", line 0, in ?
AttributeError: 'Index' object has no attribute 'navLIST'
Untitled Python (25-May @ 02:43)
Syntax Highlighted Code
- class SimpleClientJSON(grok.JSON):
- grok.context(SimpleClient)
- def firstname(self):
- [17 more lines...]
Plain Code
class SimpleClientJSON(grok.JSON):
grok.context(SimpleClient)
def firstname(self):
return {'firstname': self.context.firstname}
#return dict(client = self.context) TODO: make the object JSON serializable
def lastname(self):
return {'lastname': self.context.lastname}
class Index(grok.View):
grok.context(rdbexample)
def render(self):
session = Session()
client = session.query(SimpleClient).first()
if client:
view = getMultiAdapter((client, self.request), name='firstname')
return view()
else:
self.redirect('addsimpleclient')
Untitled Python (25-May @ 00:05)
Syntax Highlighted Code
- def foo():
- '''print hello'''
- print 'hello'
Plain Code
def foo():
'''print hello'''
print 'hello'
Untitled Python (24-May @ 06:04)
Syntax Highlighted Code
- class Listing(Master):
- '''
- Member listing view. This demonstrates how to require a permission to view, and also how to
- obtain a list of annotated principals.
- [18 more lines...]
Plain Code
class Listing(Master):
'''
Member listing view. This demonstrates how to require a permission to view, and also how to
obtain a list of annotated principals.
'''
grok.require('logindemo.ViewMemberListing')
def fieldNames(self):
return (f for f in IUser)
def members(self):
pau = getUtility(IAuthentication)
principals = pau['principals']
roster = []
for id in sorted(principals.keys()):
# adapt the principals to IUser to get all fields
user = IUser(principals[id])
fields = {}
for field in IUser:
fields[field] = getattr(user, field)
roster.append(fields)
return roster
Untitled Python (24-May @ 05:50)
Syntax Highlighted Code
- class MemberListing(grok.View):
- def fieldNames(self):
- return (f for f in IUser)
- [15 more lines...]
Plain Code
class MemberListing(grok.View):
def fieldNames(self):
return (f for f in IUser)
def members(self):
pau = component.getUtility(IAuthentication)
principals = pau['principals']
roster = [ ]
for id in sorted(principals.keys()):
print id
print principals[id]
user = IUser(principals[id]) # <----- this is where the code is breaking
fields = {}
for field in IUser:
fields[field] = getattr(user, field)
roster.append(fields)
return roster
Untitled Python (24-May @ 05:39)
Syntax Highlighted Code
- import re
- import grok
- from grok import index
- from zope.interface import Interface
- [194 more lines...]
Plain Code
import re
import grok
from grok import index
from zope.interface import Interface
from zope import schema
from z3c.widget.tiny.widget import TinyWidget
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.principalfolder import IInternalPrincipal
from zope.app.authentication.interfaces import IPasswordManager
from zope.app.authentication.session import SessionCredentialsPlugin
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalRoleManager
from zope.securitypolicy.interfaces import IRole
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.securitypolicy.role import LocalRole
from zope.i18n import MessageFactory
from zope.component import provideAdapter
from zope.component import getUtility
from zope.interface import implements
from zope.component import adapts
from zope.component import getUtility
from zope.component import getUtilitiesFor
from zope.annotation.interfaces import IAnnotations
from persistent.dict import PersistentDict
from zope.i18n import MessageFactory
import appconfig
from zope import component
expr = re.compile(r"^(w&.%#$&'*+-/=?^_`{}|~]+!)*[w&.%#$&'*+-/=?^_`{}|~]+"
r"@(([0-9a-z]([0-9a-z-]*[0-9a-z])?.)+[a-z]{2,6}|([0-9]{1,3}"
r".){3}[0-9]{1,3})$", re.IGNORECASE)
check_email = expr.match
##############################################################################
### I N T E R F A C E S ######################################################
##############################################################################
_ = MessageFactory('tpi')
################################################## email validation
class NotAnEmailAddress(schema.ValidationError):
__doc__ = _(u"Invalid email address")
check_email = re.compile(r"[a-zA-Z0-9._%-]+@([a-zA-Z0-9-]+.)*[a-zA-Z]{2,4}").match
def valid_email(value):
if check_email(value):
return True
raise NotAnEmailAddress(value)
################################################## interfaces
class IUser(Interface):
"""Basic user data."""
login = schema.TextLine(title=_(u"Login"),
required=True)
password = schema.Password(title=_(u"Password"),
required=True)
password_repeat = schema.Password(title=_(u"Password repeat"),
required=True)
fname = schema.TextLine(title=_(u"First name"),
required=False)
lname = schema.TextLine(title=_(u"Last name"),
required=False)
email = schema.ASCIILine(title=_(u"E-mail"),
required=False,
constraint=valid_email)
### H E L P E R S C R I P T S #############################################
def setup_pau(pau):
pau['principals'] = PrincipalFolder('tpi.principals.')
pau.authenticatorPlugins = ('principals',)
pau['session'] = session = SessionCredentialsPlugin()
session.loginpagename = 'login'
pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
def role_factory(*args):
def factory():
return LocalRole(*args)
return factory
##############################################################################
### A P P L I C A T I O N ####################################################
##############################################################################
class Tpi(grok.Application, grok.Container):
def __init__(self):
super(Tpi, self).__init__()
### U T I L I T I E S ###################################################
# register authentication utility
grok.local_utility(PluggableAuthentication, IAuthentication,
setup=setup_pau)
# register Admin Role
grok.local_utility(role_factory(u'TPI Administrator'), IRole,
name='tpi.Admin',
name_in_container='tpi.Admin')
# register Employee Role
grok.local_utility(role_factory(u'TPI Employees'), IRole,
name='tpi.Employee',
name_in_container='tpi.Employees')
# register Employee Role
grok.local_utility(role_factory(u'TPI Member'), IRole,
name='tpi.Member',
name_in_container='tpi.Member')
### S U B S C R I B E R S ####################################################
@grok.subscribe(Tpi, grok.IObjectAddedEvent)
def grant_permissions(app, event):
role_manager = IRolePermissionManager(app)
# Admin Permissions
role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')
role_manager.grantPermissionToRole('tpi.DeleteClient', 'tpi.Admin')
role_manager.grantPermissionToRole('tpi.ViewMemberListing', 'tpi.Admin')
# Employee Permissions
role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')
class GlobalMacros(grok.View):
grok.context(Interface)
grok.name('globalmacros')
class Index(grok.View):
grok.context(Tpi)
grok.name('index')
def navLIST(self, name):
if name not in appconfig.menuitems.keys():
pass
else:
return appconfig.menuitems[name]
##############################################################################
### A U T H E N T I C A T I O N ##############################################
##############################################################################
class Register(grok.Form):
form_fields = grok.AutoFields(IUser)
label = u'User registration'
template = grok.PageTemplateFile('form.pt')
@grok.action('Sign up')
def save(self, login, password, password_repeat, fname, lname, email):
# TODO: validate password is equal to password_repeat
# add principal to principal folder
pau = component.getUtility(IAuthentication)
principals = pau['principals']
assert(login not in principals)
name = fname + ' ' + lname
principals[login] = user = InternalPrincipal(login, password, name)
# save the email to an IUser instance
user.email = email
# grant principal the role
role_manager = IPrincipalRoleManager(self.context)
role_manager.assignRoleToPrincipal('tpi.Employee',
principals.prefix + login)
self.redirect('index')
class MemberListing(grok.Adapter):
grok.implements(IUser)
grok.template('form.pt')
def fieldNames(self):
return (f for f in IUser)
def members(self):
pau = component.getUtility(IAuthentication)
principals = pau['principals']
roster = [ ]
for id in sorted(principals.keys()):
print id
print principals[id]
user = IUser(principals[id]) # <----- this is where the code is breaking
fields = {}
for field in IUser:
fields[field] = getattr(user, field)
roster.append(fields)
return roster
Untitled Python (24-May @ 05:28)
Syntax Highlighted Code
- import grok
- from urllib import urlencode
- from zope.interface import Interface, implements, classImplements
- from zope.component import getUtility, provideAdapter
- [177 more lines...]
Plain Code
import grok
from urllib import urlencode
from zope.interface import Interface, implements, classImplements
from zope.component import getUtility, provideAdapter
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
# XXX: Failed attempt to display the password_encoding field
# from zope.app.form.browser.source import SourceDropdownWidget
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.app.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.i18n import MessageFactory
from interfaces import IUser, UserDataAdapter
_ = MessageFactory('logindemo')
def setup_pau(pau):
'''
Callback to setup the Pluggable Authentication Utility
A reference to this function is passed as a parameter in the
declaration of the PAU (see LoginDemo class)
'''
# the principal source is a PrincipalFolder, stored in ZODB
pau['principals'] = PrincipalFolder()
pau.authenticatorPlugins = ('principals',)
# the SessionCredentialsPlugin isused for cookie-based authentication
pau['session'] = session = SessionCredentialsPlugin()
session.loginpagename = 'login' # the page to redirect for login
# configuration of the credentials plugin
pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
class LoginDemo(grok.Application, grok.Container):
"""
An app that lets you create an account and change your password.
"""
# register the authentication utility; see setup_pau for settings
grok.local_utility(PluggableAuthentication, IAuthentication,
setup=setup_pau)
# make InternalPrincipal instances annotatable
classImplements(InternalPrincipal,IAttributeAnnotatable)
# register the adapter for IInternalPrincipal which provides IUser
provideAdapter(UserDataAdapter)
class ViewMemberListing(grok.Permission):
''' Permission to see the member listing '''
grok.name('logindemo.ViewMemberListing')
class Master(grok.View):
"""
The master page template macro.
The template master.pt is used as page macro in most views. Since this
template uses the logged_in method and message attributes below, it's best
to make all other views in this app subclasses of Master.
"""
grok.context(Interface) # register this view for all objects
message = '' # used to give feedback
def logged_in(self):
# this is the canonical way to tell whether the user is authenticated
# in Zope 3: check if the principal provides IUnauthenticatedPrincipal
return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
class Index(Master):
"""
The main page, showing user data and member count.
"""
def members(self):
# get the authentication utility
pau = getUtility(IAuthentication)
result = len(pau['principals'])
if result == 0:
return _(u'No one has')
elif result == 1:
return _(u'One member has')
else:
return unicode(result) + _(u' members have')
class Login(Master):
"""
Login form and handler.
"""
def update(self, login_submit=None):
if login_submit is not None: # we are handling the login submission
if self.logged_in(): # if the login was accepted then...
# redirect to where the user came from, or to the main page
dest = self.request.get('camefrom', self.application_url())
self.redirect(dest)
else: # if the user is still not logged in...
# then an incorrect login or password was provided
self.message = _(u'Invalid login name and/or password')
class Logout(grok.View):
"""
Logout handler.
"""
grok.context(Interface)
def render(self):
# get the session plugin and tell it to logout
session = getUtility(IAuthentication)['session']
session.logout(self.request)
# redirect to the main page
self.redirect(self.application_url())
class Join(grok.AddForm, Master):
"""
User registration form.
"""
form_fields = grok.AutoFields(IUser)
# XXX: Failed attempt to display the password_encoding field
#form_fields[u'password_encoding'].custom_widget = SourceDropdownWidget
label = u'User registration'
template = grok.PageTemplateFile('form.pt')
@grok.action('Save')
def save(self, **data):
'''
Create an InternalPrincipal with the user data.
This method also sets extra fields using an annotations through
the IUser adapter, and grants the ViewMemberListing permission to
the principal just created.
'''
login = data['login']
pau = getUtility(IAuthentication)
principals = pau['principals']
# create an instance of InternalPrincipal
principal = InternalPrincipal(login, data['password'], data['name'],
passwordManagerName='SHA1')
# add principal to principal folder; we may assume that the login
# name is unique because of validation on the IUser interface
# but to be doubly sure, we assert this
assert(login not in principals)
principals[login] = principal
# save the e-mail
user = IUser(principal)
user.email = data['email']
# grant the user permission to view the member listing
permission_mngr = IPrincipalPermissionManager(grok.getSite())
permission_mngr.grantPermissionToPrincipal(
'logindemo.ViewMemberListing', principals.prefix + login)
self.redirect(self.url('login')+'?'+urlencode({'login':login}))
class Account(grok.View):
def render(self):
return 'Not implemented'
class Listing(Master):
'''
Member listing view. This demonstrates how to require a permission to view, and also how to
obtain a list of annotated principals.
'''
grok.require('logindemo.ViewMemberListing')
def fieldNames(self):
return (f for f in IUser)
def members(self):
pau = getUtility(IAuthentication)
principals = pau['principals']
roster = []
for id in sorted(principals.keys()):
# adapt the principals to IUser to get all fields
user = IUser(principals[id])
fields = {}
for field in IUser:
fields[field] = getattr(user, field)
roster.append(fields)
return roster
Untitled Python (24-May @ 04:09)
Syntax Highlighted Code
- import re
- import grok
- from grok import index
- from zope.interface import Interface
- [249 more lines...]
Plain Code
import re
import grok
from grok import index
from zope.interface import Interface
from zope import schema
from z3c.widget.tiny.widget import TinyWidget
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.principalfolder import IInternalPrincipal
from zope.app.authentication.interfaces import IPasswordManager
from zope.app.authentication.session import SessionCredentialsPlugin
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalRoleManager
from zope.securitypolicy.interfaces import IRole
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.securitypolicy.role import LocalRole
from zope.i18n import MessageFactory
from zope.component import provideAdapter
from zope.component import getUtility
from zope.interface import implements
from zope.component import adapts
from zope.component import getUtility
from zope.component import getUtilitiesFor
from zope.annotation.interfaces import IAnnotations
from persistent.dict import PersistentDict
from zope.i18n import MessageFactory
import appconfig
from zope import component
expr = re.compile(r"^(w&.%#$&'*+-/=?^_`{}|~]+!)*[w&.%#$&'*+-/=?^_`{}|~]+"
r"@(([0-9a-z]([0-9a-z-]*[0-9a-z])?.)+[a-z]{2,6}|([0-9]{1,3}"
r".){3}[0-9]{1,3})$", re.IGNORECASE)
check_email = expr.match
##############################################################################
### I N T E R F A C E S ######################################################
##############################################################################
_ = MessageFactory('tpi')
USER_DATA_KEY = 'tpi.iuser.data'
################################################## email validation
class NotAnEmailAddress(schema.ValidationError):
__doc__ = _(u"Invalid email address")
check_email = re.compile(r"[a-zA-Z0-9._%-]+@([a-zA-Z0-9-]+.)*[a-zA-Z]{2,4}").match
def valid_email(value):
if check_email(value):
return True
raise NotAnEmailAddress(value)
################################################## login name validation
class LoginNameTaken(schema.ValidationError):
__doc__ = _(u"Login name already in use. Please choose a different id")
def unique_login(login):
pau = getUtility(IAuthentication)
if login in pau['principals']:
raise LoginNameTaken
return True
################################################## login name validation
class NotValidLogin(schema.ValidationError):
__doc__ = _(u"Login name is invalid. Please check your records.")
def check_valid_login(login):
pau = getUtility(IAuthentication)
if login not in pau['principals']:
raise NotValidLogin
return True
################################################## password manager selection
class PasswordManagerChoices(object):
implements(schema.interfaces.IIterableSource)
def __init__(self):
self.choices = [name for name, util in
sorted(getUtilitiesFor(IPasswordManager))]
def __iter__(self):
return iter(self.choices)
def __len__(self):
return len(self.choices)
def __contains__(self, value):
return value in self.choices
################################################## interfaces
class IUser(Interface):
"""Basic user data."""
login = schema.TextLine(title=_(u"Login"),
required=True,
constraint=unique_login)
password = schema.Password(title=_(u"Password"),
required=True)
password_repeat = schema.Password(title=_(u"Password repeat"),
required=True)
fname = schema.TextLine(title=_(u"First name"),
required=False)
lname = schema.TextLine(title=_(u"Last name"),
required=False)
email = schema.ASCIILine(title=_(u"E-mail"),
required=False,
constraint=valid_email)
### P E R M I S S I O N S ####################################################
class ViewClients(grok.Permission):
grok.name('tpi.ViewClients')
grok.title('View Clients')
class AddClient(grok.Permission):
grok.name('tpi.AddClient')
grok.title('Add Client')
class DeleteClient(grok.Permission):
grok.name('tpi.DeleteClients')
grok.title('Delete Clients')
class ViewMemberListing(grok.Permission):
grok.name('tpi.ViewMemberListing')
grok.title('View TPI Members')
### H E L P E R S C R I P T S #############################################
_ = MessageFactory('tpi')
def setup_pau(pau):
pau['principals'] = PrincipalFolder('tpi.principals.')
pau.authenticatorPlugins = ('principals',)
pau['session'] = session = SessionCredentialsPlugin()
session.loginpagename = 'login'
pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
def role_factory(*args):
def factory():
return LocalRole(*args)
return factory
##############################################################################
### A P P L I C A T I O N ####################################################
##############################################################################
class Tpi(grok.Application, grok.Container):
def __init__(self):
super(Tpi, self).__init__()
class GlobalMacros(grok.View):
grok.context(Interface)
grok.name('globalmacros')
class Index(grok.View):
grok.context(Tpi)
grok.name('index')
def navLIST(self, name):
if name not in appconfig.menuitems.keys():
pass
else:
return appconfig.menuitems[name]
##############################################################################
### A U T H E N T I C A T I O N ##############################################
##############################################################################
class Register(grok.Form):
form_fields = grok.AutoFields(IUser)
label = u'User registration'
template = grok.PageTemplateFile('form.pt')
@grok.action('Sign up')
def save(self, login, password, password_repeat, fname, lname, email):
# TODO: validate password is equal to password_repeat
# add principal to principal folder
pau = getUtility(IAuthentication)
principals = pau['principals']
name = fname + ' ' + lname
principals[login] = InternalPrincipal(login, password, name)
# grant principal the role
role_manager = IPrincipalRoleManager(self.context)
role_manager.assignRoleToPrincipal('tpi.Employee',
principals.prefix + login)
self.redirect('index')
class Login(grok.View):
grok.context(Interface)
def update(self, login=None, password=None, login_submit=None):
if (not IUnauthenticatedPrincipal.providedBy(self.request.principal)
and login_submit is not None):
camefrom = self.request.get('camefrom', '.')
self.redirect(camefrom)
class Logout(grok.View):
grok.context(Interface)
def render(self):
# get the session plugin and tell it to logout
session = component.getUtility(IAuthentication)['session']
session.logout(self.request)
# redirect to the main page
self.redirect(self.application_url())
class MyAccount(grok.View):
grok.context(Interface)
def render(self):
return 'Not yet implemented'
class MemberListing(grok.View):
grok.implements(IUser)
def fieldNames(self):
return (f for f in IUser)
def members(self):
pau = component.getUtility(IAuthentication)
principals = pau['principals']
roster = [ ]
for id in sorted(principals.keys()):
print id
#user = IUser(principals[id]) # <----- this is where the code is breaking
#fields = {}
#for field in IUser:
# fields[field] = getattr(user, field)
#roster.append(fields)
return roster
Untitled Python (21-May @ 05:25)
Syntax Highlighted Code
- import grok
- from grok import index
- import appconfig
- from zope.interface import Interface # this import will allow macros to access any object in any context
- [183 more lines...]
Plain Code
import grok
from grok import index
import appconfig
from zope.interface import Interface # this import will allow macros to access any object in any context
from zope import interface, schema
from z3c.widget.tiny.widget import TinyWidget
from agreements import IAgreements
from agreements import Agreements
from agreement import Agreement
from clients import IClients
from clients import Clients
from client import IClient
from client import Client
from shoot import Shoot
from shoots import IShoots
from shoots import Shoots
from invoice import Invoice
from billablehours import BillableHours
from imagerepository import ImageRepository
from pendingconfirmations import IPendingConfirmations
from pendingconfirmations import PendingConfirmations
from pendingconfirmation import PendingConfirmation
from groffs import Groffs
from groff import Groff
import apputils
import appconfig
from urllib import urlencode
from zope.interface import implements
from zope.interface import classImplements
from zope.component import getUtility
from zope.component import provideAdapter
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
# XXX: Failed attempt to display the password_encoding field
# from zope.app.form.browser.source import SourceDropdownWidget
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalRoleManager, IRole
from zope.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.i18n import MessageFactory
from interfaces import IUser
from interfaces import UserDataAdapter
from zope import component
### H E L P E R S C R I P T S #############################################
def setup_pau(pau):
pau['principals'] = PrincipalFolder('nudge.principals.')
pau.authenticatorPlugins = ('principals',)
pau['session'] = session = SessionCredentialsPlugin()
session.loginpagename = 'login'
pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
def role_factory(*args):
def factory():
return LocalRole(*args)
return factory
##############################################################################
### A P P L I C A T I O N ####################################################
##############################################################################
class Tpi(grok.Application, grok.Container):
def __init__(self):
super(Tpi, self).__init__()
# create top level folders
self['clients'] = Clients()
self['agreements'] = Agreements()
self['shoots'] = Shoots()
self['confirmations'] = PendingConfirmations()
self['groffs'] = Groffs()
### P E R M I S S I O N S ####################################################
class ViewClients(grok.Permission):
grok.name('tpi.ViewClients')
grok.title('View Clients')
class AddClient(grok.Permission):
grok.name('tpi.AddClient')
grok.title('Add Client')
class DeleteClient(grok.Permission):
grok.name('tpi.DeleteClients')
grok.title('Delete Clients')
### U T I L I T I E S #######################################################
# register authentication utility
grok.local_utility(PluggableAuthentication, IAuthentication,
setup=setup_pau)
# register Admin Role
grok.local_utility(role_factory(u'TPI Administrator'), IRole,
name='tpi.Admin',
name_in_container='tpi.Admin')
# register Employee Role
grok.local_utility(role_factory(u'TPI Employees'), IRole,
name='tpi.Employees',
name_in_container='tpi.Employees')
### S U B S C R I B E R S ####################################################
@grok.subscribe(Tpi, grok.IObjectAddedEvent)
def grant_permissions(app, event):
role_manager = IRolePermissionManager(app)
# Admin Permissions
role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')
role_manager.grantPermissionToRole('tpi.DeleteClient', 'tpi.Admin')
# Employee Permissions
role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')
### C A T A L O G S ##########################################################
class ClientIndex(grok.Indexes):
grok.site(Tpi)
grok.context(IClient) #objects implementing this interface will be indexed
grok.name('client_catalog') #name of catalog
name = index.Field(attribute='name')
email = index.Field(attribute='email')
uid = index.Field(attribute='uid')
##############################################################################
### V I E W S ################################################################
##############################################################################
class GlobalMacros(grok.View):
grok.context(Interface)
grok.name('globalmacros')
class Index(grok.View):
grok.context(Tpi)
grok.name('index')
def navLIST(self, name):
if name not in appconfig.menuitems.keys():
pass
else:
return appconfig.menuitems[name]
##############################################################################
### A U T H E N T I C A T I O N ##############################################
##############################################################################
class SignUp(grok.Form):
form_fields = grok.Fields(
name = schema.TextLine(title=u"Your name"),
# TODO: validate email address
email = schema.TextLine(title=u"Email address"),
password = schema.Password(title=u"Password"),
password_repeat = schema.Password(title=u"Repeat password"),
)
@grok.action('Sign up')
def sign_up(self, name, email, password, password_repeat):
# TODO: validate password is equal to password_repeat
# add principal to principal folder
pau = component.getUtility(IAuthentication)
principals = pau['principals']
principals[email] = user = InternalPrincipal(email, password, name)
# grant principal the role
role_manager = IPrincipalRoleManager(self.context)
role_manager.assignRoleToPrincipal('tpi.Employee',
principals.prefix + email)
self.redirect('index')
class Login(grok.View):
grok.context(Interface)
def update(self, login_submit=None):
if (not IUnauthenticatedPrincipal.providedBy(self.request.principal)
and login_submit is not None):
camefrom = self.request.get('camefrom', '.')
self.redirect(camefrom)
Untitled Python (19-May @ 07:39)
Syntax Highlighted Code
- import grok
- import appconfig
- from zope.interface import Interface # this import will allow macros to access any object in any context
- from zope import interface, schema
- [247 more lines...]
Plain Code
import grok
import appconfig
from zope.interface import Interface # this import will allow macros to access any object in any context
from zope import interface, schema
from z3c.widget.tiny.widget import TinyWidget
from agreements import IAgreements
from agreements import Agreements
from agreement import Agreement
from clients import IClients
from clients import Clients
from client import Client
from shoot import Shoot
from shoots import IShoots
from shoots import Shoots
from invoice import Invoice
from billablehours import BillableHours
from imagerepository import ImageRepository
from pendingconfirmations import IPendingConfirmations
from pendingconfirmations import PendingConfirmations
from pendingconfirmation import PendingConfirmation
from groffs import Groffs
from groff import Groff
import apputils
import appconfig
from urllib import urlencode
from zope.interface import Interface, implements, classImplements
from zope.component import getUtility, provideAdapter
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
# XXX: Failed attempt to display the password_encoding field
# from zope.app.form.browser.source import SourceDropdownWidget
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.i18n import MessageFactory
class Tpi(grok.Application, grok.Container):
def __init__(self):
super(Tpi, self).__init__()
self['clients'] = Clients()
self['agreements'] = Agreements()
self['shoots'] = Shoots()
self['confirmations'] = PendingConfirmations()
self['groffs'] = Groffs()
##############################################################################
### V I E W ##################################################################
##############################################################################
class GlobalMacros(grok.View):
grok.context(Interface)
grok.name('globalmacros')
def objVALUES(self):
return [ (key,self.context[key]) for key in self.context.keys() ]
##############################################################################
### V I E W ##################################################################
##############################################################################
class Index(grok.View):
grok.context(Tpi)
grok.name('index')
### L I S T I N G S ##########################################################
def objVALUES(self):
return [ (key,self.context[key]) for key in self.context.keys() ]
def navLIST(self, name):
if name not in appconfig.menuitems.keys():
pass
else:
return appconfig.menuitems[name]
##############################################################################
### A U T H E N T I C A T I O N C R A P ####################################
##############################################################################
from interfaces import IUser, UserDataAdapter
_ = MessageFactory('logindemo')
def setup_pau(pau):
'''
Callback to setup the Pluggable Authentication Utility
A reference to this function is passed as a parameter in the
declaration of the PAU (see LoginDemo class)
'''
# the principal source is a PrincipalFolder, stored in ZODB
pau['principals'] = PrincipalFolder()
pau.authenticatorPlugins = ('principals',)
# the SessionCredentialsPlugin isused for cookie-based authentication
pau['session'] = session = SessionCredentialsPlugin()
session.loginpagename = 'login' # the page to redirect for login
# configuration of the credentials plugin
pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
class LoginDemo(grok.Application, grok.Container):
"""
An app that lets you create an account and change your password.
"""
# register the authentication utility; see setup_pau for settings
grok.local_utility(PluggableAuthentication, IAuthentication,
setup=setup_pau)
# make InternalPrincipal instances annotatable
classImplements(InternalPrincipal,IAttributeAnnotatable)
# register the adapter for IInternalPrincipal which provides IUser
provideAdapter(UserDataAdapter)
class ViewMemberListing(grok.Permission):
''' Permission to see the member listing '''
grok.name('logindemo.ViewMemberListing')
class Master(grok.View):
"""
The master page template macro.
The template master.pt is used as page macro in most views. Since this
template uses the logged_in method and message attributes below, it's best
to make all other views in this app subclasses of Master.
"""
grok.context(Interface) # register this view for all objects
message = '' # used to give feedback
def logged_in(self):
# this is the canonical way to tell whether the user is authenticated
# in Zope 3: check if the principal provides IUnauthenticatedPrincipal
return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
class Members(Master):
"""
The main page, showing user data and member count.
"""
def members(self):
# get the authentication utility
pau = getUtility(IAuthentication)
result = len(pau['principals'])
if result == 0:
return _(u'No one has')
elif result == 1:
return _(u'One member has')
else:
return unicode(result) + _(u' members have')
class Login(Master):
"""
Login form and handler.
"""
def update(self, login_submit=None):
if login_submit is not None: # we are handling the login submission
if self.logged_in(): # if the login was accepted then...
# redirect to where the user came from, or to the main page
dest = self.request.get('camefrom', self.application_url())
self.redirect(dest)
else: # if the user is still not logged in...
# then an incorrect login or password was provided
self.message = _(u'Invalid login name and/or password')
class Logout(grok.View):
"""
Logout handler.
"""
grok.context(Interface)
def render(self):
# get the session plugin and tell it to logout
session = getUtility(IAuthentication)['session']
session.logout(self.request)
# redirect to the main page
self.redirect(self.application_url())
class Join(grok.AddForm, Master):
"""
User registration form.
"""
form_fields = grok.AutoFields(IUser)
# XXX: Failed attempt to display the password_encoding field
#form_fields[u'password_encoding'].custom_widget = SourceDropdownWidget
label = u'User registration'
template = grok.PageTemplateFile('form.pt')
@grok.action('Save')
def save(self, **data):
'''
Create an InternalPrincipal with the user data.
This method also sets extra fields using an annotations through
the IUser adapter, and grants the ViewMemberListing permission to
the principal just created.
'''
login = data['login']
pau = getUtility(IAuthentication)
principals = pau['principals']
# create an instance of InternalPrincipal
principal = InternalPrincipal(login, data['password'], data['name'],
passwordManagerName='SHA1')
# add principal to principal folder; we may assume that the login
# name is unique because of validation on the IUser interface
# but to be doubly sure, we assert this
assert(login not in principals)
principals[login] = principal
# save the e-mail
user = IUser(principal)
user.email = data['email']
# grant the user permission to view the member listing
permission_mngr = IPrincipalPermissionManager(grok.getSite())
permission_mngr.grantPermissionToPrincipal(
'logindemo.ViewMemberListing', principals.prefix + login)
self.redirect(self.url('login')+'?'+urlencode({'login':login}))
class Account(grok.View):
grok.context(LoginDemo)
def render(self):
return 'Not implemented'
class Listing(Master):
'''
Member listing view. This demonstrates how to require a permission to view, and also how to
obtain a list of annotated principals.
'''
grok.require('logindemo.ViewMemberListing')
def fieldNames(self):
return (f for f in IUser)
def members(self):
pau = getUtility(IAuthentication)
principals = pau['principals']
roster = []
for id in sorted(principals.keys()):
# adapt the principals to IUser to get all fields
user = IUser(principals[id])
fields = {}
for field in IUser:
fields[field] = getattr(user, field)
roster.append(fields)
return roster
Untitled Python (19-May @ 07:35)
Syntax Highlighted Code
- grok.local_utility(PluggableAuthentication, IAuthentication,
- setup=setup_pau)
Plain Code
grok.local_utility(PluggableAuthentication, IAuthentication,
setup=setup_pau)
Untitled Python (19-May @ 06:12)
Syntax Highlighted Code
- ./bin/zopectl fg
- /home/sancho/grok-wsgi/rdbexample/parts/app/runzope -C /home/sancho/grok-wsgi/rdbexample/parts/zopectl/zope.conf
- /home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py:36: SADeprecationWarning: The 'transactional' argument to sessionmaker() is deprecated; use autocommit=True|False instead.
- self._Session = scoped_session(sessionmaker(
- [35 more lines...]
Plain Code
./bin/zopectl fg
/home/sancho/grok-wsgi/rdbexample/parts/app/runzope -C /home/sancho/grok-wsgi/rdbexample/parts/zopectl/zope.conf
/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py:36: SADeprecationWarning: The 'transactional' argument to sessionmaker() is deprecated; use autocommit=True|False instead.
self._Session = scoped_session(sessionmaker(
------
2008-05-19T02:11:48 INFO root -- HTTP:localhost:8080 Server started.
Hostname: localhost
Port: 8080
------
2008-05-19T02:11:48 INFO root Startup time: 3.524 sec real, 3.450 sec CPU
------
2008-05-19T02:11:48 ERROR SiteError http://localhost:8080/example/@@index
Traceback (most recent call last):
File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 133, in publish
File "/home/sancho/grok-wsgi/rdbexample/grok/src/grok/publication.py", line 45, in callObject
return super(ZopePublicationSansProxy, self).callObject(request, ob)
File "/home/sancho/grok-wsgi/rdbexample/eggs/tmpWGUZJt/zope.app.publication-3.4.3-py2.4.egg/zope/app/publication/zopepublication.py", line 167, in callObject
File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 108, in mapply
- __traceback_info__: <rdbexample.app.FacultyList object at 0x9f8f02c>
File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 114, in debug_call
File "/home/sancho/grok-wsgi/rdbexample/grok/src/grok/components.py", line 173, in __call__
return mapply(self.render, (), self.request)
File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 108, in mapply
- __traceback_info__: <bound method FacultyList.render of <rdbexample.app.FacultyList object at 0x9f8f02c>>
File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 114, in debug_call
File "/home/sancho/grok-wsgi/rdbexample/src/rdbexample/app.py", line 32, in render
for faculty in rdb.query(Faculty).all():
File "/home/sancho/grok-wsgi/rdbexample/megrok.rdb/src/megrok/rdb/__init__.py", line 15, in query
return database.session.query(class_)
File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py", line 102, in session
self._join_transaction()
File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py", line 96, in _join_transaction
tx.join_transaction(self._Session(), self._initial_transaction_status)
File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/tx.py", line 152, in join_transaction
transaction.get().join(DataManager(session, initial_status))
File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/tx.py", line 26, in __init__
if session.transactional:
AttributeError: 'Session' object has no attribute 'transactional'
Untitled Python (17-May @ 16:51)
Syntax Highlighted Code
- import grok
- import appconfig
- from zope import interface, schema
- from groff import Groff
- [76 more lines...]
Plain Code
import grok
import appconfig
from zope import interface, schema
from groff import Groff
import apputils
import uuid, time
import fsutils
import subprocess
##############################################################################
### M O D E L ################################################################
##############################################################################
class IClients(interface.Interface):
pass
class Groffs(grok.Container):
def __init__(self):
super(Groffs, self).__init__()
def traverse(self, name):
if name in self.keys():
return self[name]
##############################################################################
### V I E W ##################################################################
##############################################################################
class Index(grok.View):
grok.context(Groffs)
grok.name('index')
def listGroffObjects(self):
return ( name for name,obj in self.context.items() if isinstance(obj, Groff))
def readPDF(self,pdfuri):
return fsutils.file_to_stringIO(pdfuri)
def writeMOM(self, obj):
template = open(appconfig.xtemplate).read()
momuri = appconfig.groffsuri + obj.__name__
mom = open(momuri, 'w')
mom.write(template %(obj.fname + ' ' + obj.lname))
return momuri
def addGROFF(self, *arg):
uid = apputils.genUUID()
self.context[uid] = Groff(*arg)
self.context._p_changed = True
return self.context[uid]
def groffME(self, momuri, pdfuri):
ret = subprocess.call("groff -mom %s | pstopdf -i -o %s" %(momuri,pdfuri),
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
return ret
def update(self, fname=None, lname=None, email=None, groffbitch=None, groff=None):
if fname and lname and email:
obj = self.addGROFF(fname, lname, email)
momuri = self.writeMOM(obj)
pdfuri = appconfig.groffsuri + obj.__name__ + '.pdf'
if self.groffME(momuri, pdfuri) == 0:
pass
obj.pdfuri = pdfuri
if groff:
pdfuri = self.context[groff].pdfuri
pdf = self.readPDF(pdfuri)
RESPONSE = self.request.response
RESPONSE.setHeader('content-type', 'application/pdf')
RESPONSE.setHeader('content-length', str(len(pdf)))
RESPONSE.setHeader('content-disposition', 'attachment; filename=%s' %(groff + '.pdf'))
return pdf
Untitled Python (17-May @ 06:42)
Syntax Highlighted Code
- def addPENDINGCONFIRMATION(self, client, agreement, datetime_sent):
- app = self.context.__parent__.__parent__
- confirmations = app['confirmations']
- uid = apputils.genUUID()
- [2 more lines...]
Plain Code
def addPENDINGCONFIRMATION(self, client, agreement, datetime_sent):
app = self.context.__parent__.__parent__
confirmations = app['confirmations']
uid = apputils.genUUID()
confirmations[uid] = PendingConfirmation(client, agreement, datetime_sent)
confirmations._p_changed = True
Untitled Python (16-May @ 17:37)
Syntax Highlighted Code
- ------
- 2008-05-16T13:36:53 ERROR SiteError http://localhost:8080/mechanic/@@index
- Traceback (most recent call last):
- File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 133, in publish
- [43 more lines...]
Plain Code
------
2008-05-16T13:36:53 ERROR SiteError http://localhost:8080/mechanic/@@index
Traceback (most recent call last):
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 133, in publish
result = publication.callObject(request, obj)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.12-py2.4.egg/grok/publication.py", line 45, in callObject
return super(ZopePublicationSansProxy, self).callObject(request, ob)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.publication-3.4.2-py2.4.egg/zope/app/publication/zopepublication.py", line 167, in callObject
return mapply(ob, request.getPositionalArguments(), request)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 108, in mapply
return debug_call(obj, args)
- __traceback_info__: <dbmechanic.app.Index object at 0xa1ad36c>
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 114, in debug_call
return obj(*args)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.12-py2.4.egg/grok/components.py", line 139, in __call__
return self._render_template()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.12-py2.4.egg/grok/components.py", line 143, in _render_template
return self.template.render(self)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/megrok.genshi-0.9-py2.4.egg/megrok/genshi/components.py", line 26, in render
return stream.render(self.result_type)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/core.py", line 154, in render
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 45, in encode
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 274, in __call__
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 519, in __call__
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 679, in __call__
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 459, in __call__
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/core.py", line 212, in _ensure
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/markup.py", line 252, in _include
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/markup.py", line 297, in _match
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/markup.py", line 242, in _exec
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/base.py", line 421, in _eval
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/eval.py", line 136, in evaluate
File "/home/sancho/grok-wsgi/DBMechanic/src/dbmechanic/app_templates/index.g", line 11, in <Expression u'view.form()'>
${view.form()}
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/ToscaWidgets-0.8.5-py2.4.egg/tw/core/base.py", line 474, in __call__
return self.display(value, **kw)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/ToscaWidgets-0.8.5-py2.4.egg/tw/core/base.py", line 468, in display
kw = self.prepare_dict(value, kw)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/tw.forms-0.8-py2.4.egg/tw/forms/core.py", line 180, in prepare_dict
error = kw.setdefault('error', self.error_at_request)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/ToscaWidgets-0.8.5-py2.4.egg/tw/core/util.py", line 235, in __get__
return getattr(request_local, self.name)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Paste-1.5-py2.4.egg/paste/registry.py", line 125, in __getattr__
return getattr(self._current_obj(), attr)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Paste-1.5-py2.4.egg/paste/registry.py", line 180, in _current_obj
raise TypeError(
TypeError: No object (name: ToscaWidgets per-request storage) has been registered for this thread
Untitled Python (16-May @ 05:05)
Syntax Highlighted Code
- Traceback (most recent call last):
- File "./bin/paster", line 7, in ?
- sys.exit(
- File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 78, in run
- [22 more lines...]
Plain Code
Traceback (most recent call last):
File "./bin/paster", line 7, in ?
sys.exit(
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 78, in run
invoke(command, command_name, options, args[1:])
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 117, in invoke
exit_code = runner.run(args)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 212, in run
result = self.command()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 227, in command
relative_to=base, global_conf=vars)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 248, in loadapp
return loadapp(
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 193, in loadapp
return loadobj(APP, uri, name=name, **kw)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 214, in loadobj
return context.create()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
return self.object_type.invoke(self)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 157, in invoke
app = filter(app)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 118, in filter_wrapper
wsgi_app, context.global_conf,
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/util/fixtypeerror.py", line 57, in fix_call
val = callable(*args, **kw)
TypeError: make_middleware() got an unexpected keyword argument 'default_view'
Untitled Python (16-May @ 01:58)
Syntax Highlighted Code
- sancho@mulata:~/grok-wsgi$ ./bin/paster serve etc/grok.ini
- Traceback (most recent call last):
- File "./bin/paster", line 7, in ?
- sys.exit(
- [67 more lines...]
Plain Code
sancho@mulata:~/grok-wsgi$ ./bin/paster serve etc/grok.ini
Traceback (most recent call last):
File "./bin/paster", line 7, in ?
sys.exit(
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 78, in run
invoke(command, command_name, options, args[1:])
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 117, in invoke
exit_code = runner.run(args)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 212, in run
result = self.command()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 227, in command
relative_to=base, global_conf=vars)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 248, in loadapp
return loadapp(
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 193, in loadapp
return loadobj(APP, uri, name=name, **kw)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 214, in loadobj
return context.create()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
return self.object_type.invoke(self)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 153, in invoke
app = context.app_context.create()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
return self.object_type.invoke(self)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 99, in invoke
return fix_call(context.object, context.global_conf, **context.local_conf)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/util/fixtypeerror.py", line 57, in fix_call
val = callable(*args, **kw)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/repoze.grok-0.1.5-py2.4.egg/repoze/grok/bbb.py", line 37, in make_grokapp
app = getWSGIApplication(config_file)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.wsgi-3.4.0-py2.4.egg/zope/app/wsgi/__init__.py", line 134, in getWSGIApplication
db = config(configfile, schemafile, features)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.wsgi-3.4.0-py2.4.egg/zope/app/wsgi/__init__.py", line 124, in config
appsetup.config(options.site_definition, features=features)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.appsetup-3.4.1-py2.4.egg/zope/app/appsetup/appsetup.py", line 111, in config
context = xmlconfig.file(file, context=context, execute=execute)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 610, in file
include(context, name, package)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 546, in include
processxmlfile(f, context)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 378, in processxmlfile
parser.parse(src)
File "xml/sax/expatreader.py", line 107, in parse
File "xml/sax/xmlreader.py", line 123, in parse
File "xml/sax/expatreader.py", line 207, in feed
File "xml/sax/expatreader.py", line 348, in end_element_ns
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 357, in endElementNS
self.context.end()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 542, in end
self.stack.pop().finish()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 690, in finish
actions = self.handler(context, **args)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 546, in include
processxmlfile(f, context)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 378, in processxmlfile
parser.parse(src)
File "xml/sax/expatreader.py", line 107, in parse
File "xml/sax/xmlreader.py", line 123, in parse
File "xml/sax/expatreader.py", line 207, in feed
File "xml/sax/expatreader.py", line 348, in end_element_ns
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 357, in endElementNS
self.context.end()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 542, in end
self.stack.pop().finish()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 690, in finish
actions = self.handler(context, **args)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.11-py2.4.egg/grok/zcml.py", line 48, in grokDirective
do_grok(package.__name__, _context)
zope.configuration.xmlconfig.ZopeXMLConfigurationError: File "/home/sancho/grok-wsgi/etc/site.zcml", line 60.0-60.68
ZopeXMLConfigurationError: File "/home/sancho/grok-wsgi/etc/grok-apps/pymenthon/src/pymenthon/configure.zcml", line 4.2-4.27
AttributeError: 'NoneType' object has no attribute '__name__'
Untitled Python (16-May @ 01:40)
Syntax Highlighted Code
- sancho@mulata:~/grok-wsgi$ ./bin/paster serve etc/grok.ini
- Traceback (most recent call last):
- File "./bin/paster", line 7, in ?
- sys.exit(
- [54 more lines...]
Plain Code
sancho@mulata:~/grok-wsgi$ ./bin/paster serve etc/grok.ini
Traceback (most recent call last):
File "./bin/paster", line 7, in ?
sys.exit(
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 78, in run
invoke(command, command_name, options, args[1:])
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 117, in invoke
exit_code = runner.run(args)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 212, in run
result = self.command()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 227, in command
relative_to=base, global_conf=vars)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 248, in loadapp
return loadapp(
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 193, in loadapp
return loadobj(APP, uri, name=name, **kw)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 214, in loadobj
return context.create()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
return self.object_type.invoke(self)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 153, in invoke
app = context.app_context.create()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
return self.object_type.invoke(self)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 99, in invoke
return fix_call(context.object, context.global_conf, **context.local_conf)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/util/fixtypeerror.py", line 57, in fix_call
val = callable(*args, **kw)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/repoze.grok-0.1.5-py2.4.egg/repoze/grok/bbb.py", line 37, in make_grokapp
app = getWSGIApplication(config_file)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.wsgi-3.4.0-py2.4.egg/zope/app/wsgi/__init__.py", line 134, in getWSGIApplication
db = config(configfile, schemafile, features)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.wsgi-3.4.0-py2.4.egg/zope/app/wsgi/__init__.py", line 124, in config
appsetup.config(options.site_definition, features=features)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.appsetup-3.4.1-py2.4.egg/zope/app/appsetup/appsetup.py", line 111, in config
context = xmlconfig.file(file, context=context, execute=execute)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 610, in file
include(context, name, package)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 546, in include
processxmlfile(f, context)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 378, in processxmlfile
parser.parse(src)
File "xml/sax/expatreader.py", line 107, in parse
File "xml/sax/xmlreader.py", line 123, in parse
File "xml/sax/expatreader.py", line 207, in feed
File "xml/sax/expatreader.py", line 348, in end_element_ns
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 357, in endElementNS
self.context.end()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 542, in end
self.stack.pop().finish()
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 690, in finish
actions = self.handler(context, **args)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 539, in include
f = openInOrPlain(path)
File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 427, in openInOrPlain
fp = open(filename)
zope.configuration.xmlconfig.ZopeXMLConfigurationError: File "/home/sancho/grok-wsgi/etc/site.zcml", line 60.0-60.31
IOError: [Errno 21] Is a directory
Untitled Python (15-May @ 15:29)
Syntax Highlighted Code
- import grok
- from zope.app.container.interfaces import IContainer
- class IClients(IContainer):
- [23 more lines...]
Plain Code
import grok
from zope.app.container.interfaces import IContainer
class IClients(IContainer):
pass
class IShoots(IContainer):
pass
class Clients(grok.Container):
grok.implements(IClients)
class Shoots(grok.Container):
grok.implements(IShoots)
class MyApp(grok.Application, ...):
grok.local_utility(Shoots, provides=IShoots, public=True, name_in_container='shoots')
grok.local_utility(Clients, provides=IClients, public=True, name_in_container='clients')
#####
class SomeView(grok.View):
def update(self):
clients = getUtility(IClients)
...
Untitled Python (15-May @ 14:57)
Syntax Highlighted Code
- import grok
- import appconfig
- from zope.component import getMultiAdapter
- from clients import Clients
- [33 more lines...]
Plain Code
import grok
import appconfig
from zope.component import getMultiAdapter
from clients import Clients
##############################################################################
### M O D E L ################################################################
##############################################################################
class Shoots(grok.Container):
#interface.implements(IClients)
"""Shoots is a type simply for display purposes"""
def __init__(self):
super(Shoots, self).__init__()
self.type = appconfig.SHOOTS_TYPE_STR
##############################################################################
### V I E W ##################################################################
##############################################################################
class ClientList(grok.View):
grok.context(Clients)
def listByTYPE(appconfig.CLIENT_TYPE_STR):
return [ key for key in self.context.keys() if str(type(self.context[key])) == mytype ]
def render(self):
pass
class Index(grok.View):
grok.context(Shoots)
grok.name('index')
def render(self):
view = getMultiAdapter((self.context,self.request), name="clientlist")
return view.listByTYPE(appconfig.CLIENT_TYPE_STR)
Untitled Python (13-May @ 05:17)
Syntax Highlighted Code
- def objVALUES(self):
- return [ (key,self.context[key]) for key in self.context.keys() ]
- def navLIST(self, name):
- [4 more lines...]
Plain Code
def objVALUES(self):
return [ (key,self.context[key]) for key in self.context.keys() ]
def navLIST(self, name):
if name not in appconfig.menuitems.keys():
pass
else:
return appconfig.menuitems[name]
PyTwitFace (24-Apr @ 14:53)
Syntax Highlighted Code
- import twitter, feedparser, socket
- #
- # SETTINGS
- [62 more lines...]
Plain Code
import twitter, feedparser, socket
#
# SETTINGS
#
twitteruser = 'username'
twitterpassword = 'password'
facebook_feed_address = "Your full Facebook status feed URL"
# Will be appended to facebook status
to_append = "(from Facebook)"
# These words will be removed from the
# beginning of your status if present
verbs = ['is', 'has']
# Make sure the script doesn't hang if it can't get through to
# Twitter or Facebook (ie network is down).
timeout = 60 # seconds
socket.setdefaulttimeout(timeout)
#
# FACEBOOK STUFF
#
# Get most recent facebook status.
feed = feedparser.parse(facebook_feed_address)
most_recent_facebook = feed.entries[0].title
# Convert facebook status string into a list of words
most_recent_facebook_words = most_recent_facebook.split()
# Get rid of name from start of string.
del most_recent_facebook_words[0]
# If next word is in verb list, remove it.
if most_recent_facebook_words[0] in verbs:
del most_recent_facebook_words[0]
# Capitalise first word.
most_recent_facebook_words[0] = most_recent_facebook_words[0].title()
# Append selected string.
most_recent_facebook_words.append(to_append)
# Convert back into a string
most_recent_facebook = " ".join(most_recent_facebook_words)
#
# TWITTER STUFF
#
# Set up API
twitterapi = twitter.Api(username=twitteruser, password=twitterpassword)
# Get list of statuses
twitter_statuses = twitterapi.GetUserTimeline(twitteruser)
twitter_statuses_text = [s.text for s in twitter_statuses]
# Check if your current Facebook status
# has already been posted to Twitter
if not most_recent_facebook in twitter_statuses_text:
# If not, post it!
twitterapi.PostUpdate(most_recent_facebook)