__id__
int64
3.09k
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
256
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
5
109
repo_url
stringlengths
24
128
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
6.65k
581M
star_events_count
int64
0
1.17k
fork_events_count
int64
0
154
gha_license_id
stringclasses
16 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
5.76M
gha_stargazers_count
int32
0
407
gha_forks_count
int32
0
119
gha_open_issues_count
int32
0
640
gha_language
stringlengths
1
16
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
9
4.53M
src_encoding
stringclasses
18 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
year
int64
1.97k
2.01k
2,576,980,420,852
ad14f439d87f0d6c106e962f7dff1b74c5c5fb8e
3b99ea8ee668419cb62d5eee4ee27e2f8a26d3b3
/app/routes.py
a0f5e2525d65aa20749fef568c6b969369e391fe
[]
no_license
clashboom/rc
https://github.com/clashboom/rc
8009c06b7fc8f9014f94ec4ba69d39a5f5d80823
f24bcdd2ca11521419e7536dd0b6ec5c38eaca89
refs/heads/master
2020-05-17T22:51:44.146684
2014-02-22T12:41:27
2014-02-22T12:41:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from handlers import * # My URL mappings route_list = [ ('/db', PopulateDB), ('/buy', PurchaseHandler), # ('/sell(?:/)?(?:([0-9]+)/([0-9]+))?', SalesHandler), ('/sell', SalesHandler), ('/prece', ProductSingle), ('/', MainPage) ]
UTF-8
Python
false
false
2,014
2,594,160,291,247
4ad380b3aeb6a8242fa44b284108c77f279b0b1b
cac5b1c22d8a09281f5c5ac2ac2fe3534116d032
/reddit/reddit.py
6b9c448ef1d3dbf7962ef433ad936063b15a21c6
[]
no_license
ngokevin/mp3-Suite
https://github.com/ngokevin/mp3-Suite
fe2944d046ade67e72a6fa180e6bef12b0d7de0f
48669cfdcb33ab6f8aedad7b81a4b83739172799
refs/heads/master
2016-09-06T07:26:38.318607
2011-09-27T22:41:43
2011-09-27T22:41:43
1,615,362
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # Posts a thread on Reddit (options for subreddit, link title, text) import datetime import urllib import urllib2 import cookielib from optparse import OptionParser def login(user, passwd): form_data = urllib.urlencode({'user': user, 'passwd' : passwd}) url = "http://www.reddit.com/api/login" request = urllib2.Request(url, form_data) response = opener.open(request) return response.read() def post_submission(kind, subreddit, title, post): # compose post request if kind == 'self': form_data = urllib.urlencode({'kind':kind, 'sr':subreddit, 'title':title, 'text': post, 'r':subreddit}) elif kind == 'link': form_data = urllib.urlencode({'kind':kind, 'sr':subreddit, 'title':title, 'url': post, 'r':subreddit}) url = "http://www.reddit.com/api/submit" request = urllib2.Request(url, form_data) response = opener.open(request) return response.read() if __name__ == '__main__': # command line arguments parser = OptionParser() parser.add_option("-u", "--username", help="reddit login username", default="", dest="username") parser.add_option("-p", "--password", help="reddit login password", default="", dest="password") parser.add_option("-s", "--subreddit", help="subreddit to post to", default="", dest="subreddit") parser.add_option("-t", "--title", help="title of submission", default="", dest="title") parser.add_option("-l", "--link", help="link to post or text if self post", default="", dest="post") parser.add_option("-k", "--kind", help="self or link", default="self", dest="kind") (options, args) = parser.parse_args() cookie_jar = cookielib.MozillaCookieJar() opener = urllib2.build_opener (urllib2.HTTPCookieProcessor(cookie_jar), urllib2.HTTPHandler()) urllib2.install_opener(opener) response = login(options.username, options.password) response = post_submission(options.kind, options.subreddit, options.title, options.post) print response
UTF-8
Python
false
false
2,011
17,025,250,388,276
690143f5ffbc0c0d35638b25705e374cf38b742c
da73af9dacd2e5161dc5843fe9140d00dfa59685
/enaml/tests/widgets/test_date_edit.py
f7e5a303873866717be0a421f10486c778f8cdd1
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
bgrant/enaml
https://github.com/bgrant/enaml
20d7c1e69a47b7ad926afff132d7f1391642d473
0bc0b61142d2f77b042b527b2780c8c8810184dd
refs/heads/master
2021-01-18T05:57:39.583506
2012-12-02T17:52:59
2012-12-02T17:52:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#------------------------------------------------------------------------------ # Copyright (c) 2012, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ from .enaml_test_case import EnamlTestCase class TestDateEdit(EnamlTestCase): """ Unit tests for the DateEdit widget. """ def setUp(self): enaml_source = """ from enaml.widgets import DateEdit, Window enamldef MainView(Window): DateEdit: pass """ self.parse_and_create(enaml_source) self.server_widget = self.find_server_widget(self.view, "DateEdit") self.client_widget = self.find_client_widget(self.client_view, "DateEdit") def test_set_date_format(self): """ Test the setting of a DateEdit's date_format attribute. """ self.server_widget.date_format = "%m/%d/%Y" assert self.client_widget.date_format == self.server_widget.date_format # XXX: Need to test the receive_date_changed() method
UTF-8
Python
false
false
2,012
11,914,239,311,002
ddee993cea98e17ee074c63b9dae4429528937fd
70a51125175d1305155ab6dbd4f8ccfde5e61bc7
/archive/sort/HillSort.py
d5880bd539b5c39540e702fa824a6511421c1bc9
[]
no_license
xuhongfeng/algorithm-gh
https://github.com/xuhongfeng/algorithm-gh
f29957ca5bcbf67f632e014a2bfe2513827a0da1
0da2c293e74f2d3deed6c1e11045c80be0172a3d
refs/heads/master
2021-01-19T09:41:45.204711
2013-08-12T16:32:42
2013-08-12T16:32:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from util.utils import randomList def hill_sort(list_): if not list_: return size = len(list_) step = int(round(size/2)) while step > 0: inverse_step = 0-step for start in range(step): for i in range(start+step, size, step): temp = list_[i] for j in range(i-step, -1, inverse_step): if list_[j] > temp: list_[j+step] = list_[j] else: list_[j+step] = temp break else: list_[start] = temp step = int(round(step/2.2)) def main(): tList = randomList(100) hill_sort(tList) print tList if __name__ == '__main__': main()
UTF-8
Python
false
false
2,013
14,491,219,695,851
3fb324aab42f6a03050d287bb83c231491ec8b59
12a7b56969524578f1e4dd980913ced19bbc9df5
/project2/urls.py
036c518957334c40965e74cb5a0208e25f557bc5
[]
no_license
mmasterenko/finance
https://github.com/mmasterenko/finance
245b6bba8f920c41e5262f9f9e4a151353b22b9a
41b89b3543a39162e06ff885567a9b5a85ca423d
refs/heads/master
2015-08-12T12:18:46.776037
2014-10-20T20:29:59
2014-10-20T20:29:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'app2.views.index', name='index'), url(r'^app2/', include('app2.urls', namespace='app2')), )
UTF-8
Python
false
false
2,014
15,083,925,167,821
e2d0e25d4ab76d971a525cd9fb3a951a4bb1ba97
9cdaec6153e5cea52804e7f5937357be31ae8368
/gsr.py
5c4a9a9ebb458616359304ee7b2c9bcf971ef9d8
[]
no_license
nj22/gadget-snapshot-reader
https://github.com/nj22/gadget-snapshot-reader
27c13e7878d60f5d371e11e67dbcf1a11c493587
9b98ee8a95355a5f5b9cb0080e1d91a3dcc4fa05
refs/heads/master
2017-04-22T08:50:18.126599
2014-05-08T14:45:50
2014-05-08T14:45:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os.path import struct import numpy as np import sys class Snapshot: """Class in charge of the read-process of every snapshot""" def __init__(self, filename): if os.path.isfile(filename): self.fname = filename self.binfile = open(self.fname, "rb") self.SnapshotData = {} # Process header self.SnapshotData['header'] = self.ProcessHeader() self.SnapshotData['pos'] = self.ProcessParticlesPos() self.SnapshotData['vel'] = self.ProcessParticlesVel() self.SnapshotData['ids'] = self.ProcessParticlesIds() self.SnapshotData['mass'] = self.ProcessParticlesMass() else: print(filename, ": No such file") sys.exit(1) def __exit__(self): self.binfile.close() def getRecordLength(self, instring): "Takes a string of some length and interprets it as a series of bits" return struct.unpack('i', instring)[0] # Header processing def ProcessHeader(self): # because at the end another field is reserved for the length again self.headerlength = self.getRecordLength(self.binfile.read(4)) + 4 header = self.binfile.read(self.headerlength) return self.unpackHeader(header) def unpackHeader(self, instring): fmtstring = "6i8d9i{0:d}x".format(self.headerlength-124) everything = struct.unpack(fmtstring, instring) # list of 6 items giving number of each particle self.Npart = np.array(everything[:6]) self.mpart = np.array(everything[6:12]) self.time = everything[12] self.Ntot = self.Npart.sum() return {'Npart': self.Npart, 'Mpart': self.mpart, 'Time': self.time, 'Ntot': self.Ntot} # Positions processing def ProcessParticlesPos(self): nbytes = self.getRecordLength(self.binfile.read(4)) + 4 body = self.binfile.read(nbytes) return self.unpackPositions(body) def unpackPositions(self, instring): fmtstring = "{0:d}f4x".format(self.Ntot*3) everything = struct.unpack(fmtstring, instring) self.pos = [np.zeros((i, 3)) for i in self.Npart] offset = 0 for i in range(6): chunk = everything[offset*3:offset*3+self.Npart[i]*3] self.pos[i] = np.reshape(chunk, (self.Npart[i], 3)) offset += self.Npart[i] return self.pos # Velocities processing def ProcessParticlesVel(self): nbytes = self.getRecordLength(self.binfile.read(4)) + 4 body = self.binfile.read(nbytes) return self.unpackVelocities(body) def unpackVelocities(self, instring): fmtstring = "{0:d}f4x".format(self.Ntot*3) everything = struct.unpack(fmtstring, instring) self.vel = [np.zeros((i, 3)) for i in self.Npart] offset = 0 for i in range(6): chunk = everything[offset*3:offset*3 + self.Npart[i]*3] self.vel[i] = np.reshape(chunk, (self.Npart[i], 3)) offset += self.Npart[i] return self.vel # Ids processing def ProcessParticlesIds(self): nbytes = self.getRecordLength(self.binfile.read(4)) + 4 body = self.binfile.read(nbytes) return self.unpackIDs(body) def unpackIDs(self, instring): fmtstring = "{0:d}i4x".format(self.Ntot) everything = struct.unpack(fmtstring, instring) self.ID = [np.zeros(i, dtype=np.int) for i in self.Npart] offset = 0 for i in range(6): chunk = everything[offset:offset+self.Npart[i]] self.ID[i] = np.array(chunk, dtype=np.int) offset += self.Npart[i] return self.ID # Mass processing def ProcessParticlesMass(self): nbytes = self.getRecordLength(self.binfile.read(4)) + 4 body = self.binfile.read(nbytes) return self.unpackMasses(body) def unpackMasses(self, instring): self.m = [np.zeros(i) for i in self.Npart] missing_masses = 0 for i in range(6): total = self.Npart[i] mass = self.mpart[i] if total > 0: if mass == 0: missing_masses += total elif mass > 0: self.m[i].fill(mass) fmtstring = "{0:d}f4x".format(missing_masses) everything = struct.unpack(fmtstring, instring) offset = 0 for i in range(6): if self.Npart[i] > 0 and self.mpart[i] == 0: chunk = everything[offset:offset+self.Npart[i]] self.m[i] = np.array(chunk) offset += self.Npart[i] return self.m # TO DO # Density processing # Energy processing # Utils def computeCOM(self, parts=range(6)): ''' Computes center of mass for all the particle types given in the list parts, default all ''' com = np.zeros(3) totM = 0.0 for i in parts: for j in range(self.Npart[i]): com += self.pos[i][j, :]*self.m[i][j] totM += self.m[i][j] com = com/totM self.com = com def to_ascii(self): def get_tuple(key): return tuple(i for i in self.SnapshotData[key]) ids = np.concatenate(get_tuple('ids'), axis = 0) mass = np.concatenate(get_tuple('mass'), axis = 0) pos = np.concatenate(get_tuple('pos'), axis = 0) vel = np.concatenate(get_tuple('vel'), axis = 0) fmtstring = ['%8d', '%1.5e', '% 1.5e', '% 1.5e', '% 1.5e', '% 1.5e', '% 1.5e', '% 1.5e'] np.savetxt(fname+'.asc', np.hstack([zip(ids, mass), pos, vel]), fmt=fmtstring) def get_header(self): return self.SnapshotData['header'] def get_data_by_type(self, ptype): if ptype < 0 or ptype > 5: print(pytpe, "Invalid data type, use only 0, 1, 2, 3, 4 or 5") return None return [self.SnapshotData['ids'][ptype], self.SnapshotData['mass'][ptype], self.SnapshotData['pos'][ptype], self.SnapshotData['vel'][ptype]] def print_data_by_type(self, ptype): if ptype < 0 or ptype > 5: print(pytpe, "Invalid data type, use only 0, 1, 2, 3, 4 or 5") return None for i in range(self.Npart[ptype]): pid = self.SnapshotData['ids'][ptype][i] mass = self.SnapshotData['mass'][ptype][i] posx, posy, posz = self.SnapshotData['pos'][ptype][i] velx, vely, velz = self.SnapshotData['vel'][ptype][i] fmtstring = '%8d %1.5e % 1.5e % 1.5e % 1.5e % 1.5e % 1.5e % 1.5e' print(fmtstring % (pid, mass, posx, posy, posz, velx, vely, velz)) ## Print utils # #def print_header(snap): # for key, val in snap.SnapshotData['header'].iteritems(): # print(key, val) # # #def print_pos(snap): # ptype = 0 # for p in snap.SnapshotData['pos']: # print("Type", ptype, p) # ptype += 1 # # #def print_vel(snap): # vtype = 0 # for v in snap.SnapshotData['vel']: # print("Type", vtype, v) # vtype += 1 # # #def print_ids(snap): # itype = 0 # for i in snap.SnapshotData['ids']: # print("Type", itype, i) # itype += 1 # # #def print_mass(snap): # mtype = 0 # for m in snap.SnapshotData['mass']: # print("Type", mtype, m) # mtype += 1
UTF-8
Python
false
false
2,014
12,335,146,105,814
cb33d13b551aace4e8a425649bc2dc911d0bdf46
0e3f194529d3bfe69fbd6be27dc19d35b6feb8c1
/botsaveprincess2/main.py
1d92fa3fa8b87039c2a9ccdfa1970192f50b6917
[]
no_license
anilsunke/Hackerrank
https://github.com/anilsunke/Hackerrank
73522f88814af66c2eb3f85b96848e5cb5e7e487
b91f358d06040f283e1039f261d58a59434d43fb
refs/heads/master
2016-09-06T23:55:04.117022
2014-02-15T19:38:51
2014-02-15T19:38:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys def nextMove(n,r,c,grid): m_i=r m_j=c p_i=-1 p_j=-1 for i in range(0,n): for j in range(0,n): if grid[i][j]=='p': p_i=i p_j=j break if m_j>p_j: return "LEFT" if m_j<p_j: return "RIGHT" if m_i>p_i: return "UP" if m_i<p_i: return "DOWN" N=int(sys.stdin.readline()) input=sys.stdin.readline().strip().split(' ') r=input[0] c=input[1] grid=[] for i in range(0,N): row=[] input=sys.stdin.readline().strip() for x in input: row.append(x) grid.append(row) nextMove
UTF-8
Python
false
false
2,014
10,831,907,554,290
05298c49168bce891af9c5ef36ebce981630d08f
408ce0266d728811631efe679a8a6e05446de9de
/db.py
76e101aa7ef9284f2f25ab3967a689a3e0a28c15
[]
no_license
ayanamist/Gmail-to-GTalk
https://github.com/ayanamist/Gmail-to-GTalk
3df46bf055c4f43d5258b0a9aab5c63e9491c17b
81c52f3f25432ce7cebf2b33629ea6c32b92aba8
refs/heads/master
2016-09-06T06:10:30.808829
2011-05-04T07:26:36
2011-05-04T07:26:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python from google.appengine.ext import db from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError class MyModel(db.Model): def put(self, **kwargs): while db.WRITE_CAPABILITY: try: result = super(MyModel, self).put(**kwargs) except (db.Timeout, db.InternalError): pass except CapabilityDisabledError: return None else: return result else: return None def delete(self, **kwargs): while db.WRITE_CAPABILITY: try: result = super(MyModel, self).delete(**kwargs) except (db.Timeout, db.InternalError): pass except CapabilityDisabledError: return None else: return result else: return None @classmethod def get_by_key_name(cls, key_names, parent=None, **kwargs): while db.READ_CAPABILITY: try: result = super(MyModel, cls).get_by_key_name(key_names, parent=parent, **kwargs) except (db.Timeout, db.InternalError): pass else: return result else: return None class Mail(MyModel): pass class User(MyModel): access_key = db.StringProperty() access_secret = db.StringProperty() enabled = db.BooleanProperty(default=True) class Session(MyModel): data = db.TextProperty(default=None)
UTF-8
Python
false
false
2,011
635,655,172,165
e20953cab01602ae92158eb6912076be66053090
7473d626aa5265815afe90a086f2f154e9e81396
/quadratic.py
f3bb64dcdf8ac1c2bfe7fa5f712547c0b88a3415
[]
no_license
Rishabh570/helloworld
https://github.com/Rishabh570/helloworld
baf10dcf2ef1c724fe66ed3696116dd94dcee582
b944b0875c26aacf91577d264cea3c9b33834428
refs/heads/master
2017-04-25T18:45:54.920301
2010-02-21T12:48:41
2010-02-21T12:48:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Module contains a function that solves quadratic equation.""" import math EPSILON = 10**(-9) def solve_quadratic(a, b, c): """Find real or complex roots of equation ax**2 + bx + c = 0. >>> solve_quadratic(0, 2, 1) Traceback (most recent call last): ... ValueError: equation is not quadratic >>> solve_quadratic(1, -4, 4) (2.0,) >>> solve_quadratic(1, -5, 6) (2.0, 3.0) >>> [solve_quadratic(1, 0, k**2) for k in range(1, 5)] [(-1j, 1j), (-2j, 2j), (-3j, 3j), (-4j, 4j)] """ if abs(a) < EPSILON: raise ValueError("equation is not quadratic") discriminant = b**2 - 4 * a * c def sqrt(x): return math.sqrt(x) if x >= 0 else complex(0, math.sqrt(-x)) roots = [(-b + k * sqrt(discriminant)) / (2.0 * a) for k in (-1, 1)] return (roots[0],) if abs(discriminant) < EPSILON else tuple(roots) if __name__ == "__main__": import doctest doctest.testmod()
UTF-8
Python
false
false
2,010
6,803,228,199,438
8875bd868cf2e21043e30687211510c2244cab7e
8f9e0b8f259f0da134abe0241fdef6ba666b67a9
/tests/python/pants_test/base/test_address.py
b61ce870cddc3fddf14e8e8e0d4467c7f44932be
[ "Apache-2.0" ]
permissive
luciferous/pants
https://github.com/luciferous/pants
35c0438ffaaa8501a8fe5bbf3ae9c0976c46bb39
fe211bde2837ce99031175cde3e46b7385a098d0
refs/heads/master
2021-01-21T23:38:46.814557
2014-04-17T22:42:04
2014-04-17T22:42:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import os import unittest from contextlib import contextmanager import pytest from twitter.common.contextutil import pushd, temporary_dir from twitter.common.dirutil import touch from pants.base.address import Address from pants.base.build_environment import set_buildroot class AddressTest(unittest.TestCase): @contextmanager def workspace(self, *buildfiles): with temporary_dir() as root_dir: set_buildroot(root_dir) with pushd(root_dir): for buildfile in buildfiles: touch(os.path.join(root_dir, buildfile)) yield os.path.realpath(root_dir) def assertAddress(self, root_dir, path, name, address): self.assertEqual(root_dir, address.buildfile.root_dir) self.assertEqual(path, address.buildfile.relpath) self.assertEqual(name, address.target_name) def test_full_forms(self): with self.workspace('a/BUILD') as root_dir: self.assertAddress(root_dir, 'a/BUILD', 'b', Address.parse(root_dir, 'a:b')) self.assertAddress(root_dir, 'a/BUILD', 'b', Address.parse(root_dir, 'a/:b')) self.assertAddress(root_dir, 'a/BUILD', 'b', Address.parse(root_dir, 'a/BUILD:b')) self.assertAddress(root_dir, 'a/BUILD', 'b', Address.parse(root_dir, 'a/BUILD/:b')) def test_default_form(self): with self.workspace('a/BUILD') as root_dir: self.assertAddress(root_dir, 'a/BUILD', 'a', Address.parse(root_dir, 'a')) self.assertAddress(root_dir, 'a/BUILD', 'a', Address.parse(root_dir, 'a/BUILD')) self.assertAddress(root_dir, 'a/BUILD', 'a', Address.parse(root_dir, 'a/BUILD/')) def test_top_level(self): with self.workspace('BUILD') as root_dir: self.assertAddress(root_dir, 'BUILD', 'c', Address.parse(root_dir, ':c')) self.assertAddress(root_dir, 'BUILD', 'c', Address.parse(root_dir, '.:c')) self.assertAddress(root_dir, 'BUILD', 'c', Address.parse(root_dir, './:c')) self.assertAddress(root_dir, 'BUILD', 'c', Address.parse(root_dir, './BUILD:c')) self.assertAddress(root_dir, 'BUILD', 'c', Address.parse(root_dir, 'BUILD:c')) def test_parse_from_root_dir(self): with self.workspace('a/b/c/BUILD') as root_dir: self.assertAddress(root_dir, 'a/b/c/BUILD', 'c', Address.parse(root_dir, 'a/b/c', is_relative=False)) self.assertAddress(root_dir, 'a/b/c/BUILD', 'c', Address.parse(root_dir, 'a/b/c', is_relative=True)) def test_parse_from_sub_dir(self): with self.workspace('a/b/c/BUILD') as root_dir: with pushd(os.path.join(root_dir, 'a')): self.assertAddress(root_dir, 'a/b/c/BUILD', 'c', Address.parse(root_dir, 'b/c', is_relative=True)) with pytest.raises(IOError): Address.parse(root_dir, 'b/c', is_relative=False)
UTF-8
Python
false
false
2,014
3,453,153,721,949
0d5d8bb3ae9073c0b0ce5ca4f00c85820ec89dea
20d823ce69168f37eab2e0db903483908fcc070b
/util.py
0f5e6d939496101660a1cb1a3998fc4d12c9db2c
[]
no_license
keithfancher/Pent
https://github.com/keithfancher/Pent
70e23533b601513dc2b52163c709e25f91cce516
811ab2637d87a124543b3e9080dcebd9b72af01f
refs/heads/master
2016-09-01T22:18:06.947175
2011-09-29T02:51:16
2011-09-29T02:51:16
2,452,311
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import pygame def print_text(screen, text, size, color, **kwargs): """Writes text to a given surface using pygame.font, or fails with a warning if pygame.font isn't available. The **kwargs are passed to get_rect(), and can be used to easily position the text on the target surface.""" if not pygame.font: print "Warning: fonts disabled. Install pygame.font!" else: # font = pygame.font.Font('fonts/inconsolata.otf', size) font = pygame.font.Font(None, size) text_surface = font.render(text, True, color) text_rect = text_surface.get_rect(**kwargs) screen.blit(text_surface, text_rect) def shut_down(screen, message="Shutting everything down..."): """There's an annoying delay while Pygame shuts down -- this function gives the user some visual indication that things are closing down properly, and the game's not just hanging.""" print message print_text(screen, message, 25, pygame.Color('red'), midbottom=screen.get_rect().midbottom) pygame.display.flip() sys.exit()
UTF-8
Python
false
false
2,011
10,222,022,214,146
d1533cea856e8f17c9f69b3b303176d92397df57
eef4b7d6dc33aa882f1c7e72ed097ae37bf72403
/formencode_jinja2/formfill.py
1b3fca2cb94e81e6f2b1f0657c57e291fa41862d
[ "MIT" ]
permissive
yoloseem/FormEncode-Jinja2
https://github.com/yoloseem/FormEncode-Jinja2
40659de323e3355fdae15509cf30a3ddc5c04590
85da5b8a899191268d05ec936056c6e4005aa73a
refs/heads/master
2021-01-18T11:40:42.272517
2013-04-12T07:34:14
2013-04-12T07:34:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import collections import formencode.htmlfill import jinja2 import jinja2.ext from jinja2 import nodes class FormFillExtension(jinja2.ext.Extension): """Jinja2 extension for filling HTML forms via :mod:`formencode.htmlfill`. For example, this code:: {% formfill {'username': 'robert', 'email': '[email protected]'} with {'username': 'This name is invalid'} %} <form action="/register" method="POST"> <input type="text" name="username" /> <form:error name="username"> <input type="password" name="password" /> <input type="email" name="email" /> </form> {% endformfill %} will be rendered like below:: <form action="/register" method="POST"> <input type="text" name="username" class="error" value="robert" /> <span class="error-message">This name is invalid</span> <input type="password" name="password" value="" /> <input type="email" name="email" value="[email protected]" /> </form> :param defaults: a dict-like object that contains default values of the input field (including ``select`` and ``textarea``) surrounded in the template tag. Keys contain a value of ``name`` attribute of the input field, and values contain its default value. :param errors: a dict-like object that contains messages for the error of the input fields. this value will also effect ``class`` attribute of the input field. :returns: rendered forms """ tags = frozenset(['formfill']) def parse(self, parser): token = next(parser.stream) defaults = parser.parse_expression() if parser.stream.skip_if('name:with'): errors = parser.parse_expression() else: errors = nodes.Const({}) if isinstance(defaults, nodes.Name): defaults = nodes.Getattr(nodes.ContextReference(), defaults.name, self.environment) if isinstance(errors, nodes.Name): errors = nodes.Getattr(nodes.ContextReference(), errors.name, self.environment) body = parser.parse_statements(['name:endformfill'], drop_needle=True) return nodes.CallBlock( self.call_method('_formfill_support', (defaults, errors)), (), (), body).set_lineno(token.lineno) def _formfill_support(self, defaults, errors, caller): if not isinstance(defaults, collections.Mapping): raise TypeError("argument 'defaults' should be " "collections.Mapping, not {0!r}".format(defaults)) if not isinstance(errors, collections.Mapping): raise TypeError("argument 'errors' should be collections.Mapping, " "not {0!r}".format(errors)) rv = caller() return formencode.htmlfill.render( rv, defaults, errors, error_formatters=self.ERROR_FORMATTERS) ERROR_FORMATTERS = { 'default': lambda msg: u'<span class="error-message">{0}</span>' .format(msg), }
UTF-8
Python
false
false
2,013
16,217,796,523,926
53ad5aa3603def9c2a3c8f3c5fc2c799a5251538
e1d3d28b84e91b1c5f22f03a2969565c86d51a2e
/makeHtml.py
e0474d921f70373067f7f6ef87cea5254cfd067b
[]
no_license
ralekar/geddit
https://github.com/ralekar/geddit
8c7f070066b76f2a42f4a2d5e2ce3eb5d646f4b7
282040a82ffd0ee39fd37ceef22b5d41fbe83368
refs/heads/master
2016-08-07T09:53:53.894600
2013-09-26T00:41:16
2013-09-26T00:41:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Shutterfly: def __init__(self,code,name): self.code = code self.name = name class TinyPrints: def __init__(self,code,name): self.code = code self.name = name '''class Html: def __init__(self): self.count = 1 ''' def html(sfly,tp,count): sfly_tag1 = "<tr><td><div id=\"content\" style=\"background-color:"+sfly.code+"; height: 40px; width: 110px;\">" sfly_tag2 = "</div></td><td>"+sfly.name+"name<input hidden=\"text\" value=\""+sfly.code+"\"></td>" tp_tag1 = "<td><div id=\"content\" style=\"background-color:"+tp.code+"; height: 40px; width: 120px;\">" tp_tag2 = "</div></td><td>"+tp.name+"<input hidden=\"text\" value=\""+tp.code+"\"></td>" radioM="<td><input type=\"radio\" name=\"group"+str(count)+"\" value=\"yes\">matched</td>" radioNM="<td><input type=\"radio\" name=\"group"+str(count)+"\" value=\"no\">not matched</td></tr>" return sfly_tag1+sfly_tag2+tp_tag1+tp_tag2+radioM+radioNM if __name__== "__main__": fread = open("colors_everything.txt","r").readlines() count=1 for line in fread: cells = line.split("==>") c = cells[0].split(":") sfly = Shutterfly("#"+c[0].strip(),c[1].strip()) d = cells[1].split(":") tp = TinyPrints("#"+d[0].strip(),d[1].strip()) print html(sfly,tp,count) count+=1
UTF-8
Python
false
false
2,013
15,101,105,064,942
f504607fc72c291095d157e7bb947c8460c6ccf9
1e38fa6bc4613e9c6e2604228a2a4613bbb837b1
/panel/core/system.py
adb403d41911a6fa86be5b52bcaf92ec0df399ba
[]
no_license
itamarjp/webhosting_control_panel
https://github.com/itamarjp/webhosting_control_panel
31e54665f423f916b2a185c69cf7b7b91406dbcf
ec00ab8571d91f19528386370322cddc128d4705
refs/heads/master
2016-09-10T09:26:00.827438
2013-09-20T02:13:12
2013-09-20T02:13:12
10,712,894
0
1
null
false
2013-09-18T08:37:34
2013-06-15T22:33:51
2013-09-18T08:28:09
2013-09-16T22:46:42
648
null
1
2
Python
null
null
# -*- coding: utf-8 -*- import platform def __distribution(): if platform.system() == 'Linux': return platform.linux_distribution()[0] else: raise NotImplementedError('Unsupported platform') def __version(): if platform.system() == 'Linux': return platform.linux_distribution()[1] else: raise NotImplementedError('Unsupported platform') distribution = __distribution() version = __version()
UTF-8
Python
false
false
2,013
7,928,509,659,280
74f0dc999189b179f1d2816bdf065624143dd4a2
780c87a412fac2d910cae28e4442ab36d717449f
/code/zato-admin/src/zato/admin/web/views/load_balancer.py
fb4e845bfaad1116733ec920c7b80d44f6adabd4
[]
no_license
dsuch/zato
https://github.com/dsuch/zato
4d9553ef461f23c7206307c5a505ab50c69a0aea
518f54ed66913d1f62d1ad8ca637d485184e0ffd
refs/heads/master
2018-05-30T09:29:00.584784
2012-12-15T20:26:08
2012-12-15T20:26:08
3,575,501
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Copyright (C) 2010 Dariusz Suchojad <dsuch at gefira.pl> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import json, logging from traceback import format_exc # OrderedDict is new in 2.7 try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict # Django from django.contrib import messages from django.http import HttpResponse from django.shortcuts import redirect from django.template.response import TemplateResponse # Zato from zato.admin.web import from_utc_to_user from zato.admin.web.forms.load_balancer import ManageLoadBalancerForm, RemoteCommandForm, \ ManageLoadBalancerSourceCodeForm from zato.admin.web.views import get_lb_client, meth_allowed from zato.common.haproxy import haproxy_stats, Config from zato.common.odb.model import Cluster logger = logging.getLogger(__name__) def _haproxy_alive(client): """ Check whether HAProxy is up and running. If 'status' is True then HAProxy is alive, sets 'status' to False otherwise and fills in the 'error' attribute with the details of an exception caught. """ haproxy_alive = {} try: is_alive = client.is_haproxy_alive() except Exception, e: haproxy_alive["status"] = False haproxy_alive["error"] = format_exc(e) else: haproxy_alive["status"] = True return haproxy_alive def _haproxy_stat_config(client=None, lb_config=None): """ Return the configuration of the HAProxy HTTP stats interface. """ if not lb_config: lb_config = client.get_config() # Stats URI is optional try: stats_uri = lb_config["defaults"]["stats_uri"] except KeyError, e: return None, None else: stats_port = lb_config["frontend"]["front_http_plain"]["bind"]["port"] return stats_uri, stats_port def _get_validate_save_flag(cluster_id, req_post): """ A convenience function for checking we were told to validate & save a config or was it a request for validating it only. """ if "validate_save" in req_post: save = True elif "validate" in req_post: save = False else: msg = "Expected a flag indicating what to do with input data. cluster_id:[{cluster_id}] req.POST:[{post}]" msg = msg.format(cluster_id=cluster_id, post=req_post) logger.error(msg) raise Exception(msg) return save def _client_validate_save(req, meth, *args): """ A convenience function for validating or validating & saving a config file on a remote SSL XML-RPC server. """ save = args[1] try: meth(*args) except Exception, e: msg = "Caught an exception while invoking the load-balancer agent, e={e}".format(e=format_exc(e)) logger.error(msg) messages.add_message(req, messages.INFO, msg, extra_tags="failure") else: if save: msg = "Config validated and saved successfully" else: msg = "Config is valid, it's safe to save it" messages.add_message(req, messages.INFO, msg, extra_tags="success") @meth_allowed("GET", "POST") def remote_command(req, cluster_id): """ Execute a HAProxy command. """ cluster = req.zato.odb.query(Cluster).filter_by(id=cluster_id).one() client = get_lb_client(cluster) haproxy_alive = _haproxy_alive(client) cluster.stats_uri, cluster.stats_port = _haproxy_stat_config(client=client) # We need to know the HAProxy version before we can build up the select box # on the form. commands = haproxy_stats[("1", "3")] version_info = tuple(client.haproxy_version_info()) if version_info >= ("1", "4"): commands.update(haproxy_stats[("1", "4")]) if req.method == "POST": result = client.execute_command(req.POST["command"], req.POST["timeout"], req.POST.get("extra", "")) if not result.strip(): result = "(empty result)" initial={"result":result} for k, v in req.POST.items(): if k != "result": initial[k] = v form = RemoteCommandForm(commands, initial) else: form = RemoteCommandForm(commands) return_data = {"form":form, "cluster":cluster, "haproxy_alive":haproxy_alive} return TemplateResponse(req, 'zato/load_balancer/remote_command.html', return_data) @meth_allowed("GET") def manage(req, cluster_id): """ GUI for managing HAProxy configuration. """ cluster = req.zato.odb.query(Cluster).filter_by(id=cluster_id).one() client = get_lb_client(cluster) lb_start_time = from_utc_to_user(client.get_uptime_info(), req.zato.user_profile) lb_config = client.get_config() lb_work_config = client.get_work_config() lb_work_config['verify_fields'] = ', '.join(['%s=%s' % (k,v) for (k, v) in sorted(lb_work_config['verify_fields'].items())]) form_data = { 'global_log_host': lb_config['global_']['log']['host'], 'global_log_port': lb_config['global_']['log']['port'], 'global_log_level': lb_config['global_']['log']['level'], 'global_log_facility': lb_config['global_']['log']['facility'], 'timeout_connect': lb_config['defaults']['timeout_connect'], 'timeout_client': lb_config['defaults']['timeout_client'], 'timeout_server': lb_config['defaults']['timeout_server'], 'http_plain_bind_address':lb_config['frontend']['front_http_plain']['bind']['address'], 'http_plain_bind_port':lb_config['frontend']['front_http_plain']['bind']['port'], 'http_plain_log_http_requests':lb_config['frontend']['front_http_plain']['log_http_requests'], 'http_plain_maxconn':lb_config['frontend']['front_http_plain']['maxconn'], 'http_plain_monitor_uri':lb_config['frontend']['front_http_plain']['monitor_uri'], } backends = {} for backend_type in lb_config['backend']: for name in lb_config['backend'][backend_type]: # Is it a server? if 'address' in lb_config['backend'][backend_type][name]: if not name in backends: backends[name] = {} backends[name][backend_type] = {} backends[name][backend_type]['address'] = lb_config['backend'][backend_type][name]['address'] backends[name][backend_type]['port'] = lb_config['backend'][backend_type][name]['port'] backends[name][backend_type]['extra'] = lb_config['backend'][backend_type][name]['extra'] backends = OrderedDict(sorted(backends.items(), key=lambda t: t[0])) form = ManageLoadBalancerForm(initial=form_data) haproxy_alive = _haproxy_alive(client) cluster.stats_uri, cluster.stats_port = _haproxy_stat_config(lb_config=lb_config) servers_state = client.get_servers_state() return_data = {'cluster':cluster, 'lb_start_time':lb_start_time, 'lb_config':lb_config, 'lb_work_config':lb_work_config, 'form':form, 'backends':backends, 'haproxy_alive':haproxy_alive, 'servers_state':servers_state} return TemplateResponse(req, 'zato/load_balancer/manage.html', return_data) @meth_allowed("POST") def validate_save(req, cluster_id): """ A common handler for both validating and saving a HAProxy config using a pretty GUI form. """ save = _get_validate_save_flag(cluster_id, req.POST) cluster = req.zato.odb.query(Cluster).filter_by(id=cluster_id).one() client = get_lb_client(cluster) lb_config = Config() lb_config.global_["log"] = {} lb_config.frontend["front_http_plain"] = {} lb_config.frontend["front_http_plain"]["bind"] = {} lb_config.global_["log"]["host"] = req.POST["global_log_host"] lb_config.global_["log"]["port"] = req.POST["global_log_port"] lb_config.global_["log"]["level"] = req.POST["global_log_level"] lb_config.global_["log"]["facility"] = req.POST["global_log_facility"] lb_config.defaults["timeout_connect"] = req.POST["timeout_connect"] lb_config.defaults["timeout_client"] = req.POST["timeout_client"] lb_config.defaults["timeout_server"] = req.POST["timeout_server"] lb_config.frontend["front_http_plain"]["bind"]["address"] = req.POST["http_plain_bind_address"] lb_config.frontend["front_http_plain"]["bind"]["port"] = req.POST["http_plain_bind_port"] lb_config.frontend["front_http_plain"]["log_http_requests"] = req.POST["http_plain_log_http_requests"] lb_config.frontend["front_http_plain"]["maxconn"] = req.POST["http_plain_maxconn"] lb_config.frontend["front_http_plain"]["monitor_uri"] = req.POST["http_plain_monitor_uri"] for key, value in req.POST.items(): if key.startswith("bck_http"): for token in("address", "port", "extra"): splitted = key.split(token) if splitted[0] == key: continue # We don't have the token in that key. backend_type, backend_name = splitted # Get rid of underscores left over from the .split above. backend_type = backend_type[:-1] backend_name = backend_name[1:] lb_config.backend.setdefault(backend_type, {}) lb_config.backend[backend_type].setdefault(backend_name, {}) lb_config.backend[backend_type][backend_name][token] = value # Invoke the LB agent _client_validate_save(req, client.validate_save, lb_config, save) return redirect("lb-manage", cluster_id=cluster_id) @meth_allowed("GET") def manage_source_code(req, cluster_id): """ Source code view for managing HAProxy configuration. """ cluster = req.zato.odb.query(Cluster).filter_by(id=cluster_id).one() client = get_lb_client(cluster) cluster.stats_uri, cluster.stats_port = _haproxy_stat_config(client=client) haproxy_alive = _haproxy_alive(client) source_code = client.get_config_source_code() form = ManageLoadBalancerSourceCodeForm(initial={"source_code":source_code}) return_data = {"form": form, "haproxy_alive":haproxy_alive, "cluster":cluster} return TemplateResponse(req, 'zato/load_balancer/manage_source_code.html', return_data) @meth_allowed("POST") def validate_save_source_code(req, cluster_id): """ A common handler for both validating and saving a HAProxy config using the raw HAProxy config file's view. """ cluster = req.zato.odb.query(Cluster).filter_by(id=cluster_id).one() save = _get_validate_save_flag(cluster_id, req.POST) # Invoke the LB agent client = get_lb_client(cluster) _client_validate_save(req, client.validate_save_source_code, req.POST["source_code"], save) return redirect("lb-manage-source-code", cluster_id=cluster_id) @meth_allowed("GET") def get_addresses(req, cluster_id): """ Return JSON-formatted addresses known to HAProxy. """ cluster = req.zato.odb.query(Cluster).filter_by(id=cluster_id).one() client = get_lb_client(cluster) addresses = {} addresses["cluster"] = {"lb_host": cluster.lb_host, "lb_agent_port":cluster.lb_agent_port} try: lb_config = client.get_config() except Exception, e: msg = "Could not get load balancer's config, client:[{client!r}], e:[{e}]".format(client=client, e=format_exc(e)) logger.error(msg) lb_config = None addresses["cluster"]["lb_config"] = lb_config return HttpResponse(json.dumps(addresses))
UTF-8
Python
false
false
2,012
7,645,041,837,708
0b4f31cda7b5a021b7fc55d0e4fe173d535e1cb7
942d5347355d3faef7ff37dc3d71c013a61ce2db
/auto_docstr.py
72b7574d10cb4dfa99eb1c6b49716ce842a96132
[]
no_license
BloodD/my-utils
https://github.com/BloodD/my-utils
542d5be1a99594e7f349c1c74d54733450219637
0c937dd77f5a7f62ae1440a4601cf7be3dc5001a
refs/heads/master
2021-01-22T07:04:08.034883
2014-03-03T07:00:04
2014-03-03T07:00:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: #-*- coding: utf-8 -*- ############################################################ #auto generate docstr Date:2013.03.12 ############################################################ """ usage: docstr_generator [-h] [-r dir] -s source Extract .py file docstring and insert into the .py file. optional arguments: -h, --help show this help message and exit -r dir choose dir mode -s source source file or dir. """ import os import sys import re import argparse parser = argparse.ArgumentParser(description = '''Extract .py file docstring and insert into the .py file.''', prog = 'docstr_generator') parser.add_argument('-r', dest = 'dir', required = False, metavar = 'dir', help = 'choose dir mode') parser.add_argument('-s', dest = 'source', required = True, metavar = 'source', help = 'source file or dir.') args = parser.parse_args() if args.dir != None: print 'dir mode test.' pass else: print '--------------------------------------------------------------' print 'Target command file is: %s'%args.source count = 0 num = 0 lines=[] f = open(args.source,"r+") content = f.readlines() for line in content: if line.find('"""' )!=-1 and count<2: count=count+1 num=num+1 lines.append(num) elif count==2: break else: num=num+1 docstring = content[lines[0]:lines[1]-1] for dstr in docstring: content.remove(dstr) cmd = "python %s -h>tmp"%args.source print '-----------------------------------------------------------------' print "Run>>>", cmd print '-----------------------------------------------------------------' os.system(cmd) tmp = open('tmp',"r+") newdocstr = tmp.readlines() print "New docstring is:" print ' '.join(newdocstr) print '-----------------------------------------------------------------' ln = lines[0] for newstr in newdocstr: content.insert(ln,newstr) ln = ln+1 content.insert(ln,'\n') print content content = [l.replace('\r\n','\n') for l in content] print content f.close() wf = open(args.source,"w") wf.writelines(content) wf.close() tmp.close() os.remove('tmp') print "Insert it into .py file is done!" print '-----------------------------------------------------------------'
UTF-8
Python
false
false
2,014
18,073,222,400,404
663b061737d7a3101ee078ef5f76f2a7239729d4
5443274af9ce35718d8865f8580b488192fb5466
/v3/k_means_creator.py
fa6a6303123f8df464ff0fc70d9600dd9e87c47f
[ "GPL-3.0-or-later", "LGPL-2.1-or-later", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-3.0-only" ]
non_permissive
kosonya/smartspacedatan
https://github.com/kosonya/smartspacedatan
bfb095db7e7dc4586d38ffe3889743344f090f26
ca641d40cb4b86fac287b6a6c0fce0bb2461ed55
refs/heads/master
2021-05-26T17:42:21.478912
2013-12-11T06:58:06
2013-12-11T06:58:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import time import numpy import mdp import pickle import traceback import dataprovider group_by = 60 def _main(order = 2, pnodefile = "knode.p"): global group_by report = "" coeffs = raw_readings_norm_coeffs = {"temp": 100, "light": 100, "humidity" : 100, "pressure": 1e5, "audio_p2p": 100, "motion" : 1} try: numpy.set_printoptions(precision=1, linewidth=284, threshold=40, edgeitems=13) if True: data_provider = dataprovider.DataProvider(order=order, debug=True, start_time = 1379984887, stop_time = 1379984887+3600*24*10, device_list = ["17030002"], eliminate_const_one=True, device_groupping="numpy_matrix", raw_readings_norm_coeffs = coeffs) else: data_provider = dataprovider.DataProvider(order=1, debug=True, eliminate_const_one=True, device_groupping="numpy_matrix", raw_readings_norm_coeffs = coeffs) pnode = mdp.nodes.KMeansClassifier(num_clusters = 4) processing_time_start = time.asctime() processing_time_start_s = time.time() print "Processing has started:", processing_time_start except Exception: tr = traceback.format_exc().splitlines() for line in tr: report += line + "\n" return try: for data in data_provider: example_pols_in = data[0] example_pols_in = example_pols_in.reshape(1, example_pols_in.size) pnode.train(data) print "\n" processing_time_end = time.asctime() processing_time_end_s = time.time() except Exception: tr = traceback.format_exc().splitlines() for line in tr: report += line + "\n" try: print "Stopping training..." stopping_time_start = time.asctime() print stopping_time_start stopping_time_start_s = time.time() pnode.stop_training() stopping_time_end = time.asctime() stopping_time_end_s = time.time() print "Training stopped:", stopping_time_end print "Dumping K-means node with pickle to:", pnodefile f = open(pnodefile, "wb") pickle.dump(pnode, f) f.close() print "Dumped successfully" except Exception: tr = traceback.format_exc().splitlines() for line in tr: report += line + "\n" try: report += "K-means Node was dumped to %s with pickle\n" % pnodefile report += "Processing started at:\t" + str(processing_time_start) + "\n" report += "Processing end at:\t" + str(processing_time_end) + "\n" report += "It took %d seconds" % (processing_time_end_s - processing_time_start_s) + "\n" report += "Stopping started at:\t" + str(stopping_time_start) + "\n" report += "Stopping stopped at:\t" + str(stopping_time_end) + "\n" report += "It took %d seconds" % (stopping_time_end_s - stopping_time_start_s) + "\n" report += "Total time elapsed:\t%d seconds" % (stopping_time_end_s - processing_time_start_s) + "\n" + "\n" report += "Polynomial order:\t" + str(order) + "\n" except Exception: tr = traceback.format_exc().splitlines() for line in tr: report += line + "\n" print report return report def main(): for order in [2]: print "%d order processing has started" % order report = _main(order = order, pnodefile = ("%d_order_knode.p" % order)) print "%d order processing has stopped" % order f = open( ("%d_order_k_means_report.txt" % order), "w") f.write(report) f.close() print "Report is written to", ("%d_order_k_means_report.txt" % order) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,013
2,130,303,802,926
e4481ca9ce7cba96fb87687621414f0aaee32fd5
dafb8a65df7657968ead69517e90483f7dee018e
/truth.py
6acc938322ae9959b9f3bdf9f9d91837f6e3794d
[]
no_license
tonumikk/Learn-Python
https://github.com/tonumikk/Learn-Python
31b5ae34de19c0f3d2ac8181d51d6345069178b1
2df8167d8d381b02ce3a00f888c02881050c7cbf
refs/heads/master
2021-01-19T11:20:58.032659
2012-03-05T20:41:13
2012-03-05T20:41:13
2,513,289
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Programmatic way to Truth Tables """ print "These exercises will test you how well you know the truth tables" print "The computer asks you a question and you need to enter 'True' or 'False'" print "What is 'not False'" answer = raw_input("Type your answer: ") if answer == "True": print "Correct - good job!"; else: print "Incorrect - try again." print "What is 'not True'" answer = raw_input("Type your answer: ") if answer == "False": print "Correct - good job!"; else: print "Incorrect - try again."
UTF-8
Python
false
false
2,012
910,533,067,037
8e78350890af541a988a722f37bac88576709aed
1e754d56215f70bf5d16aa18bf064cd6c804bbca
/OtherCodeIhaveYetToSiftThrough/CtoDCPU/Python Progs/Compiler/setup.py
559c01ff7392905b75a1d43b339289b6e56d2419
[]
no_license
alex-polosky/MyOldCode
https://github.com/alex-polosky/MyOldCode
b4cd2113b33c0bc7a985f1f1c27a1081a874ad00
a4c80f14b0aad05621e517999b8eaf991808a08f
refs/heads/master
2020-02-05T17:14:37.241508
2014-05-01T04:07:06
2014-05-01T04:07:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from distutils.core import setup import py2exe import sys sys.argv.append('py2exe') setup( name = 'Py DCPU ASM', version = '1.1', author = 'LordHondros', author_email = '[email protected]', description = 'Console', options = { 'py2exe': { 'bundle_files': 1, } }, console=['pydcpuasm.py'], zipfile = None, )
UTF-8
Python
false
false
2,014
10,428,180,599,209
2939f943f720619a7393397cffa11944685817ff
280fab1ce77c007cbaaf4b277bd1b84c853ce4d9
/HW6/problem1a.py
4c8af02bed6025fa156c2e6943cd4d5176a5addc
[]
no_license
pcp135/C-AD
https://github.com/pcp135/C-AD
36f428d7a2525de237d841ea9c44ff0c30d5eb2e
4525e672e0b7c8baaab41169dee29a6a3e431edf
refs/heads/master
2016-08-05T00:55:43.802125
2013-10-26T22:26:39
2013-10-26T22:26:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys Numbers=set(map(int,file(sys.argv[1],"r"))) print "Dict Loaded" counter = 0 for t in range(-10000,10001): for x in Numbers: if t-x in Numbers and t!=x: print "%s + %s = %s" % (x,t-x,t) counter+=1 break print counter
UTF-8
Python
false
false
2,013
18,811,956,771,948
7b4dcbba3e0f27a3d65d355b44f08a48251d1ad7
5c023bf2e7fea93a4841fefc9175ecd0b6beb772
/ana/seidner/plot_spec_test.py
67189b9e07d53080e3d242c19a61c31fca2e5bf4
[ "MIT" ]
permissive
timy/dm_spec
https://github.com/timy/dm_spec
4f06a4fc26e2090fcd4e2c87e184a9fef0a04da7
1e50922f43612a638e56a2877b8500d30e191217
refs/heads/master
2021-01-20T21:53:24.381412
2014-09-16T13:14:40
2014-09-16T13:14:40
22,839,560
3
4
null
null
null
null
null
null
null
null
null
null
null
null
null
import matplotlib.pyplot as plt import numpy as np n_t = 2200 #data = np.loadtxt("res/ppar_2d_ 3_2.dat") #data = np.loadtxt("res/ppar_test.dat") #data = np.loadtxt("res/spec_test.dat") #w = data[:,0] #spec = data[:,1]**2 + data[:,2]**2 data = np.loadtxt("res/spec_2d_ 3_2.dat") w = data[::n_t, 0] r_sp = data[::n_t, 2] i_sp = data[::n_t, 3] sp = r_sp**2 + i_sp**2 plt.plot( w, sp, marker='.' ) plt.show() #w_y, w_x = data[::n_x, 0], data[:n_x, 1] # print w_x[699], w_x[700], w_x[701] # dat = data[700:1201, 2] + data[700:1201, 3]*1j # sp = np.fft.fft(dat) # freq = np.fft.fftfreq(501) * 1.0 / 1.88492e-4 # plt.plot( freq, sp.real**2 + sp.imag**2 ) # plt.show() #dat = data[700:, 3] #print w_x #spec = data[:n_x, 2]**2 + data[:n_x, 3]**2 #plt.plot(spec) #plt.show()
UTF-8
Python
false
false
2,014
4,870,492,917,188
12e4b8d0470635832aff190567cd7421dfb633a8
15d45393001541fd3ea71e9fad6efb7541293920
/testapp/validapp/urls.py
4422a4fd83b270476c60c0e01d9d5e9f08a479f3
[ "BSD-2-Clause" ]
permissive
lalo73/django-liar
https://github.com/lalo73/django-liar
8b8a34be62edf7d9b712ac86c1de04f4ec2c3c72
23d56f5cd5a235c6ddd480be4745983df49b4818
refs/heads/master
2021-01-22T16:25:56.027096
2013-10-17T03:10:48
2013-10-17T03:10:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! coding: utf-8 from django.conf.urls import patterns, include, url from django.http import HttpResponse def view(request, *args, **kwargs): return HttpResponse('This works!') urlpatterns = patterns( '', url(r'^some/valid/path/$', view), )
UTF-8
Python
false
false
2,013
13,786,845,022,598
7807186413231e1d00a846418e608638e8293b3b
4d4e786ba71e1f5bafe80ee2e1882718c63a7a3a
/apps/proposals/templatetags/proposals_tags.py
92e2e80e98478e5d21ce4861b2d0fd6ce88ae294
[]
no_license
lothwen/valioso
https://github.com/lothwen/valioso
37fe4fa4cdf4d96777063fe994098fbdbeb4a913
00381f2607d65ec2454bdcea22d9bcfeb3d74d9c
refs/heads/master
2020-02-27T05:15:08.880400
2012-06-25T12:06:03
2012-06-25T12:06:03
3,026,093
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import template from django.core.urlresolvers import reverse from django.db.models import Q from django.db.models.loading import get_model from django.template import TemplateSyntaxError register = template.Library() class IfRecommendedNode(template.Node): def __init__(self, nodelist_true, nodelist_false, *args): self.nodelist_true = nodelist_true self.nodelist_false = nodelist_false self.from_user, self.to_proposal = args def render(self, context): from_user = template.resolve_variable(self.from_user, context) to_proposal = template.resolve_variable(self.to_proposal, context) if from_user in to_proposal.recommendations.all(): return self.nodelist_true.render(context) return self.nodelist_false.render(context) @register.tag def if_recommended(parser, token): """ Determine if a certain proposal is recommended by a certain user Example:: {% if_recommended user proposal %} Recommended {% else %} Not recommended {% endif_recommended %} """ bits = list(token.split_contents()) if len(bits) != 3: raise TemplateSyntaxError, "%r takes 2 arguments:\n%s" % \ (bits[0], if_recommended.__doc__) end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = template.NodeList() return IfRecommendedNode(nodelist_true, nodelist_false, *bits[1:]) @register.filter def add_recommendation_url(proposal): """ Generate a url for adding a recommendation on a given proposal. Usage:: href="{{ proposal|add_recommendation_url }}" """ return reverse('proposal_recommend', args=[proposal.id]) @register.filter def remove_recommendation_url(proposal): """ Generate a url for removing a recommendation on a given proposal. Usage:: href="{{ proposal|remove_recommendation_url }}" """ return reverse('proposal_unrecommend', args=[proposal.id])
UTF-8
Python
false
false
2,012
1,821,066,168,592
54f719a5ce256a01d0d96505ec8e6478d82f8909
fa48afbc351739ecd05b59a086b7769b9e591e54
/find_basedirs.py
ad08ac2b7e3512dc9d5315ef7afd97bcf530cd63
[]
no_license
hazybluedot/pygrade
https://github.com/hazybluedot/pygrade
39f7c5f3ca4fc27267d5e803ab37befb815bb847
ebdf67a28c65c88a1afa005930ba836444a62cb0
refs/heads/master
2020-04-24T15:51:35.938702
2014-03-07T19:11:45
2014-03-07T19:11:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2 import scholar import argparse import subprocess import sys import os parser = argparse.ArgumentParser("Try to deduce base directory for student by searching for source files") parser.add_argument("-v","--verbose", action='store_true', help="Be verbose") parser.add_argument("-f", type=argparse.FileType('r'), help="Path to homework data file") parser.add_argument("--base-dir", help="Base directory to search in") args = parser.parse_args() if __name__=='__main__': (homework,scholar) = scholar.open_homework(args.f) if not os.path.isdir(args.base_dir): sys.stderr.write("{}: not a valid directory\n".format(args.base_dir)) sys.exit(1) dirs = [] for problem in homework['problems']: (pbase,pfile) = os.path.split(problem['src']) find_cmd = ['find', args.base_dir, '-name', pfile ] results = subprocess.check_output(find_cmd) dirs.extend([ os.path.split(path)[0] for path in results.split("\n") ]) dirs = list(set(dirs)) for pid in scholar.pids(): path = os.path.commonprefix([ entry for entry in dirs if entry.find("{}/".format(pid)) >= 0 ]) if path: print "{} \"{}\"".format(pid, path) else: sys.stderr.write("No directory found for {}\n".format(pid)) #for path in results.split("\n"): # print path
UTF-8
Python
false
false
2,014
17,317,308,160,614
3451607d4859833d729612c843d01bdfcf77ed65
8cab9bdb897336872378a433d7595b9cde17f07d
/devsite/minivr/admin.py
f88d69f4e18e62a064dc95758cd9a05928901421
[]
no_license
sjlehtin/minivr
https://github.com/sjlehtin/minivr
da00c874e0ddfd6f0ffa6bbbc4a8dced7ead1433
65b5ad2c6cef1f8fed7aac25ccee00a16edcf671
refs/heads/master
2021-01-23T08:35:00.709424
2010-11-10T18:08:52
2010-11-10T18:25:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import minivr.models as minivr from django.contrib import admin admin.site.register(minivr.Ticket) admin.site.register(minivr.Service) admin.site.register(minivr.Train) admin.site.register(minivr.Station) admin.site.register(minivr.Stop) admin.site.register(minivr.Connection) admin.site.register(minivr.CustomerType)
UTF-8
Python
false
false
2,010
8,418,135,924,095
31349c8ac8c8225175c5ce86bb124b1968eb15bd
78708a3e3f4ebdd083b577e03f8acbb858a25446
/tiny_uwsgi/tiny_uwsgi.py
5dd1e5aa4cb917c0f934e8cdcda8eb279326c305
[ "LGPL-3.0-only" ]
non_permissive
kasworld/tiny_uwsgi
https://github.com/kasworld/tiny_uwsgi
145cbfe471e0daed8968e25aa74ce5a9537c5c72
a8ef3dcac33fa305fa78a7306d54b7c8cfd8d83f
refs/heads/master
2020-05-27T01:29:18.285156
2014-03-05T10:07:19
2014-03-05T10:07:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """very thin python/uwsgi Framework made by kasw copyright 2013,2014 Version""" Version = '3.2.0' import traceback import sys import signal import pprint try: import cProfile as profile except: import profile class FailSafe(): profile = False def requestMainEntry(self, cookie, request, response): response.sendHeader() return 'OK' ServiceDict = { 'favicon.ico': { 'obj': FailSafe(), 'class': FailSafe, }, 'SYSTEM': { } } # uwsgi specific import uwsgi import uwsgidecorators from tiny_crr import Cookie, Request, Response @uwsgidecorators.postfork def ServiceInit(): print sys.version print __doc__, Version print "server forked ", uwsgi.worker_id() # additional init for k, v in ServiceDict.iteritems(): if k in ['favicon.ico', 'SYSTEM']: continue try: v['obj'] = v['class']() except: print traceback.format_exc() print 'service init fail', k # pprint.pprint(ServiceDict) def uwsgiEntry(environ, start_response): """ Main http request process """ cookie = Cookie(environ) request = Request(environ) response = Response(environ, start_response, cookie) try: servicename = request.path[0] service = ServiceDict[servicename] except: print traceback.format_exc() rtn = response.responseError('Bad Request', code=400) return rtn try: if getattr(service['obj'], 'profile', False) is True: service['obj'].profileobj.enable() rtn = service['obj'].requestMainEntry( cookie, request, response) except: print traceback.format_exc() rtn = response.responseError('Bad Request', code=400) finally: if getattr(service['obj'], 'profile', False) is True: service['obj'].profileobj.disable() return rtn def getRequestEntry(config): for k, v in config.iteritems(): if k in ServiceDict: ServiceDict[k].update(config.get(k, {})) else: print '[Warning] not inited service in config', k return uwsgiEntry # =========== class ServiceBase(object): def getServiceDict(self): return ServiceDict def getServiceConfig(self): return ServiceDict[self.serviceName] @classmethod def registerService(serviceClass): if serviceClass.serviceName in ServiceDict: print '[Warning] already registered service name', serviceClass.serviceName else: ServiceDict[serviceClass.serviceName] = {'class': serviceClass} class ProfileMixin(object): def __init__(self): self.profile = self.getServiceConfig().get('profile', False) if self.profile is True: self.profileobj = profile.Profile() def printProfileResult(self): if self.profile is True: self.profileobj.print_stats() else: print 'No profile' class DispatcherMixin_CRR(object): def requestMainEntry(self, cookie, request, response): try: request.parseJsonPost() except: print traceback.format_exc() return response.responseError('Bad Request', code=400) try: fnname = request.path[1] result = self.dispatchFnDict[ fnname](self, cookie, request, response) except: print traceback.format_exc() return response.responseError('Bad Request', code=400) response.sendHeader() return result @classmethod def exposeToURL(serviceClass, oldfn): serviceClass.dispatchFnDict[oldfn.__name__] = oldfn setattr(serviceClass, oldfn.__name__, oldfn) return oldfn class DispatcherMixin_AD(object): def requestMainEntry(self, cookie, request, response): try: request.parseJsonPost() except: print traceback.format_exc() return response.responseError('Bad Request', code=400) try: fnname = request.path[1] result = self.dispatchFnDict[ fnname](self, request.args, request.json) except: print traceback.format_exc() return response.responseError('Bad Request', code=400) response.sendHeader() return result @classmethod def exposeToURL(serviceClass, oldfn): serviceClass.dispatchFnDict[oldfn.__name__] = oldfn setattr(serviceClass, oldfn.__name__, oldfn) return oldfn ''' class Service0(ServiceBase, ProfileMixin, DispatcherMixin): """ basic service class """ serviceName = 'Service0' dispatchFnDict = {} Service0.registerService() @Service0.exposeToURL def info(self, cookie, request, response): return 'service0' + str(Service0.exposeToURL) class Service1(ServiceBase, ProfileMixin, DispatcherMixin): """ basic service class """ serviceName = 'Service1' dispatchFnDict = {} Service1.registerService() @Service1.exposeToURL def info2(self, cookie, request, response): return 'service1' + self.serviceName config = dict( Service0=dict( profile=True ), Service1=dict( profile=True ), ) application = getRequestEntry(config) '''
UTF-8
Python
false
false
2,014
5,420,248,767,836
e351eb7f1adecdca9e66f463cdfc133de7c36cb2
532436d7a66ed4df3fb2fa4e2ed1f26fec371998
/patches/november_2012/disable_cancelled_profiles.py
68e88675f6483b17aebd7b75ca812f22f5aaa0f4
[ "GPL-3.0-only", "CC-BY-SA-3.0", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
nabinhait/erpnext
https://github.com/nabinhait/erpnext
627caa622fb298dcd3dcb9ddca4bad8cdc93d47c
21ce1282ca7d19e34262644b8b904c2d30bdac8e
refs/heads/master
2023-08-11T13:56:47.889283
2013-12-02T10:42:04
2013-12-02T10:42:04
1,864,450
4
1
NOASSERTION
true
2020-05-14T10:14:13
2011-06-08T09:12:28
2015-09-01T06:09:21
2020-05-11T10:43:17
872,479
2
0
0
Python
false
false
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import webnotes def execute(): """ in old system, deleted profiles were set as docstatus=2 in new system, its either disabled or deleted. """ webnotes.conn.sql("""update `tabProfile` set docstatus=0, enabled=0 where docstatus=2""")
UTF-8
Python
false
false
2,013
14,310,831,035,847
d71c86e89d619c33304f8c987ee0ae862bac4a01
c6e83e3ac6a2628c4a813f527608080b36601bb1
/lang/python/algo/pyqt/pyQt/book/135_fiveButtons_nonAnonymousSlot.py
be4ea9621dc26b24bda7bf588e14215ab54db0d2
[]
no_license
emayssat/sandbox
https://github.com/emayssat/sandbox
53b25ee5a44cec80ad1e231c106994b1b6f99f9e
1c910c0733bb44e76e693285c7c474350aa0f410
refs/heads/master
2019-06-28T19:08:57.494846
2014-03-23T09:27:21
2014-03-23T09:27:21
5,719,986
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python #---------------------------------------------------------------------- # Module includes #---------------------------------------------------------------------- import sys from PyQt4.QtCore import * from PyQt4.QtGui import * #Does partial exist in this version? #If version is to old, create the function if sys.version_info[:2] < (2, 5): def partial (func, arg): """ partial is a function that returns a reference on another function Usage: my_wrapped_function=partial(unwrapper_function, parameters_set_in_stone) """ def callme(): return func(arg) return callme else: from functools import partial #---------------------------------------------------------------------- # Class definition (POO) #---------------------------------------------------------------------- #Form class instance class Form(QDialog): def __init__(self, parent=None): super(Form,self).__init__(parent) self.setWindowTitle("Custom Signals and Slots") button1=QPushButton("One") button2=QPushButton("Two") button3=QPushButton("Three") button4=QPushButton("Four") button5=QPushButton("Five") button6=QPushButton("Six") button7=QPushButton("Seven") #Note: label is an object of the intance, because is called in other methods of the class self.label=QLabel("Hello") layout = QHBoxLayout() layout.addWidget(button1) layout.addWidget(button2) layout.addWidget(button3) layout.addWidget(button4) layout.addWidget(button5) layout.addWidget(button6) layout.addWidget(button7) layout.addWidget(self.label) self.setLayout(layout) #TECHNIQUE 1 #Note that one/two, ... are not widget SLOTs but simple method self.connect(button1, SIGNAL("clicked()"), self.one) self.connect(button2, SIGNAL("clicked()"), self.three) #Note: Here I overwrite the above connection self.connect(button2, SIGNAL("clicked()"), self.two) #TECHNIQUE 2 (BETTER WAY) #Given that all the methods are almost the same, instead of #self.connect(button3, SIGNAL("clicked()"), self.three) #self.connect(button4, SIGNAL("clicked()"), self.four) #self.connect(button5, SIGNAL("clicked()"), self.five) # we try self.connect(button3, SIGNAL("clicked()"), partial(self.anyButton, "Three")) self.connect(button4, SIGNAL("clicked()"), partial(self.anyButton, "Four")) #FINALLY, IF IT DOESN'T WORK #In version of PyQt 4.0 - 4.2, the above may not work due to garbage collection #To avoid garbage collection, attach the partial to a 'permanent' variable self.button5callback=partial(self.anyButton, "Five") self.connect(button5, SIGNAL("clicked()"), self.button5callback) #In other words, self.button5callback(self) is equivalent to self.anyButton(self, "Five") #We are forced to use the above, because connect only takes a #TECHNIQUE 3 #TECHNIQUE 4 (Not as good as Technique 2 #We are using a SLOT! self.connect(button6, SIGNAL("clicked()"), self.clickedPseudoSLOT) #self.connect(button7, SIGNAL("clicked()"), self.clickedPseudoSLOT) #This doesn't work because pseudoSlot only! Not a real SLOT #Oh really? It seems that when using this notation, you cannot use self #but that is a real SLOT... (to investigate...) self.connect(button7, SIGNAL("clicked()"), self, SLOT("clickedPseudoSLOT")) #TECHNIQUE 5 (QSignalWrapper) def one(self): """ Print in One i label """ self.label.setText("(Indiv Method) You clicked button 'One'") def two(self): self.label.setText("(Indiv Method) You clicked button 'Two'") def three(self): self.label.setText("(Indiv Method) You clicked button 'Three'") def four(self): self.label.setText("(Indiv Method) You clicked button 'Four'") def five(self): self.label.setText("(Indiv Method) You clicked button 'Five'") def anyButton(self,who): self.label.setText("(Shared Method) You clicked button '%s'" % who) def clickedPseudoSLOT(self): #We can call the QObject sender method (not good POO!) sender=self.sender() #Check that sender is an existing QPushBtton instance if sender is None or not isinstance(sender, QPushButton): return if hasattr(sender, "text"): #Always true since it is a QPushButton ;-) self.label.setText("(PseudoSLOT) You clicked button '%s'" % sender.text()) #---------------------------------------------------------------------- # Main (Sequential) #---------------------------------------------------------------------- app = QApplication(sys.argv) form = Form() form.show() app.exec_()
UTF-8
Python
false
false
2,014
5,823,975,657,217
cbb4b2334b569b6b0d11d0dcbdb32877dbf45734
c3ba6d65fe0ddbcccf957e5c103acdefe06a954d
/RSS/DBUtils.py
350b576b8a93c77702b9245f3834eea09751e19e
[ "MIT" ]
permissive
ZereoX/ThePyScraper
https://github.com/ZereoX/ThePyScraper
9bafe5f2b3df564566b66eb4a5319b5022aaacc6
a381bb62902bff0d7b755c94c2f4620a1bb39e4f
refs/heads/master
2021-01-19T04:52:18.649555
2014-05-15T06:54:28
2014-05-15T06:54:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sqlite3 import queue import feedparser import time from time import strftime def openSQLConnection(DATABASE, THREAD): conn = sqlite3.connect(DATABASE, check_same_thread=THREAD) conn.row_factory = sqlite3.Row return conn def commitSQLConnection(DBConnection): DBConnection.commit() def closeSQLConnection(DBConnection): DBConnection.close() def SQLExecute(DBCursor, SQLStatement): DBCursor.execute(SQLStatement) def fetchAndProcessFeed(feed_id, feed_url, feed_date, DBConnection): print("Thread ID#: " + str(feed_id) + " opened.") feedparser._HTMLSanitizer.acceptable_elements.update(['iframe','embed']) feed = feedparser.parse(feed_url, modified=feed_date) if feed.status != 304: if hasattr(feed, "modified"): DBConnection.cursor().execute("UPDATE RSSFeeds SET date=? WHERE url=?;", (strftime("%Y-%m-%d %H:%M:%S %Z",feed.modified_parsed), feed_url)) else: DBConnection.cursor().execute("UPDATE RSSFeeds SET date=? WHERE url=?;", (strftime("%Y-%m-%d %H:%M:%S %Z",time.gmtime()), feed_url)) storeEntries(feed_id, feed.entries, DBConnection) else: print("SKIPPING: " + feed_url) def storeEntries(feed_id, entries, DBConnection): for entry in entries: post = len(DBConnection.cursor().execute('SELECT entry_id from RSSEntries WHERE url=?', (entry.link,)).fetchall()) postContent = "" if hasattr(entry, "content"): postContent = entry.content[0].value else: postContent = entry.summary if post == 0: DBConnection.cursor().execute('INSERT INTO RSSEntries (feed_id, url, title, content, date) VALUES (?,?,?,?,?)', (feed_id, entry.link, entry.title, postContent, strftime("%Y-%m-%d %H:%M:%S %Z",entry.updated_parsed)))
UTF-8
Python
false
false
2,014
4,827,543,243,563
b4d3c822c464c6f5f514ba976e138f7455a5ea76
0eb1df5e92b70aba19628ca8dfbd6f406f91fa3d
/gkel.py
b6ec4530a0fab79c838520aed18a63fa0b76fd5d
[]
no_license
fanixk/pyGkel
https://github.com/fanixk/pyGkel
d85afea77dd141397f160f3c84bada420c834303
f16c6b82eac17d0ecd75b4ba1881ee23cfeaf01a
refs/heads/master
2021-01-01T17:10:21.004588
2013-03-27T08:32:08
2013-03-27T08:32:08
2,625,031
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys,signal import urllib import time from getpass import getpass import re def get_data(): resp = urllib.urlopen('https://gkel.teipir.gr/gkelv2/prog_process/progress-e.2011.html') resp = resp.read() last_modified = re.search(r'(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+)',resp) last_modified = last_modified.group() return last_modified def check_for_new(): last = new = get_data() while(True): new = get_data() print new if new != last: break time.sleep(int(sys.argv[1])) print 'Nea kataxorisi! ' + new def help(): print 'Usage: %s <time in seconds>' % (sys.argv[0]) print '\nGmail SMTP Server: smtp.gmail.com' print 'Hotmail SMTP Server: smtp.live.com' def send_sms(): from otenet import Otenet username = raw_input('Username: ') password = getpass() otenet = Otenet(username,password) otenet.login() otenet.check_limit() while(True): number = raw_input('Kinhto: ') if number.startswith('69') and len(number) == 10: #sanity check break print 'Mi egkyros arithmos tilefonou.' check_for_new() otenet.login() #relog in case of logout otenet.send_sms(number,'Nea kataxorisi bathmologias sto Gkel') def send_mail(): import smtplib from email.mime.text import MIMEText try: server = raw_input('SMTP Server: ') server = smtplib.SMTP(server) username = raw_input('Username: ') password = getpass() server.starttls() server.login(username,password) except: print 'Login Error' sys.exit(1) print 'Logged in...' mail = raw_input('Email address: ') check_for_new() mail_text = MIMEText('Nea Kataxorisi bathmologias sto Gkel') mail_text['Subject'] = 'Gkel' try: server.sendmail('[email protected]', mail, mail_text.as_string()) except smtplib.SMTPServerDisconnected: server.login(username,password) server.sendmail('[email protected]', mail, mail_text.as_string()) server.quit() if __name__ == '__main__': def handler(*args): print '\n\nBye Bye!' sys.exit(0) signal.signal(signal.SIGINT,handler) if len(sys.argv) == 2 and sys.argv[1].isdigit(): notification = raw_input('Patiste 1 gia sms / 2 gia email: ') if notification == '1': send_sms() elif notification == '2': send_mail() else: print 'Egkyres epiloges: 1 gia sms / 2 gia email.' elif len(sys.argv) == 2 and (sys.argv[1] in ["-h","--help"]): help() else: help()
UTF-8
Python
false
false
2,013
14,285,061,230,435
b3e57fc1a3042d187b75b61c2956cbfdbd54d7f1
d47a45b2bc9c7efc8f9e8642d4cee903d6e8e3d4
/models/__init__.py
0f95cbecaad8b858f3b4623bf5f380d137bb99af
[]
no_license
cider-load-test/comicfeed
https://github.com/cider-load-test/comicfeed
cd0e03ab0e8278e822c95a2b9e7359851c8c01d3
0cb3e2ff7bc7fe4b8ff53251e64e9ea4306d17a9
refs/heads/master
2021-12-02T07:50:27.667012
2012-02-24T02:32:02
2012-02-24T02:32:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from google.appengine.ext import db import datetime class Feed(db.Model): name = db.StringProperty(multiline=False) url = db.StringProperty() active = db.BooleanProperty() last_updated = db.DateTimeProperty(auto_now_add=True) @staticmethod def get_active_feeds(): feeds = db.GqlQuery("select * from Feed where active = :1", True) return feeds @staticmethod def init(): feed_count = db.GqlQuery("select * from Feed").count() if feed_count == 0: feed = Feed() feed.name = "Explosm" feed.url = "http://feeds.feedburner.com/Explosm" feed.active = True feed.last_updated = datetime.datetime.fromtimestamp(0) feed.put() class FeedItem(db.Model): url = db.StringProperty() title = db.StringProperty() content = db.TextProperty() date = db.DateTimeProperty(auto_now_add=True) enclosure = db.BlobProperty() feed = db.ReferenceProperty(Feed) content_type = db.StringProperty() @staticmethod def is_fetched(url): items = db.GqlQuery("select * from FeedItem where url = :1", url) return items.count() > 0 @staticmethod def get_latest(): items = db.GqlQuery("select * from FeedItem order by date desc limit 10") return items
UTF-8
Python
false
false
2,012
8,426,725,856,857
7bacb69a3c9c51f4169c65da2ec69a8bdb30aea4
6d97ca8fadb764d3a7722e1b3a90357ede474ba6
/python/ggzboard/server_hnefatafl.py
015f7a587a0bf46167ba8ceec7495c7cc61b8c61
[ "GPL-2.0-only" ]
non_permissive
zaun/ggz-original
https://github.com/zaun/ggz-original
66174d3bf6fc88e8497c0362f174396094830464
7eb970cba38650f8b9f44b17c52aac6bc205a50f
refs/heads/master
2021-03-16T09:16:57.606929
2011-03-27T12:32:37
2011-03-27T12:32:37
22,027,529
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # Server for the Hnefatafl game # Copyright (C) 2004 Josef Spillner <[email protected]> # Published under GNU GPL conditions from Numeric import * import sys import time import random import os, pwd import re import gettext gettext.install("ggzpython", None, 1) import ggzdmod try: import ggzsettings DATAPATH = ggzsettings.DATAPATH + "/ggzboard/" MODULEPATH = ggzsettings.MODULEPATH + "/ggzboard/" I18NPATH = ggzsettings.I18NPATH sys.path = [ggzsettings.MODULEPATH + "/ggzboard/"] + sys.path sys.path = [ggzsettings.MODULEPATH + "/common/"] + sys.path except: DATAPATH = "./" MODULEPATH = "./" I18NPATH = "./" sys.path = ["../lib/"] + sys.path from module_hnefatafl import * from ggzboard_net import * class Server(NetworkBase): def __init__(self): NetworkBase.__init__(self) self.MSG_SEAT = 0 self.MSG_PLAYERS = 1 self.MSG_START = 5 self.MSG_MOVE = 2 self.MSG_GAMEOVER = 3 self.REQ_MOVE = 4 # self.MSG_SYNC = 6 # self.REQ_SYNC = 7 # self.REQ_AGAIN = 8 # self.SRV_ERROR = -1 # self.SRV_OK = 0 # self.SRV_JOIN = 1 # self.SRV_LEFT = 2 # self.SRV_QUIT = 3 def table_full(self): full = 1 for i in range(ggzdmod.getNumSeats()): seat = ggzdmod.getSeat(i) (number, type, name, fd) = seat if type != ggzdmod.SEAT_PLAYER and type != ggzdmod.SEAT_BOT: full = 0 return full def seatFd(self, i): seat = ggzdmod.getSeat(i) (number, type, name, fd) = seat return fd def send_players(self): for i in range(ggzdmod.getNumSeats()): fd = self.seatFd(i) if fd != -1: net.init(fd) net.sendbyte(self.MSG_SEAT) net.sendbyte(i) net.sendbyte(self.MSG_PLAYERS) for j in range(ggzdmod.getNumSeats()): seat = ggzdmod.getSeat(j) (number, type, name, fd) = seat print "TYPE", type net.sendbyte(type) if type != ggzdmod.SEAT_OPEN: print "NAME", name net.sendstring(name) def send_start(self): for i in range(ggzdmod.getNumSeats()): fd = self.seatFd(i) if fd != -1: net.init(fd) net.sendbyte(self.MSG_START) def hook_state (state): print "* state:", str(state) def hook_join (num, type, name, fd): print "* join:", num, type, name, fd net.send_players() if net.table_full(): net.send_start() def hook_leave (num, type, name, fd): print "* leave:", num, type, name, fd def hook_data (num, type, name, fd): print "* data:", num, type, name, fd net.init(fd) op = net.getbyte() print "READ(4bytes)", op if op == net.REQ_MOVE: print "- move" fromposval = net.getbyte() toposval = net.getbyte() print " + ", fromposval, toposval # TODO: move validity check # TODO: send to all players frompos = (fromposval % 9, fromposval / 9) topos = (toposval % 9, toposval / 9) if ggzboardgame.validatemove("w", frompos, topos): ggzboardgame.domove(frompos, topos) net.sendbyte(net.MSG_MOVE) net.sendbyte(fromposval) net.sendbyte(toposval) (ret, frompos, topos) = ggzboardgame.aimove() print "AI:", ret, frompos, topos if ret: (x, y) = frompos (x2, y2) = topos fromposval = y * 9 + x toposval = y2 * 9 + x2 ggzboardgame.domove(frompos, topos) net.sendbyte(net.MSG_MOVE) net.sendbyte(fromposval) net.sendbyte(toposval) if ggzboardgame.over(): winner = 0 # FIXME! net.sendbyte(net.MSG_GAMEOVER) net.sendbyte(winner) ggzdmod.reportStatistics(winner) if net.error(): print "** network error! **" sys.exit(-1) def hook_error (arg): print "* error:", arg sys.exit(-1) def initggz(): ggzdmod.setHandler(ggzdmod.EVENT_STATE, hook_state) ggzdmod.setHandler(ggzdmod.EVENT_JOIN, hook_join) ggzdmod.setHandler(ggzdmod.EVENT_LEAVE, hook_leave) ggzdmod.setHandler(ggzdmod.EVENT_DATA, hook_data) ggzdmod.setHandler(ggzdmod.EVENT_ERROR, hook_error) def main(): global net global ggzboardgame print "### launched" """ Setup """ print "### go init ggz" initggz() net = Server() print "### now go loop" ggzdmod.connect() ggzdmod.mainLoop() """ Main loop """ while 1: pass if __name__ == "__main__": main()
UTF-8
Python
false
false
2,011
10,668,698,800,432
d6394a209a44b9720dfff1b1884812bed939ebab
a7eb878d24a9efc1aa5387c05269ff67ccff2b7c
/Oving9/oppg1.py
f28c309849ff7f3dbdd16e5f387426d3b964b527
[]
no_license
oyvindrobertsen/TDT4110-Code
https://github.com/oyvindrobertsen/TDT4110-Code
23abbe1cc4492e41e09b0f37ecf5c97ddfc7657e
f2d18c32e03902362f2d334a8722d988a881498e
refs/heads/master
2021-01-02T09:08:33.674074
2012-12-05T10:46:48
2012-12-05T10:46:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
videoer = [ 'http://www.youtube.com/watch?v=oKI-tD0L18A', 'http://www.youtube.com/watch?v=82LCKBdjywQ', 'http://www.youtube.com/watch?v=GpNSip5gyKo', 'http://www.youtube.com/watch?v=rHG-JO8gIGk', 'http://www.youtube.com/watch?v=ZFngtBIxRPk', 'http://www.youtube.com/watch?v=OZBWfyYtYQY', ] def yt_short(videoliste): videoer_short = [] for i in videoliste: videoer_short.append('youtu.be/' + i[(i.find('=') + 1):]) return videoer_short def main(): print(yt_short(videoer)) main()
UTF-8
Python
false
false
2,012
11,252,814,343,195
58e309059552a8c1830774019deb0f31f2fc1856
ff3e6e73060f025582b45a9667df5ce896459c20
/sito/models.py
65d7cad95d51e6aa525bfd6c3b84faed636235ed
[]
no_license
pierangelo1982/azzurrachild
https://github.com/pierangelo1982/azzurrachild
a552312ae1bb64f4054d421c0ded3ff6f288f416
a71f10316f1b2f160e3a6e942331081e0339e619
refs/heads/master
2020-02-26T03:52:39.533956
2014-12-12T05:35:26
2014-12-12T05:35:26
27,383,888
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from image_cropping import ImageRatioField, ImageCropField from tinymce.models import HTMLField # Create your models here. class Galleria(models.Model): titolo = models.CharField(max_length=100, verbose_name="Titolo del Progetto:") image = models.ImageField(blank=True, null=True, upload_to='uploaded_images') didascalia = models.TextField(null=True, blank=True) cropping = ImageRatioField('image', '500x480') slider = ImageRatioField('image', '870x480') thumb = ImageRatioField('image', '132x94') croppinguno = ImageRatioField('image', '1140x487') croppingdue = ImageRatioField('image', '198x132') croppingtre = ImageRatioField('image', '1199x674') croppingquattro = ImageRatioField('image', '500x469', verbose_name="Design Miniatura") croppingcinque = ImageRatioField('image', '1200x800', verbose_name="Design HD") croppingsei = ImageRatioField('image', '1200x1125', verbose_name="News") pub_date = models.DateTimeField('date published') def __unicode__(self): return self.titolo class Slider(models.Model): titolo = models.CharField(max_length=100, verbose_name="Titolo del Progetto:") titolo_uk = models.CharField(max_length=100, verbose_name="Titolo Inglese:") link = models.CharField(max_length=100, verbose_name="Link") image = models.ImageField(blank=True, null=True, upload_to='uploaded_images') body = models.TextField(null=True, blank=True) cropping = ImageRatioField('image', '1170x500') slider = ImageRatioField('image', '870x480') thumb = ImageRatioField('image', '132x94') pub_date = models.DateTimeField('date published') def __unicode__(self): return self.titolo class Post(models.Model): titolo = models.CharField("Titolo:", max_length=100, null=True, blank=True) titolo_uk = models.CharField("Titolo Inglese:", max_length=100, null=True, blank=True) intro = models.TextField(null=True, blank=True, verbose_name="Intro") intro_uk = models.TextField(null=True, blank=True, verbose_name="Intro Inglese") body = HTMLField(null=True, blank=True, verbose_name="Descrizione") body_uk = HTMLField(null=True, blank=True, verbose_name="Descrizione Inglese") image = models.ImageField(blank=True, null=True, upload_to='uploaded_images') miniatura = ImageRatioField('image', '500x281') cropping = ImageRatioField('image', '1200x675') galleria = models.ManyToManyField(Galleria, null=True, blank=True, verbose_name="Seleziona Immagini Galleria") pub_date = models.DateTimeField('date published') def __unicode__(self): return self.titolo class Meta: verbose_name_plural = "Post" class Page(models.Model): titolo = models.CharField("Titolo:", max_length=100, null=True, blank=True) titolo_uk = models.CharField("Titolo Inglese:", max_length=100, null=True, blank=True) intro = models.TextField(null=True, blank=True, verbose_name="Intro") intro_uk = models.TextField(null=True, blank=True, verbose_name="Intro Inglese") body = HTMLField(null=True, blank=True, verbose_name="Descrizione") body_uk = HTMLField(null=True, blank=True, verbose_name="Descrizione Inglese") image = models.ImageField(blank=True, null=True, upload_to='uploaded_images') miniatura = ImageRatioField('image', '300x200') cropping = ImageRatioField('image', '1200x675') galleria = models.ManyToManyField(Galleria, null=True, blank=True, verbose_name="Seleziona Immagini Galleria") pub_date = models.DateTimeField('date published') def __unicode__(self): return self.titolo class Meta: verbose_name_plural = "Progetti" class News(models.Model): titolo = models.CharField("Titolo:", max_length=100, null=True, blank=True) titolo_uk = models.CharField("Titolo Inglese:", max_length=100, null=True, blank=True) intro = models.TextField(null=True, blank=True, verbose_name="Intro") intro_uk = models.TextField(null=True, blank=True, verbose_name="Intro Inglese") body = HTMLField(null=True, blank=True, verbose_name="Descrizione") body_uk = HTMLField(null=True, blank=True, verbose_name="Descrizione Inglese") image = models.ImageField(blank=True, null=True, upload_to='uploaded_images') miniatura = ImageRatioField('image', '500x281') cropping = ImageRatioField('image', '1200x675') galleria = models.ManyToManyField(Galleria, null=True, blank=True, verbose_name="Seleziona Immagini Galleria") pub_date = models.DateTimeField('date published') def __unicode__(self): return self.titolo class Meta: verbose_name_plural = "News" class Link(models.Model): titolo = models.CharField("Titolo:", max_length=100, null=True, blank=True) titolo_uk = models.CharField("Titolo Inglese:", max_length=100, null=True, blank=True) email = models.CharField("Email:", max_length=100, null=True, blank=True) url = models.CharField("Link:", max_length=100, null=True, blank=True) body = models.TextField(null=True, blank=True, verbose_name="Descrizione") body_uk = models.TextField(null=True, blank=True, verbose_name="Descrizione Inglese") image = models.ImageField(blank=True, null=True, upload_to='uploaded_images') miniatura = ImageRatioField('image', '500x281') pub_date = models.DateTimeField('date published') def __unicode__(self): return self.titolo class Meta: verbose_name_plural = "Link"
UTF-8
Python
false
false
2,014
14,010,183,320,627
aa303fc03502e1435eaa7d310e24cad1971c3d3e
071697ffebeb4e392e37581bb86d62c44c52b26f
/commission_rate.py
795b598f596d1cbd0f396c67a6e3f1b28bcfae94
[]
no_license
Christopherpl/python_poison
https://github.com/Christopherpl/python_poison
574684305d6b3faf169a0237c015fd271e2734fa
b1cccc2b1a1f3e912a0790197c2beacfcf151670
refs/heads/master
2016-03-27T16:14:28.033688
2012-10-05T17:26:04
2012-10-05T17:26:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!"usr/local/bin/python3.2" #this program calculates a salesperson's pay at #Make Your Own Music #define the main function def main(): #get the salesperson's monthly sales #note that the function resides on the right of the operator sales = get_sales() #get the amount of advanced pay advanced_pay = get_advanced_pay() #determine the commission rate #it is dependant upon the sales, so the determine_commission_rate #takes the sales argument commission_rate = determine_commission_rate(sales) #get the final pay pay = sales * commission_rate - advanced_pay #display the final pay print("The pay is $", format(pay, ',.2f')) #is the pay negative? if pay < 0: print("This employee must reimburse the company $") #the get sales function asks the user to input the employees' monthly_sales total #and returns the value def get_sales(): #get the amount of monthly sales monthly_sales = float(input("Enter the employees' sales: $ ")) #return the amount entered return monthly_sales #the get_advanced_pay function asks the user to enter the employees' #advanced pay and reurns the value def get_advanced_pay(): print("Enter the amount of advanced pay OR") print("if no advanced pay was given, enter 0") advanced = float(input("Enter advanced pay: $ ")) #return the value of advanced pay return advanced #the commission_rate function calculates the commission rate #and returns its value def determine_commission_rate(sales): if sales < 10000: rate = 0.10 elif sales >= 10000 and sales <= 14999.99: rate = 0.12 elif sales >= 15000 and sales <= 17999.99: rate = 0.14 elif sales >=18000 and sales <= 21999.99: rate = 0.16 else: rate = 0.18 #return the values of commission rate return rate main()
UTF-8
Python
false
false
2,012
11,390,253,291,372
30dd5cb424630f4803c8c60d9405e6cd78f18975
83b02819adbe0afb030a990a3545aa604f5235e8
/mtg/gatherer/__init__.py
a04de262cc09547fda9c34300f543bd85b392354
[]
no_license
glibersat/python-mtg
https://github.com/glibersat/python-mtg
9e031090eee1c1eaebd063f3bbce237187e843a5
2441b8e62151d29da2f8c0ff5d58ab6c67b744a0
refs/heads/master
2021-01-01T18:54:17.628681
2011-05-27T10:26:37
2011-05-27T10:26:37
1,809,073
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__version__ = '0.0.1' __author__ = 'Cameron Higby-Naquin'
UTF-8
Python
false
false
2,011
17,008,070,494,786
0ac177ba2d9c9f959fed0c20a899a45574206b78
80e0306273b784596cccc6d80912b5126bab5684
/src/Kawaz/globals/templatetags/active.py
a98eaf4ecac72922ced9ef5a417f00e76c83734b
[]
no_license
lambdalisue/Kawaz
https://github.com/lambdalisue/Kawaz
e472a3ec39b73df2bd03bc116a85767f40359841
5a5494183609bfdb7c5a2dc6caa57d4e3236bca5
refs/heads/master
2021-03-12T23:47:07.579201
2011-07-08T10:11:31
2011-07-08T10:11:31
1,835,855
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # # Created: 2010/10/13 # Author: alisue # from django import template register = template.Library() @register.simple_tag def active(request, pattern): from re import search if search(pattern, request.path): return 'active' return ''
UTF-8
Python
false
false
2,011
5,875,515,293,385
238b2d510a8b42e01892f8a42353a94118360dd9
a0852fa887283b7c549531388ebb124c09b633c6
/Script/COMMON_SCRIPT/listname.py
fab4d7c1cdef23c24c3b3d0d9e71a0ccc2363781
[]
no_license
jccheng-ad/AppCore
https://github.com/jccheng-ad/AppCore
ac463b8678408c097be03b0b3108186fa32dcbf9
7d00cbeb4e10d5cb3c8259c9558d4cbe717265ec
refs/heads/master
2016-03-10T23:31:09.419785
2013-10-22T09:30:59
2013-10-22T09:30:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python import sys import os import os.path import glob import re if len(sys.argv) != 2: print "please enter <command> <case_number>" exit() num = sys.argv[1] f = open('%s-setup-post'%num,'w') # get target filename string = "%s-*.*rp" %num print 'search ',string files = glob.glob(string) for file in files: if not re.search('settings',file): print >> f,file,'\n', f.close()
UTF-8
Python
false
false
2,013
4,741,643,920,213
f6ca4f2ba858e4db962188cbeaac1424b35c3aac
1e5010000db97c191310e50a4382211ab0944e56
/src/iluminare/limbo/consultas_gerais.py
520f6a94dbf4afde5672d520cbbaffd13e59714e
[]
no_license
tacsio/iluminare
https://github.com/tacsio/iluminare
7f627c7d19870efd5fd02fa3c187c3f85f3412ab
de7219924ce3a966eb852f48c2bd5ccb47ab81b6
refs/heads/master
2016-11-11T09:57:32.349380
2012-01-29T17:29:14
2012-01-29T17:29:14
1,533,839
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-*- coding: utf-8 -*- import csv from datetime import * from iluminare.paciente.models import * from iluminare.tratamento.models import * from iluminare.atendimento.models import * from iluminare.voluntario.models import * from django.core.exceptions import MultipleObjectsReturned import re from django.utils.encoding import smart_str, smart_unicode dir_log = "/media/DATA/Iluminare/relatorios/" def gera_csv(lista_rotulos, lista, nome_arquivo_csv): spamWriter = csv.writer(open(dir_log+nome_arquivo_csv, 'wb'), delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamWriter.writerow(lista_rotulos) for item in lista: spamWriter.writerow(item) def retorna_dia_semana(data): dia_semana_int = data.weekday() dia_semana_str = "" if dia_semana_int == 0: dia_semana_str = "Segunda" elif dia_semana_int == 1: dia_semana_str = "Terça" elif dia_semana_int == 2: dia_semana_str = "Quarta" elif dia_semana_int == 3: dia_semana_str = "Quinta" elif dia_semana_int == 4: dia_semana_str = "Sexta" elif dia_semana_int == 5: dia_semana_str = "Sábado" elif dia_semana_int == 6: dia_semana_str = "Domingo" return dia_semana_str # funcao desenvolvida para carga de dados.. # no dia 15-12-2011 iniciamos os trabalhos sem os dados do dia 12. def carrega_ats_15122011(): spamReader = csv.reader(open(dir_log+'ats_15122011.csv', 'rb'), delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) it_s1 = InstanciaTratamento(tratamento = Tratamento.objects.get(descricao_basica='Sala 1'), data='2011-12-15') it_s1.save() it_s2 = InstanciaTratamento(tratamento = Tratamento.objects.get(descricao_basica='Sala 2'), data='2011-12-15') it_s2.save() it_s3 = InstanciaTratamento(tratamento = Tratamento.objects.get(descricao_basica='Sala 3'), data='2011-12-15') it_s3.save() it_s4 = InstanciaTratamento(tratamento = Tratamento.objects.get(descricao_basica='Sala 4'), data='2011-12-15') it_s4.save() it_s5 = InstanciaTratamento(tratamento = Tratamento.objects.get(descricao_basica='Sala 5'), data='2011-12-15') it_s5.save() for row in spamReader: print row[1] pac = Paciente.objects.filter(nome=row[1]) if len(pac) == 0: pac = Paciente(nome = row[1]) pac.save() print 'NOVO PACIENTE: ' + row[1] elif len(pac) == 1: pac = pac[0] else: print 'MAIS DE UM NOME.. ' + row[1] pac = Paciente.objects.get(id=row[0]) sala_str = row[2] it = None if sala_str == 'Sala 1': it = it_s1 elif sala_str == 'Sala 2': it = it_s2 elif sala_str == 'Sala 3': it = it_s3 elif sala_str == 'Sala 4': it = it_s4 elif sala_str == 'Sala 5': it = it_s5 at = Atendimento(paciente = pac, instancia_tratamento = it, hora_chegada = row[3], status = row[4], \ observacao_prioridade = row[5], observacao = row[6]) at.save() spamReader = csv.reader(open(dir_log+'ts_15122011.csv', 'rb'), delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in spamReader: print row[0] vol = Voluntario.objects.get(id=row[0]) f = Funcao.objects.get(descricao='Geral') if len(row[2]) > 0: trabalho = Trabalho(funcao = f, voluntario = vol, data = '2011-12-15', hora_inicio = row[1], hora_final = row[2]) else: trabalho = Trabalho(funcao = f, voluntario = vol, data = '2011-12-15', hora_inicio = row[1]) trabalho.save() # funcao desenvolvida para carga de dados.. # no dia 15-12-2011 iniciamos os trabalhos sem os dados do dia 12. def atendimentos_15122011(): ats = Atendimento.objects.filter(instancia_tratamento__data='2011-12-15') # 7 campos lista_rotulos = ["Id Paciente", #1 "Nome Paciente", #2 "Tratamento", #3 "Hora chegada",#4 "Status", #5 "Observacao Prioridade", #6 "Observacao"] #7 lista_retorno = [] for at in ats: lista = [] lista.append(at.paciente.id) #1 print at.paciente.id lista.append(smart_str(at.paciente.nome)) #2 lista.append(smart_str(at.instancia_tratamento.tratamento.descricao_basica)) #3 lista.append(at.hora_chegada) #4 lista.append(at.status) #5 lista.append(smart_str(at.observacao_prioridade)) #6 lista.append(smart_str(at.observacao)) #7 lista_retorno.append(lista) gera_csv(lista_rotulos, lista_retorno, "ats_15122011.csv") ts = Trabalho.objects.filter(data = '2011-12-15') lista_rotulos = ["Id Voluntario", #1 "Hora Inicio", #2 "Hora final"] #3 lista_retorno = [] for t in ts: lista = [] lista.append(t.voluntario.id) #1 print t.voluntario.id lista.append(t.hora_inicio) #2 lista.append(t.hora_final) #3 lista_retorno.append(lista) gera_csv(lista_rotulos, lista_retorno, "ts_15122011.csv") def relatorio_trabalhos(): ts = Trabalho.objects.filter() lista_rotulos = ["Id Trabalho", #1 "Nome voluntário", #2 "Data", #3 "Dia semana", #4 "Mes", #5 "Ano", #6 "Hora inicio", #7 "Hora final", #8 "Ativo", #9 "Tipo voluntário" #10 ] lista_retorno = [] for t in ts: lista = [] lista.append(t.id) #1 print t.id lista.append(smart_str(t.voluntario.paciente.nome)) #2 lista.append(t.data) #3 dia_semana_str = retorna_dia_semana(t.data) lista.append(smart_str(dia_semana_str)) #4 lista.append(t.data.month) #5 lista.append(t.data.year) #6 lista.append(t.hora_inicio) #7 lista.append(t.hora_final) #8 ativo = t.voluntario.ativo if ativo: lista.append("S") #9 else: lista.append("N") #9 lista.append(t.voluntario.tipo) #10 lista_retorno.append(lista) gera_csv(lista_rotulos, lista_retorno, "relatorio_trabalhos.csv") def relatorio_atendimentos_basico(): ats = Atendimento.objects.all() # 17 campos lista_rotulos = ["Id Atendimento", #1 "Nome Paciente", #2 "Sexo", #3 "Tratamento", #4 "Tratamento dia", #5 "Data", #6 "Hora chegada",#7 "Status atendimento", #8 "Voluntario", #9 "Prioridade", #10 "Tipo Prioridade", #11 "Prioridade no dia", #12 "Observacao", #13 "Observacao Prioridade", #14 "Mes", #15 "Ano", #16 "Dia semana"] #17 lista_retorno = [] for at in ats: lista = [] lista.append(at.id) #1 print at.id lista.append(smart_str(at.paciente.nome)) #2 if at.paciente.sexo: lista.append(at.paciente.sexo) #3 else: lista.append("") tps = TratamentoPaciente.objects.filter(paciente = at.paciente) if tps: lista.append(smart_str(tps[0].tratamento.descricao_basica)) #4 else: lista.append("") lista.append(smart_str(at.instancia_tratamento.tratamento.descricao_basica)) #5 lista.append(at.instancia_tratamento.data) #6 lista.append(at.hora_chegada) #7 lista.append(at.status) #8 vols = Voluntario.objects.filter(paciente = at.paciente, ativo = True) if vols: lista.append(vols[0].tipo) #9 else: lista.append("") dtps = DetalhePrioridade.objects.filter(paciente = at.paciente) if len(dtps) > 0: lista.append("P") #10 lista.append(dtps[0].tipo) # 11 else: lista.append("N") lista.append("") if at.prioridade: lista.append("P") #12 else: lista.append("N") lista.append(smart_str(at.observacao)) #13 lista.append(smart_str(at.observacao_prioridade)) #14 lista.append(at.instancia_tratamento.data.month) #15 lista.append(at.instancia_tratamento.data.year) #16 dia_semana_str = retorna_dia_semana(at.instancia_tratamento.data) lista.append(smart_str(dia_semana_str)) #17 lista_retorno.append(lista) gera_csv(lista_rotulos, lista_retorno, "relatorio_geral_atendimentos.csv") def retorna_tratamentos_trabalhadores(): ats = Atendimento.objects.raw(""" select at.id, p.nome, it.data, t.descricao_basica from atendimento_atendimento at join paciente_paciente p on p.id = at.paciente_id join voluntario_voluntario v on v.paciente_id = p.id join tratamento_instanciatratamento it on at.instancia_tratamento_id = it.id join tratamento_tratamento t on t.id = it.tratamento_id where v.ativo = True and (it.data = '2011-09-01' or it.data = '2011-09-08' or it.data = '2011-09-15' or it.data = '2011-09-22' or it.data = '2011-09-29' or it.data = '2011-10-06' or it.data = '2011-10-13' or it.data = '2011-10-20' or it.data = '2011-10-27') order by p.nome, it.data; """) lista_rotulos = ["Nome", "Data", "Tratamento"] # lista de listas lista_retorno = [] for at in ats: lista = [] lista.append(smart_str(at.paciente.nome)) lista.append(at.instancia_tratamento.data) lista.append(at.instancia_tratamento.tratamento.descricao_basica) lista_retorno.append(lista) gera_csv(lista_rotulos, lista_retorno, "consulta_tratamentos_trabalhadores.csv") def retorna_trabalhos_trabalhadores(): ts = Trabalho.objects.raw(""" select tr.id, p.nome, tr.data, tr.hora_inicio, tr.hora_final from voluntario_trabalho tr join voluntario_voluntario v on v.id = tr.voluntario_id join paciente_paciente p on p.id = v.paciente_id; """) spamWriter = csv.writer(open(dir_log+"consulta2.csv", 'wb'), delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamWriter.writerow(["Id", "Nome", "Data", "Dia semana" , "Hora Inicio", "Hora Final"]) for t in ts: lista = [] lista.append(t.id) lista.append(smart_str(t.voluntario.paciente.nome)) lista.append(t.data) dia_semana_int = t.data.weekday() dia_semana_str = "" if dia_semana_int == 0: dia_semana_str = "Segunda" elif dia_semana_int == 1: dia_semana_str = "Terça" elif dia_semana_int == 2: dia_semana_str = "Quarta" elif dia_semana_int == 3: dia_semana_str = "Quinta" elif dia_semana_int == 4: dia_semana_str = "Sexta" elif dia_semana_int == 5: dia_semana_str = "Sábado" elif dia_semana_int == 6: dia_semana_str = "Domingo" lista.append(smart_str(dia_semana_str)) lista.append(t.hora_inicio) lista.append(t.hora_final) spamWriter.writerow(lista)
UTF-8
Python
false
false
2,012
10,436,770,563,659
53bef1088baf740cbfe945cdf001dd8f3420df19
1134ac407b1634ba1a63545cc6b07c6efa399969
/src/base_syntax/parser__test.py
536ae94ee7bbcdd82741602ea3b61bd9a07487c0
[ "CC-BY-ND-3.0" ]
non_permissive
timka-s/hql-python
https://github.com/timka-s/hql-python
a2f16466700ce3d332e358600bc2bb5c8af0e7de
4adf9b7ef53db66a9373b68069ca3c0e60ee1e0e
refs/heads/master
2016-09-06T19:10:20.312022
2013-07-22T19:51:08
2013-07-22T19:51:08
11,250,321
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pytest from .__external__ import tree from .parser import Parser @pytest.fixture(scope='module') def parser(): return Parser() @pytest.fixture(scope='module') def completeness_string(): return ''' GET field_one = @row_a.attr field_two = @row_b.attr field_three = {TRUE} USING SUCH COMBINATION SUCH @row_a FROM %input_seq_a WHERE @row_a.field > 22 @row_b FROM %input_seq_b WHERE @row_a.parent_id == @row_b.id AND EACH @item FROM @row.seq ACCORD ( @item.text AS @text ACCORD ( FALSE || (321 != (123)) && {"not_empty_string"} && NOT FALSE && (@text == "input_seq.seq.text.value") ) ) ''' @pytest.fixture(scope='module', params=[ 'GET field_one = -2', 'GET field_one = @item USING @item FROM %seq', 'GET field_one = @item USING SUCH @item FROM %seq WHERE @item > 1', 'GET field_one = eq(a=2,b=3)', 'GET field_one = abs(value=2)', 'GET field_one = rand()' ]) def input_select_string(request): return request.param @pytest.fixture(scope='module') def input_bad_string(): return 'GET $@row = %param' def test_constructor(parser): assert isinstance(parser, Parser) def test_parse_ok_realization(parser, completeness_string): node = parser.parse(completeness_string, debug=True) assert isinstance(node, tree.Select) def test_parse_ok_select(parser, input_select_string): node = parser.parse(input_select_string, debug=True) assert isinstance(node, tree.Select) def test_parse_error_syntax(parser, input_bad_string): with pytest.raises(SyntaxError): parser.parse(input_bad_string, debug=True)
UTF-8
Python
false
false
2,013
18,580,028,529,197
b2c589141652101fd18c78ecc466f3306cc604c4
fd8e92a56b479f124f6c3538d64d4ce4e2333755
/challenge-140-easy/python/solution.py
4c75820c40f6d08270b434cea44f6bd122109cc8
[]
no_license
taylan/reddit-dailyprogrammer
https://github.com/taylan/reddit-dailyprogrammer
d651f517d1331c69bb27478bf82d887136901874
677b4c702b3b025b3f11ed8cddf0f678c8d702e0
refs/heads/master
2021-01-19T08:55:39.588110
2014-04-03T12:04:21
2014-04-03T12:04:21
11,274,692
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from string import capwords def main(): ops = [lambda x: capwords(x), lambda x: x.lower(), lambda x: x.upper()] for p in [l.split(' ') for l in open('input.txt').read().splitlines()]: print(('' if p[0] == '0' else '_').join(list(map(ops[int(p[0])], p[1:])))) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
18,803,366,836,982
c75080ef07ce589f0715ed0f2a3bcb38f260e9be
c198dbd09a25f7c21a058fe600a85c29fef4206d
/batma/core/engine.py
d90482927aa1795a4ac9b537c4b40b3377e2218b
[ "MIT" ]
permissive
droidguy04/batma
https://github.com/droidguy04/batma
f1a7dad12f221739e516a60c4fa2cc054334d97d
772a063c8ad7c4324debf1cf7f3c25da1dce4e7a
refs/heads/master
2020-12-25T23:46:43.012369
2012-07-23T00:27:25
2012-07-23T00:27:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding:utf-8 -*- # Copyright (c) 2011 Renato de Pontes Pereira, renato.ppontes at gmail dot com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. __all__ = ['Engine'] import pygame import batma from batma.core.camera import Camera from batma.util import singleton, WeakList @singleton class Engine(object): '''Batma Engine object''' def __init__(self): self.all_colliders = WeakList() self.__running = True self.__exit = False # Game Loop =============================================================== def __game_loop(self): '''Game loop''' # text_fps for FPS report on screen # text_fps = batma.Text('', # position=(10, 10), # anchor='bottomleft', # font_size=62, # color=batma.Color(0.3, 0.3, 0.3, 1) # ) # Initialize the game ================================================= batma.game._initialize() batma.game._load_content() # ===================================================================== batma.clock.tick(batma.display.max_fps) while not self.__exit: tick = batma.clock.tick(batma.display.max_fps) # Event Update ==================================================== for event in pygame.event.get(): if event.type == pygame.QUIT: # self.stop() elif event.type == pygame.VIDEORESIZE: # Update the display size with the new window resolution batma.display.size = event.size else: # User defined schedule functions batma.clock.update_schedule(event) # ================================================================= # Input Update ==================================================== batma.keyboard.update(tick) batma.mouse.update(tick) # ================================================================= # Game Update and Drawing ========================================= if self.__running: batma.game._update(tick) # Clear after the update, forcing all drawing call to be # called on game.draw() batma.display.clear() batma.game._draw() # ================================================================= # Camera location ================================================= batma.camera.locate() # ================================================================= if batma.display.show_colliders: for collider in self.all_colliders.iter(): collider.draw() # if batma.display.show_fps: # text_fps.text = '%.2f'%batma.clock.get_fps() # text_fps.draw() pygame.display.flip() batma.game._unload_content() # ========================================================================= # Configuration =========================================================== def apply_config(self, game, *args, **kwargs): '''Apply new configuration to engine''' # Set up the global variables batma.game = game batma.camera = Camera() # Pygame initialization pygame.init() pygame.font.init() # Display initialization batma.display.apply_config(*args, **kwargs) # ========================================================================= # Engine Control ========================================================== def start(self): '''Starts the engine''' self.__running = True self.__exit = False batma.display.init() self.__game_loop() def pause(self): '''Pauses the engine''' self.__running = False def resume(self): '''Resume the paused engine''' self.__running = True def stop(self): '''Stop the engine and end the game''' self.__exit = True def is_running(self): '''Verify if engine is paused''' return self.__running # =========================================================================
UTF-8
Python
false
false
2,012
8,306,466,757,766
417c64336abc0b28f0d9fdc7ade3cfcc90a0f28c
ae7c3121c4c19b6613c191a2672112f7a2305dd0
/impl/MenuItem.py
ffa1efc7d73d9e642b98e6b25a481f4d0eacebb3
[]
no_license
varnie/snake
https://github.com/varnie/snake
c597d9f4d90ddb9623c006c9dcc1ec5bd2aa6627
a68945316959bf7df44969428a7e9540c634e52f
refs/heads/master
2018-01-07T13:16:21.101577
2010-12-19T15:16:11
2010-12-19T15:16:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pyglet from pyglet.window import key class MenuItem(object): SELECTED_ITEM_FONT_SIZE, DESELECTED_ITEM_FONT_SIZE = 16, 13 def __init__(self, text, x, y, func, batch=None): super(MenuItem, self).__init__() self._label = pyglet.text.Label(text, font_name="Times New Roman", color=(100, 0, 0, 100), font_size=MenuItem.DESELECTED_ITEM_FONT_SIZE, x=x, y=y, anchor_x='center', anchor_y='center', batch=batch) self._func=func self._is_selected = False @property def is_selected(self): return self._is_selected @is_selected.setter def is_selected(self, value): if self._is_selected != value: self._is_selected = value self._label.font_size = MenuItem.SELECTED_ITEM_FONT_SIZE if value else MenuItem.DESELECTED_ITEM_FONT_SIZE def on_key_press(self, symbol, modifiers): if symbol == key.ENTER: self._func() def on_mouse_press(self, x, y): if self._label.x + self._label.content_width/2 > x > self._label.x - self._label.content_width/2 and \ self._label.y + self._label.content_height/2 > y > self._label.y - self._label.content_height/2: self._func() return True def on_draw(self): #print "menuitem draw" self._label.draw()
UTF-8
Python
false
false
2,010
13,451,837,614,773
b4a02fa0151299ee6fb6a2a6131a18fbdabadce1
f32b3812aa48d53fece6d0b87fb0399c09dde119
/webapp/larryslist/admin/apps/auth/forms.py
be012fac2381098f8ba48b81f8aaa79054ffd791
[]
no_license
larryslist/larryslist_pub
https://github.com/larryslist/larryslist_pub
e7f0a01c3c06711260ff7b4c04a8b327bfebe523
725c644c4fb616623526179b55cbb9341b49ff9a
refs/heads/master
2021-01-20T23:11:44.885476
2013-10-09T14:17:56
2013-10-09T14:17:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from jsonclient.backend import DBMessage import formencode from larryslist.admin.apps.auth.models import AdminLoginProc, UpdatePasswordProc, ResendRequestProc, PasswordRequestProc from larryslist.lib.baseviews import GenericSuccessMessage from larryslist.lib.formlib.formfields import BaseForm, EmailField, PasswordField, REQUIRED __author__ = 'Martin' class LoginForm(BaseForm): label = "Login" action_label = "Login" fields = [ EmailField("email", "Email", REQUIRED) , PasswordField("pwd", "Password", REQUIRED) ] @classmethod def on_success(cls, request, values): try: user = AdminLoginProc(request, values) except DBMessage, e: msg = e.message if e.message == 'LOGIN_FAILED': msg = "Unknown email or password" return {'success':False, 'errors': {'email': msg}} else: return {'success':True, 'redirect': request.fwd_url("admin_index")} class PasswordforgotForm(BaseForm): id = 'pwdforgot' label = "Forgot password" action_label = "Submit" fields = [ EmailField("email", "Email", REQUIRED) ] @classmethod def on_success(cls, request, values): email = values['email'] try: if request.json_body.get('isResend'): ResendRequestProc(request, {'email':email}) else: PasswordRequestProc(request, {'email':email}) except DBMessage, e: if e.message in ['NO_USER', 'NO_USER_WITH_THIS_EMAIL', 'NO_OWNER_WITH_THIS_EMAIL']: errors = {"email": "Unknown email address."} return {'values' : values, 'errors':errors} elif e.message == "TOKEN_SET_IN_LAST_24_HOURS": values['isResend'] = True return {'values' : values, 'errors':{'email': "Email has been sent in last 24 hours!"}} else: raise e request.session.flash(GenericSuccessMessage("An email to reset your password has been sent to: {email}!".format(**values)), "generic_messages") return {"success":True, "redirect":request.fwd_url("admin_login")} class PasswordResetForm(BaseForm): successmsg = "Your password has been changed. You can now log in using your new password." fields = [ PasswordField("pwd", "Password", REQUIRED) , PasswordField("pwdconfirm", "Confirm password", REQUIRED) ] chained_validators = [formencode.validators.FieldsMatch('pwd', 'pwdconfirm')] @classmethod def on_success(cls, request, values): try: UpdatePasswordProc(request, {'token':request.context.user.token, 'pwd':values['pwd']}) except DBMessage: raise # HORROR HAPPENED request.session.flash(GenericSuccessMessage(cls.successmsg), "generic_messages") return {'success':True, 'redirect': request.fwd_url("admin_index"), 'message': cls.successmsg}
UTF-8
Python
false
false
2,013
9,594,956,987,688
34c69ab84f71e0e1bb31df117e9b9ba5ebe12b33
be84a1d38369ef6649a7e5d53338f8afec969f33
/src/SVMFile.py
316125c21ead983a2f4cc98aeb4828a78f7feb39
[]
no_license
Joylim/Classifier
https://github.com/Joylim/Classifier
0229ddfa64ce033b6999b8a269f0189dd2b69a67
4c675dc34dbf43d5d56d7e06ae9a309abbef6898
refs/heads/master
2021-03-12T20:15:40.424282
2013-12-29T14:14:04
2013-12-29T14:14:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#i*- coding=utf-8 -*- #THU #12-16-2013 import VSM import pickle def saveSVMTrainFile(label,FileNum): #class 1 label=1 f=open('../data/trainData/SVMFile/SVMTrainFile.txt','a') slabel=('%d ') %label #f.write(slabel) #f.write(' ') for i in range(FileNum): s=('../data/trainData/Data/class%d/%d.txt') % (label,i) print "text i",i #f.write(slabel) t=VSM.TextToVector(s) if len(t)>0: f.write(slabel) for k in range(len(t)): str=('%d:%d ') % (t[k][0],t[k][1]) f.write(str) f.write('\r\n') #f.write('end') f.close() def saveSVMTestFile(): def saveSVM(FileNum): for i in range(4): label=i+1 saveSVMTrainFile(label,FileNum) print "saveSVMTrainFile has finished!" if __name__=='__main__': #saveSVM(250)
UTF-8
Python
false
false
2,013
11,922,829,225,418
9f72b6d76d84adf8d4b1160e5a333d00bbcd6a8d
62665d9f4446eb4ab79d06e22347002bed798de9
/system/site_builder.py
ac302b356a39f2f3efb6d7ea2c0b101574114ed6
[]
no_license
derekzhang79/website-5
https://github.com/derekzhang79/website-5
917ae1f59399abd219afa7124983e59fd12f769f
72a856bc05e424e5580a15bd90361cc1ee76bf59
refs/heads/master
2020-12-30T23:34:01.923006
2013-07-21T01:10:34
2013-07-21T01:10:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import __init__ import __main__ import cherrypy from jinja2 import Environment, FileSystemLoader, exceptions class builder(): env = Environment( auto_reload=True, loader=FileSystemLoader(__main__.core.APP_DIR+'templates/') ) def __init__(self, core = None): try: self.core except: self.core = __main__.core def throwWebError(self, error_code = 404, params = {}): error = 'Unknown error' if error_code == 404: error = 'Page Not Found' data = {'fields': {'error': error, 'code': error_code }} return self.loadTemplate('./service/error.jinja2', data) def throwFrameworkError(self, name, context = {}): data = { 'fields': { 'error_name': name, 'context': context } } if not self.core.conf['debug']['framework_errors']: return self.throwWebError() return self.loadTemplate(self.core.SERVICE_TEMPLATES['framework_error']+'.jinja2', data) def httpRedirect(self, url): raise cherrypy.HTTPRedirect(url) def loadTemplate(self, filename = '', data = {'fields': {} }): if not 'current_page' in data['fields']: data['fields'].update({ '__base__': { 'current_page': filename, 'app_name': self.core.__appname__, 'framework': self.core.__framework__['name']+', version: '+self.core.__framework__['version'], 'version': self.core.__version__, 'address': cherrypy.request.path_info[1:], 'revision': self.core.__revision__, 'conf_name': self.core.conf['conf_name'] } }) data['fields']['__base__'].update(self.core.base_fields) try: template = self.env.get_template(filename) except exceptions.TemplateNotFound, e: return self.throwFrameworkError('template not found', {'template name': str(e)}) text = template.render(data['fields']) if self.core.conf['debug']['web_debug']: template = self.env.get_template(self.core.SERVICE_TEMPLATES['debug']+'.jinja2') text += template.render(data) if self.core.conf['debug']['model_debug']: template = self.env.get_template(self.core.SERVICE_TEMPLATES['debug_model']+'.jinja2') text += template.render({'__debug_model': self.core.model}) return text
UTF-8
Python
false
false
2,013
292,057,814,715
ad79dedeaf808fc47bf6f634c6441b7e7e4980b7
a3577a6832ddf3b7477f967fb5cbd9ab9c609b9a
/branches/1.0/start.py
eca81c55bef5f2b3e232700ff4e631e122e9a166
[ "GPL-3.0-only" ]
non_permissive
BackupTheBerlios/freq-dev-svn
https://github.com/BackupTheBerlios/freq-dev-svn
5573eea0646a88d3e32785d21f150695a07a3730
82bc821d17996a32c18228c0b20b0fcaa4df0079
refs/heads/master
2020-05-23T14:29:03.267975
2012-04-10T23:41:42
2012-04-10T23:41:42
40,663,392
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/local/bin/python import sys sys.stdout.write('Initializing... ') from twisted.words.protocols.jabber import xmlstream from twisted.words.protocols.jabber.client import IQ from twisted.web.html import escape import traceback import re import config from twisted.internet import reactor import os import time wd = os.path.dirname(sys.argv[0]) if not wd: wd = '.' os.chdir(wd) sys.path.insert(1, 'src/kernel') sys.path.insert(1, 'modules') try: fp = file(config.PIDFILE, 'r') p = fp.read() fp.close() os.kill(int(p), 9) time.sleep(5) sys.stdout.write('pid %s killed.. ' % (p, )) except: pass fp = file(config.PIDFILE, 'w') fp.write(str(os.getpid())) fp.close() from freq import freqbot import lang bot = freqbot(globals()) try: bot.plug.load_all() print 'reactor.run()' reactor.run() except: bot.log.err(escape('fatal error: %s' % (traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback), ))) del bot raise
UTF-8
Python
false
false
2,012
17,824,114,291,851
1612b0f3dfdf5ac2230b4ea97268a3c19ef74961
f678596084a6880f52f0e88ddc4e478f54359b57
/examples/diode-dc-curve.py
644af9faeebe204b6c3b7ab8885c6ab59f9677be
[ "GPL-3.0-only" ]
non_permissive
BatteryPower/PySpice
https://github.com/BatteryPower/PySpice
4abda294093ec6de7933742f6a42ac504bc22123
1d58f6dec2625aa094b6c9054f3e781294d4e429
refs/heads/master
2021-01-14T09:24:50.062057
2014-04-18T17:27:29
2014-04-18T17:27:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#################################################################################################### import os from matplotlib import pylab #################################################################################################### import PySpice.Logging.Logging as Logging logger = Logging.setup_logging() #################################################################################################### from PySpice.Netlist import Circuit from PySpice.SpiceLibrary import SpiceLibrary from PySpice.Pipe import SpiceServer from PySpice.Units import * #################################################################################################### libraries_path = os.path.join(os.path.dirname(__file__), 'libraries') spice_library = SpiceLibrary(libraries_path) spice_server = SpiceServer() #################################################################################################### circuit = Circuit('Diode DC Curve') circuit.include(spice_library['1N4148']) # 1N5919B: 5.6 V, 3.0 W Zener Diode Voltage Regulator circuit.include(spice_library['d1n5919brl']) circuit.V('input', 'in', circuit.gnd, '10V') circuit.R(1, 'in', 'out', kilo(1)) # circuit.X('D1', '1N4148', 'out', circuit.gnd) circuit.X('DZ1', 'd1n5919brl', 'out', circuit.gnd) simulation = circuit.simulation(temperature=25, nominal_temperature=25) simulation.dc(Vinput=slice(-20, 20, .1)) print str(simulation) raw_file = spice_server(simulation) for field in raw_file.variables: print field analysis = raw_file.analysis # pylab.plot(data['v(out)'], (data['v(in)'] - data['v(out)'])/1000) pylab.plot(analysis.out.v, -analysis.vinput.v) # .i pylab.axvline(x=-5.6, color='blue') pylab.legend(('Diode curve',), loc=(.1,.8)) pylab.grid() pylab.xlabel('Voltage [V]') pylab.ylabel('Current [A]') pylab.show() #################################################################################################### # # End # ####################################################################################################
UTF-8
Python
false
false
2,014
8,641,474,229,270
a65b205100f1975f3160b71d0333fa9a16cec55c
b2b5b99a6a93b787d2d0a1db14b6033c3bbac912
/leagueoflegends/views.py
684788e381b4756cfe8876f2571c84db5a708e61
[]
no_license
LeonidasEsteban/anothernoob.github
https://github.com/LeonidasEsteban/anothernoob.github
ddfccbc01146ebfa9430c6a08175e2ad14e1d32d
9d238805ad5c29ef29942ab5f189a8fec817f414
refs/heads/master
2016-09-06T06:45:18.992591
2014-03-06T08:46:14
2014-03-06T08:46:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from leagueoflegends.models import Players from leagueoflegends.forms import SummonerForm import os from leagueoflegends.models import Champions def champion_list(request): environ = os.environ champion_list = Champions.objects.all() return render_to_response('test.html', {'champion_list': champion_list, 'environ': environ}, context_instance = RequestContext(request)) def league_index(request): if request.method == 'POST': form = SummonerForm(request.POST) if form.is_valid(): data = SummonerForm.cleaned_data['nickname'] template = 'league.html' try: summoner = Players.objects.get(user = request.user) except: summoner = None context = { 'summoner': summoner, 'summonerForm': SummonerForm } return render_to_response(template, context, context_instance = RequestContext(request))
UTF-8
Python
false
false
2,014
2,199,023,256,904
1233026e2c628c9f1b1825d19e2374f1716c4cc8
12308a4b820f4617494bc4690690fd5505a9154e
/svc/ui/smntcs/dacoder.py
7be6545579a25946d89798aa453f92eae0db81dd
[ "GPL-3.0-only", "GPL-1.0-or-later", "GPL-2.0-or-later", "GPL-2.0-only" ]
non_permissive
pombredanne/extended-hidden-vector-state-parser
https://github.com/pombredanne/extended-hidden-vector-state-parser
2c2b89b243924c38d0bcc43501018989388b8b57
7b559f7a2ce7215d2d9765b7019ae1a911978dba
refs/heads/master
2021-01-15T23:02:57.111346
2009-04-06T08:26:26
2009-04-06T08:26:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# SVC library - usefull Python routines and classes # Copyright (C) 2006-2008 Jan Svec, [email protected] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from svc.scripting import * from svc.ui.smntcs import fsm class DacoderFSM(fsm.FSM): def __init__(self, fsm_dir): parts = { 'name': 'dacoder', 'in_maps': ['dacoder.isym'], 'out_map': 'dacoder.osym', 'parts': ['dacoder1.fsm', 'dacoder2.fsm'], } super(DacoderFSM, self).__init__(fsm_dir, parts, nbest=1) def mapInput(self, input): map = self.in_maps[0] _user_ = map['_user_'] _operator_ = map['_operator_'] _unseen_ = map['_unseen_'] _empty_ = map['_empty_'] input = [j.split() for j in input.split(';')] ret = [] for j, da in enumerate(input): spkr = [_operator_, _user_][j%2] ret.append( (spkr, None) ) for i in da: sym = map.get(i, _unseen_) ret.append( (sym, i) ) ret.append( (_empty_, None) ) return ret def mapOutput(self, output, orig_input): ret = [] for item in output: iindex, osym, weight = item if osym != 0: osym = self.out_map[osym] ret.append(osym) return ret class SegmentorFSM(fsm.FSM): def __init__(self, fsm_dir): parts = { 'name': 'hvsseg', 'in_maps': ['hvsseg.isym1'], 'out_map': 'dacoder.fsm.osym', 'parts': ['hvsseg.fsm', 'dacoder.fsm', 'dialogue_act.fsm'], } super(SegmentorFSM, self).__init__(fsm_dir, parts, nbest=3) def mapInput(self, input): map = self.in_maps[0] _unseen_ = map['_unseen_'] _empty_ = map['_empty_'] ret = [] for i in input.split(): sym = map.get(i, _unseen_) ret.append( (sym, i) ) ret.append( (_empty_, None) ) return ret def mapOutput(self, output, orig_input): ret = [] for item in output: iindex, osym, weight = item if osym != 0: osym = self.out_map[osym] ret.append(osym) return ret class Dacoder(Script): options = { 'model_dir': (Required, String), } posOpts = ['model_dir'] def main(self, model_dir): fsm = SegmentorFSM(model_dir) while True: i = unicode(raw_input(), 'latin2') #print fsm.mapInput(i) print fsm.processInput(i)
UTF-8
Python
false
false
2,009
5,454,608,503,780
e1ef1e4861b807a61d9acc3876fa6c9a6db31e16
867af5e27d44e89f00ba60fc3cdbd3791590b823
/src/config.py
d16f8247f0e50c7469478e74254cfb32d359a051
[]
no_license
Xowap/KarteServer
https://github.com/Xowap/KarteServer
a754050f78e0f6fe2b93f007cde180ab5f4a3861
ce3b24922f2932a203d6c8f749365ffbcc589fc5
refs/heads/master
2021-01-01T18:11:42.616568
2011-12-16T14:45:53
2011-12-16T14:45:53
2,651,532
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- encoding: utf-8 -*- DB_MODULE = "psycopg2" DB_HOST = "localhost" DB_USER = "karte" DB_PASS = "tagada" DB_BASE = "karte"
UTF-8
Python
false
false
2,011
15,642,270,939,634
9bd198597b8e30a77d2286e9c1c5a0b84e1cb01c
c4ac2306c26980df58aaa374b07b2b81d0fa4508
/newscollect/settings.py
d3b3bf5ae73f38ecfb6ff8a5fe2caa57a8662652
[]
no_license
demelziraptor/newscollect
https://github.com/demelziraptor/newscollect
aceadc474a002142278513dd2134fce4888ace81
ae79b2555cc59fd5f6a3772ab1e9b2ba5903a21c
refs/heads/master
2020-05-30T12:30:20.048539
2014-08-07T19:49:40
2014-08-07T19:49:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Scrapy settings for newscollect project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'newscollect' SPIDER_MODULES = ['newscollect.spiders'] NEWSPIDER_MODULE = 'newscollect.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'newscollect (+http://www.yourdomain.com)' ITEM_PIPELINES = { 'newscollect.pipelines.DatelessPipeline': 300, 'newscollect.pipelines.ParseDatePipeline': 400, 'newscollect.pipelines.NewscollectPipeline': 1000 }
UTF-8
Python
false
false
2,014
3,272,765,128,121
a34bab295439656669b573803818f597162507e1
a15463975753fe8eda5b86d2db46d180a4375bef
/UsingDesigner/firstdlg.pyw
c82922d9731da339d5e08a02aebff0f2596d608a
[]
no_license
folger/PyQtRapid
https://github.com/folger/PyQtRapid
3d00e330e1f4a6e36744f8fda83d7bf04678de8e
619144615d0af3d60854cba136202b29eb5f4481
refs/heads/master
2016-09-05T10:32:08.816897
2014-02-16T14:01:23
2014-02-16T14:01:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from ui_first import Ui_FirstDialog class MyDlg(QDialog, Ui_FirstDialog): def __init__(self, parent=None): super(MyDlg, self).__init__(parent) self.setupUi(self) self.connect(self.btnTest, SIGNAL("clicked()"), self.helloClicked) def helloClicked(self): QMessageBox.information(self, "Hello", "Hello World", QMessageBox.Ok | QMessageBox.Cancel) app = QApplication(sys.argv) dlg = MyDlg() dlg.show() app.exec_()
UTF-8
Python
false
false
2,014
8,383,776,177,215
01c3b15720ac7834f304ccb54323807787b5f9b5
9a39dcd72ba8ded07ea0e1002828d3ebffe21113
/auth.py
98cae09f1a0768daa63c64e39d658ef6df464b95
[ "LicenseRef-scancode-public-domain" ]
non_permissive
00/wikihouse
https://github.com/00/wikihouse
994882c2bfd7246547a9d12b05692ff2315b769d
f7b697ec36a051bb69e4d575c1b600b802c7c59b
refs/heads/master
2016-09-06T15:17:52.067633
2014-11-07T15:25:38
2014-11-07T15:25:38
2,136,845
15
4
null
false
2014-11-07T15:25:38
2011-08-01T13:37:12
2014-10-20T12:11:38
2014-11-07T15:25:38
868
28
4
3
Python
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Provides `@auth.required` and `@auth.admin` decorators, using `google.appengine.api.users`. """ from google.appengine.api import users def required(handler_method): """ Decorator to require that a user be logged in to access a handler. """ def check_login(self, *args, **kwargs): user = users.get_current_user() if user is None: return self.redirect(users.create_login_url(self.request.path)) return handler_method(self, *args, **kwargs) return check_login def admin(handler_method): """ Decorator to require that a user be logged in and an admin. """ def check_admin(self, *args, **kwargs): user = users.get_current_user() if user is None: return self.redirect(users.create_login_url(self.request.path)) elif not users.is_current_user_admin(): return self.error(status=403) return handler_method(self, *args, **kwargs) return check_admin
UTF-8
Python
false
false
2,014
3,246,995,312,019
56c0d619cb1e1cf1532abc2a0ccceb96f895084e
d44b99e1bab628fadbb3dbada6042e6de2ce7fef
/src/scissor/error.py
caec16a36e502e1052d02d9223dda477bf8dbb4e
[]
no_license
avanc/scissor
https://github.com/avanc/scissor
baa1d117d48c9d2eb63b1821f910d4620debe0c1
f6f8c34c509ea94c262e0613cb6c604a411f6b29
refs/heads/master
2021-01-01T19:51:31.372935
2013-10-22T17:08:30
2013-10-22T17:08:30
9,778,226
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (C) 2013 Sven Klomp ([email protected]) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. class WrongFileTypeError(Exception): """Exception raised for wrong filetype. Attributes: filename -- filename of wrong type expected -- Expected file type """ def __init__(self, filename, expected): self.filename = filename self.expected = expected def __str__(self): return "Got '{0}' but expected '*{1}'.".format(self.filename, self.expected)
UTF-8
Python
false
false
2,013
10,909,216,952,095
9729050951ec47c21cd3c8ca11cfcd4a1f7a894d
62d4b4742f96d9e30a579bc8a1ee4f4b2be6fb94
/grasp_analyzer.py
c2e490803671e846963490f0cd49f3100dd5e372
[]
no_license
CURG-archive/trajectory_planner
https://github.com/CURG-archive/trajectory_planner
760d729b1d090fa763d0148463af21e2d0e86ec5
0c91126f912dbc086f622ce504d4fdcedba74e80
refs/heads/master
2021-05-28T06:03:06.046326
2014-05-02T14:13:08
2014-05-02T14:13:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sklearn import * import rospy import random import trajectory_planner as tp import graspit_msgs.msg import itertools import tf_conversions.posemath as pm from numpy import pi, eye, dot, cross, linalg, sqrt, ceil, size from numpy import hstack, vstack, mat, array, arange, fabs, unique from math import acos import pdb import std_msgs.msg class GraspAnalyzer(object): def __init__(self, global_data, analyze_grasp_topic = "/graspit/analyze_grasps", demo_pose_topic = "/graspit/analyze_demo_pose"): self.data = set() self.grasp_analysis_func = [] self.retrain_threshold = 1 self.model = neighbors.NearestNeighbors(n_neighbors=20, algorithm = 'kd_tree') self.global_data = global_data self.max_data_len = 5000 self.array_data = [] self.grasp_classes = [] self.analyze_grasp_subscriber = rospy.Subscriber(analyze_grasp_topic, graspit_msgs.msg.Grasp, self.analyze_grasp, queue_size = 1) self.analyze_pose_subscriber = rospy.Subscriber(demo_pose_topic, graspit_msgs.msg.Grasp, self.analyze_demonstration_pose, queue_size = 1) self.grasp_analysis_publisher = rospy.Publisher(analyze_grasp_topic + "_results", graspit_msgs.msg.GraspStatus) self.demo_pose_analysis_publisher = rospy.Publisher(demo_pose_topic + "_results", std_msgs.msg.Float32) def data_to_array(self): self.array_data = array([pm.toMatrix(pm.fromMsg(grasp_msg[0].final_grasp_pose))[:3,3] for grasp_msg in self.data]) def analyze_demonstration_pose(self, demo_grasp): if(len(self.data) ==0): return 1.0 demo_pose = pm.toMatrix(pm.fromMsg(demo_grasp.final_grasp_pose)) demo_position = demo_pose[:3,3] distances, indices = self.model.kneighbors(demo_position) indices = unique(indices) nbrs = [t for t in itertools.compress(self.data, indices)] valid_nbrs = [] for n in nbrs: pose = pm.toMatrix(pm.fromMsg(n[0].final_grasp_pose)) if (acos(dot(pose[:3,2],demo_pose[:3,2]) < .52)): valid_nbrs.append(n) if len(valid_nbrs): success_probability = len([n for n in valid_nbrs if n[1] & 1])/(1.0*len(valid_nbrs)) else: success_probability = 0 self.demo_pose_analysis_publisher.publish(success_probability) return success_probability def train_model(self, grasp, grasp_class): self.data.add((grasp, grasp_class)) if len(self.data) > self.max_data_len: self.sparcify_data() if not len(self.data)%self.retrain_threshold: self.data_to_array() self.model.fit(self.array_data) def sparcify_data(self): self.data = random.sample(self.data, len(self.data)/2.0) def test_grasp_msg(self, grasp_msg): """@brief """ def set_home(rob): rob.SetActiveDOFs(range(10)) rob.SetActiveDOFValues([0,0,0,0,0,0,0,0,0,0]) def set_barrett_hand_open(rob): rob.SetActiveDOFs(range(6,10)) rob.SetActiveDOFValues([0,0,0,0]) def set_barrett_hand_dofs(rob, dofs): rob.SetActiveDOFs(range(6,10)) rob.SetActiveDOFValues(dofs) def set_staubli_dofs(rob, dofs): rob.SetActiveDOFs(range(6)) rob.SetActiveDOFValues(dofs) def grasp_tran_from_msg(grasp_msg): grasp_tran = pm.toMatrix(pm.fromMsg(grasp_msg.final_grasp_pose)) grasp_tran[0:3,3] /=1000 #mm to meters return grasp_tran def test_pose_reachability(rob, tran): #Test if end effector pose is in collision rob.SetActiveDOFs(range(6)) end_effector_collision = rob.GetManipulators()[0].CheckEndEffectorCollision(tran) if end_effector_collision: return graspit_msgs.msg.GraspStatus.ENDEFFECTORERROR #Test if pose is reachable j = rob.GetManipulators()[0].FindIKSolutions(tran, tp.IkFilterOptions.CheckEnvCollisions) if j != []: return graspit_msgs.msg.GraspStatus.SUCCESS #Test if pose is reachable if we ignore collisions all together j = rob.GetManipulators()[0].FindIKSolutions(tran, 0) if j != []: return graspit_msgs.msg.GraspStatus.UNREACHABLE else: return (graspit_msgs.msg.GraspStatus.UNREACHABLE | graspit_msgs.msg.GraspStatus.ENDEFFECTORERROR) def test_trajectory_reachability(tran): success, trajectory_filename, dof_list, j = tp.run_cbirrt_with_tran( self.global_data.or_env, tran, [], 1 ) return success def set_barrett_enabled(rob, collision): links = rob.GetManipulators()[0].GetChildLinks() [l.Enable(collision) for l in links[1:]] def test_pregrasp_to_grasp(rob, pre_grasp, grasp, steps): grasp_diff = (grasp - pre_grasp)/steps test_reachability_result = graspit_msgs.msg.GraspStatus.SUCCESS for i in xrange(1, steps): test_tran = pre_grasp + i * grasp_diff test_reachability_result = test_pose_reachability(rob, test_tran) if test_reachability_result is not graspit_msgs.msg.GraspStatus.SUCCESS: print "Failed in test pregrasp to grasp in step %i in pose %s with result %i\n"%(i, grasp_tran, test_reachability_result) break return test_reachability_result def test_hand_closing(rob, start_dof, end_dof, steps): dof_diff = (array(end_dof) - array(start_dof))/steps #self.global_data.or_env.GetCollisionChecker().SetCollisionOptions(tp.CollisionOptions.ActiveDOFs) for i in xrange(1, steps): dofs = start_dof + i * dof_diff set_barrett_hand_dofs(rob, dofs) rob.GetEnv().UpdatePublishedBodies() end_effector_collision = rob.GetEnv().CheckCollision(rob) #raw_input('continue to next test') if end_effector_collision: return False return True def test_grasp_closure(rob, grasp_msg): pre_grasp_dof = [0,0,0,grasp_msg.pre_grasp_dof[0]] grasp_dof = [grasp_msg.final_grasp_dof[1],grasp_msg.final_grasp_dof[2], grasp_msg.final_grasp_dof[3], grasp_msg.final_grasp_dof[0]] return test_hand_closing(rob, pre_grasp_dof, grasp_dof, 10) with self.global_data.or_env: robot = self.global_data.or_env.GetRobots()[0] set_home(robot) target_object = self.global_data.or_env.GetKinBody(grasp_msg.object_name) if target_object is None: rospy.logwarn("Trying to analyze grasp on %s, but the object is not in the planning environment", grasp_msg.object_name) return None, None, None obj_tran = target_object.GetTransform() grasp_rel_tran = grasp_tran_from_msg(grasp_msg) grasp_tran = dot(obj_tran, grasp_rel_tran) pre_grasp_tran = dot(obj_tran, tp.get_pregrasp_tran_from_tran(grasp_rel_tran, -.05)) pregrasp_test = test_pose_reachability(robot, pre_grasp_tran) if pregrasp_test is not graspit_msgs.msg.GraspStatus.SUCCESS: return graspit_msgs.msg.GraspStatus.FAILED, graspit_msgs.msg.GraspStatus.PREGRASPERROR, pregrasp_test #Can we reach the grasp pose #Disable target object collisions target_object.Enable(False) grasp_test = test_pose_reachability(robot, grasp_tran) if grasp_test is not graspit_msgs.msg.GraspStatus.SUCCESS: return graspit_msgs.msg.GraspStatus.FAILED, graspit_msgs.msg.GraspStatus.GRASPERROR, grasp_test move_forward_test = test_pregrasp_to_grasp(robot, pre_grasp_tran, grasp_tran, 10) if move_forward_test is not graspit_msgs.msg.GraspStatus.SUCCESS: return graspit_msgs.msg.GraspStatus.FAILED, (graspit_msgs.msg.GraspStatus.PREGRASPERROR | graspit_msgs.msg.GraspStatus.GRASPERROR), move_forward_test j = robot.GetManipulators()[0].FindIKSolutions(grasp_tran, tp.IkFilterOptions.CheckEnvCollisions) if not j: pdb.set_trace() set_staubli_dofs(robot, j[0]) closure_result = test_grasp_closure(robot, grasp_msg) if not closure_result: return graspit_msgs.msg.GraspStatus.FAILED, (graspit_msgs.msg.GraspStatus.PREGRASPERROR | graspit_msgs.msg.GraspStatus.GRASPERROR), graspit_msgs.msg.GraspStatus.ENDEFFECTORERROR target_object.Enable(True) set_home(robot) #Can we reach the pregrasp pose trajectory_test = test_trajectory_reachability(pre_grasp_tran) if not trajectory_test: return graspit_msgs.msg.GraspStatus.FAILED, graspit_msgs.msg.GraspStatus.ROBOTERROR, graspit_msgs.msg.GraspStatus.PREGRASPERROR return graspit_msgs.msg.GraspStatus.SUCCESS, 0, 0 def analyze_grasp(self, grasp_msg): success, failure_mode, score = self.test_grasp_msg(grasp_msg) #success == None implies the analysis itself failed to run. Do nothing for now. if success == None: return gs = graspit_msgs.msg.GraspStatus() if not success: gs.status_msg = "Grasp %i unreachable: %i %i %i"%(grasp_msg.secondary_qualities[0], success, failure_mode, score) print gs.status_msg gs.grasp_identifier = grasp_msg.secondary_qualities[0] gs.grasp_status = success | failure_mode | score self.train_model(grasp_msg, gs.grasp_status) self.grasp_analysis_publisher.publish(gs)
UTF-8
Python
false
false
2,014
13,975,823,628,270
372155e1f62ecbdbe5a2509c02295754464b5779
80693ffeabae00795eb53a350e7eed5d32ac3654
/duct_tape/template.py
c79bbf173d9849c6fe7a3a643a871fdab22e0323
[]
no_license
luzfcb/django-duct-tape
https://github.com/luzfcb/django-duct-tape
49d0c6ff3d8570bd327fa4137e7c20422b6f9d46
621b8a1a1402394f46216834634c786336b21cff
refs/heads/master
2021-01-18T07:46:12.165995
2011-12-29T23:14:57
2011-12-29T23:14:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.template import RequestContext as D_RequestContext from duct_tape.lib.template_queue import TemplateQueue class RequestContext(D_RequestContext): def __init__(self, request, dict=None,**kwargs): if not dict: dict = {} if not 'tab' in dict: dict['tab'] = None if not 'duct_tape__behavior_queue' in dict: dict['duct_tape__behavior_queue'] = TemplateQueue() super(RequestContext,self).__init__(request,dict=dict,**kwargs)
UTF-8
Python
false
false
2,011
17,858,474,032,436
61a3e7c1f7c7e455d866def423baaa6d4c1dba8e
7c920b0d53225854501dd366a3982232d3d13fc9
/parking-ticket/urls.py
261fbc57baa530ee9ed7862b9fb6db082a4ae106
[]
no_license
mamun1980/parking-tickets
https://github.com/mamun1980/parking-tickets
6c5757a4fe529340d641ccfa8d5b13b6c8f8f4b5
744d6001a8ba2ab9645c7347e03fe1bc1b926722
refs/heads/master
2021-01-10T07:49:49.075728
2013-02-27T09:52:41
2013-02-27T09:52:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'tgis.views.home', name='home'), url(r'^test/$', 'tgis.views.test', name='test'), url(r'^getlaw/$', 'tgis.views.getLaw', name='getLaw'), )
UTF-8
Python
false
false
2,013
16,157,666,989,571
bddd398c9b70f05740e411b6dbf42a03bf3459b5
22955081c03ec1553d5403dd44f56ea4b4ed7d61
/gub/specs/fondu.py
98a3d20d6a788b96b6a3ec5e61a53f39e9355e6c
[ "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-or-later" ]
non_permissive
janneke/gub
https://github.com/janneke/gub
b2c9f439dfd8a24c23209fa05830940792838778
6c807d584396406446ed43bf8dd6e9026ae5d4ab
refs/heads/master
2017-09-07T21:49:27.170275
2012-08-28T11:54:18
2012-08-31T07:03:19
68,877
5
5
null
null
null
null
null
null
null
null
null
null
null
null
null
from gub import target class Fondu (target.AutoBuild): source = 'http://fondu.sourceforge.net/fondu_src-060102.tgz' def srcdir (self): return '%(allsrcdir)s/' + ('fondu-%s' % self.version ()) def patch (self): target.AutoBuild.patch (self) self.file_sub ([('wilprefix', 'prefix')], '%(srcdir)s/Makefile.in') class Fondu__darwin (Fondu): def patch (self): Fondu.patch (self) self.file_sub ([('/System/Library/', '%(system_root)s/System/Library/')], '%(srcdir)s/Makefile.in')
UTF-8
Python
false
false
2,012
14,474,039,834,560
dcc972898a157b57a0066fbf031dde9053965ca9
4f59105e4ef8e18099b3de18dc93252f19982a89
/figureout/mainGUI.py
66fc4daa91de1decf38a5ce8da0f41fe631cf447
[]
no_license
lbin/FigureOut
https://github.com/lbin/FigureOut
6d5d4c4beb7c426c24aa23e1fcd4e9176207a5a7
57cf66f188d3648bfacdc0bd754e10c774893cc6
refs/heads/master
2016-03-24T07:10:53.128781
2014-10-03T06:36:18
2014-10-03T06:36:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from __future__ import print_function from IO import * from Data import * from Command import * from DataDockCtr import * from ConfSettingWindow import * from Configurator import * from matplotlib._png import read_png import sys #from matplotlib.backend_bases import key_press_handler from matplotlib.backends.backend_qt4agg import ( FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar) from matplotlib.backends import qt4_compat use_pyside = qt4_compat.QT_API == qt4_compat.QT_API_PYSIDE import matplotlib.pyplot as plt from matplotlib.widgets import Cursor from matplotlib.offsetbox import OffsetImage, AnnotationBbox if use_pyside: from PySide.QtCore import * from PySide.QtGui import * else: from PyQt4.QtCore import * from PyQt4.QtGui import * class Window(QMainWindow): def __init__(self, parent=None): super(Window, self).__init__(parent) self.main_frame = QWidget() self.createActions() self.createMenus() message = "Figure Out Application!" self.statusBar().showMessage(message) self.setWindowTitle("Figure Out") self.resize(960,640) self.fig = plt.figure(figsize=(960,640), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0)); self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) self.setCentralWidget(self.canvas) self.canvas.setFocusPolicy(Qt.StrongFocus) self.canvas.setFocus() self.undoStack = QUndoStack(self) self.io=IO() self.data=Data() self.dataDock = QDockWidget("Data Browse", self) self.dataDock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.addDockWidget(Qt.RightDockWidgetArea, self.dataDock) self.dataDockCtr=DataDockCtr(self.dataDock) self.dataDock.setFloating(True) self.dataDock.move(1000,200) #self.confDock = QDockWidget("Conf Setting", self) #self.confDock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) #self.addDockWidget(Qt.RightDockWidgetArea, self.confDock) #self.confDockCtr=ConfDockCtr(self.confDock) #self.confDock.setFloating(True) #self.confDock.hide() self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) self.cursor = Cursor(self.ax, useblit=True, color='red', linewidth=1 ) #self.setWindowFlags(Qt.FramelessWindowHint) vbox = QVBoxLayout() vbox.addWidget(self.mpl_toolbar) vbox.addWidget(self.canvas) # the matplotlib canvas vbox.setSpacing(0) vbox.setContentsMargins(0,0,0,0) self.main_frame.setLayout(vbox) self.setCentralWidget(self.main_frame) #self.setStyleSheet("QFrame {background-image:url(:/images/frame.jpg);border:1px solid black;}") #self.setStyleSheet("QLineEdit { background-color: transparent; border: 0px; border-width: 0px;}") self.labelEdit = QLineEdit(self.canvas) self.labelEdit.resize(20, self.labelEdit.height()) self.labelEdit.move(200,200) self.labelEdit.hide() self.fig.canvas.mpl_connect('button_press_event', self.onLeftClick) self.fig.canvas.mpl_connect('pick_event', self.OnSelectedPeak) #self.fig.canvas.mpl_connect('scroll_event', self.onMouseScroll) self.inaxes=False self.infig=False self.conf = Configurator() self.fig.canvas.mpl_connect('figure_enter_event', self.enter_figure) self.fig.canvas.mpl_connect('figure_leave_event', self.leave_figure) self.fig.canvas.mpl_connect('axes_enter_event', self.enter_axes) self.fig.canvas.mpl_connect('axes_leave_event', self.leave_axes) #self.connect(self.labelEdit, SIGNAL("lostfocus()"),self.labelEditChangedFocusSlot) self.labelEdit.editingFinished.connect(self.labelEditChangedFocusSlot) self.labelEdit.textChanged.connect(self.resizeLineEditToContents) def contextMenuEvent(self, event): menu = QMenu(self) menu.addAction(self.openAct) menu.addAction(self.undoAct) menu.addAction(self.redoAct) menu.addSeparator() menu.addAction(self.modelNormalAct) menu.addAction(self.modelPeakAct) menu.addAction(self.modelTextAct) menu.addAction(self.modelImageAct) menu.addSeparator() menu.exec_(event.globalPos()) def createActions(self): self.openAct = QAction("&Open...", self, shortcut=QKeySequence.Open, statusTip="Open an existing file", triggered=self.openFile) self.undoAct = QAction("&Undo", self, shortcut=QKeySequence.Undo, statusTip="Undo", triggered=self.undo) self.redoAct = QAction("&Redo", self, shortcut=QKeySequence.Redo, statusTip="Redo", triggered=self.redo) self.settingAct = QAction("&Setting", self, statusTip="Setting", triggered=self.setting) self.modelNormalAct = QAction("&Normal", self, checkable=True, shortcut="Ctrl+N", statusTip="Normal", triggered=self.setModel2Normal) self.modelPeakAct = QAction("&PeakSelect", self, checkable=True, shortcut="Ctrl+P", statusTip="PeakSelect", triggered=self.setModel2Peak) self.modelTextAct = QAction("&Text", self, checkable=True, shortcut="Ctrl+T", statusTip="Text", triggered=self.setModel2Text) self.modelImageAct = QAction("&Image", self, checkable=True, shortcut="Ctrl+N", statusTip="Image", triggered=self.setModel2Image) self.modelGroup = QActionGroup(self) self.modelGroup.addAction(self.modelNormalAct) self.modelGroup.addAction(self.modelPeakAct) self.modelGroup.addAction(self.modelTextAct) self.modelGroup.addAction(self.modelImageAct) self.modelNormalAct.setChecked(True) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.openAct) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.undoAct) self.editMenu.addAction(self.redoAct) self.modelMenu = self.menuBar().addMenu("&Model") self.modelMenu.addAction(self.modelNormalAct) self.modelMenu.addAction(self.modelPeakAct) self.modelMenu.addAction(self.modelTextAct) self.modelMenu.addAction(self.modelImageAct) self.optionMenu = self.menuBar().addMenu("&Option") self.optionMenu.addAction(self.settingAct) def drawAll(self): self.ax.clear() self.mpl_toolbar.forward() self.drawMainLine() self.drawSelectedPeak() self.drawText() self.drawImage() self.fig.canvas.draw() def setting(self): pass #self.confDock.show() def setModel2Normal(self): self.conf.setModel("Normal") def setModel2Peak(self): self.conf.setModel("PeakSelect") def setModel2Text(self): self.conf.setModel("Text") def setModel2Image(self): self.conf.setModel("Image") def openFile(self): fileName = QFileDialog.getOpenFileName(self,"OpenFile", "./","All Files (*.txt)") lines=self.io.loadData(fileName) self.data.praData(lines) self.dataDockCtr.setData(self.data) self.drawAll() def labelEditChangedFocusSlot(self): self.labelEdit.hide() if not self.labelEdit.text().isEmpty(): text = FOText() text.str = self.labelEdit.text() text.x,text.y = self.lex,self.ley command = AddTextCommand(self.data,text, "AddText") self.undoStack.push(command) self.drawAll() self.labelEdit.clear() def resizeLineEditToContents(self): text = self.labelEdit.text() fm = self.labelEdit.fontMetrics(); w = fm.boundingRect(text).width(); if fm.boundingRect(text).width()<20: w=20 self.labelEdit.resize(w, self.labelEdit.height()) def onLeftClick(self,event): if self.inaxes==True and self.infig == True: if event.button == 1 and event.dblclick: if self.conf.model == "Text": self.labelEdit.show() self.lex,self.ley = self.ax.transAxes.inverted().transform((event.x,event.y)) self.labelEdit.move(event.x,self.canvas.height()-event.y) self.labelEdit.setFocus() if self.conf.model == "Image": imageFileName = QFileDialog.getOpenFileName(self,"OpenImageFile", "./","All Files (*.png)") if not imageFileName.isEmpty(): imageFileName = str(imageFileName.toUtf8()).decode("utf-8") arr_lena = read_png(imageFileName) #imagebox = OffsetImage(arr_lena) image = FOImage() image.xdata,image.ydata = event.xdata,event.ydata image.x,image.y = event.x,event.y image.imageSrc = arr_lena command = AddImageCommand(self.data,image, "AddImage") self.undoStack.push(command) self.drawAll() def OnSelectedPeak(self,event): if self.inaxes==True and self.infig == True: if self.conf.model == "PeakSelect": if event.artist ==self.line: N = len(event.ind) if not N: return True dataind = event.ind[0] command = AddSelectedPeakCommand(self.data,dataind,"SelectPoint") self.undoStack.push(command) self.drawAll() if len(self.texts) != 0 and event.artist == self.texts[0]: textStr, ok = QInputDialog.getText(self, self.tr("Input Text"), self.tr("Input Text"), QLineEdit.Normal) def drawSelectedPeak(self): self.peakPoints=[] for ind in self.data.selectedPeak: x,y= float(self.data.xData[ind]), float(self.data.yData[ind]) self.peakPoints.append(self.ax.plot(x, y, 'o', ms=12, alpha=0.4,color='yellow',picker=True)) self.ax.annotate('local max %f'%(y), xy=(x,y), xytext=(x+30, y),arrowprops=dict(arrowstyle="->", color="0.1",patchB=None,shrinkB=0, connectionstyle="arc3,rad=0.3",)) #def onMouseScroll(self,event): #print 'button=%s, step=%d'%(event.button, event.step) def drawMainLine(self): self.line, = self.ax.plot(self.data.xData, self.data.yData,linewidth=1,color='black',picker=1) def drawText(self): self.texts = [] for text in self.data.foTexts: self.texts.append(self.ax.text(text.x, text.y, text.str,transform=self.ax.transAxes, va='top',picker=True)) def drawImage(self): self.images = [] for image in self.data.foImages: ab = AnnotationBbox(OffsetImage(image.imageSrc),xy=(image.xdata,image.ydata),xybox=(30,30), xycoords='data', boxcoords="offset points", pad=0.1,) self.ax.add_artist(ab) self.images.append(ab) def undo(self): self.undoStack.undo() self.drawAll() def redo(self): self.undoStack.redo() self.drawAll() def enter_axes(self,event): self.inaxes=True def leave_axes(self,event): self.inaxes=False def enter_figure(self,event): self.infig=True def leave_figure(self,event): self.infig=False if __name__ == '__main__': app = QApplication(sys.argv) win = Window() win.show() sys.exit(app.exec_())
UTF-8
Python
false
false
2,014
9,122,510,575,230
00a4b3ec67ad5806e31d2c34fe66aae120fffdd3
f77dc7fa0f5dd41ef8acaf3e5d96ce7e94356c95
/tests/python/typeinference/for.py
5a6da2c2a02329c03916a2d067f1749cd511576a
[ "LGPL-2.0-or-later", "LGPL-2.1-only" ]
non_permissive
retoo/pystructure
https://github.com/retoo/pystructure
932dcba2a25b8d22508cc9f755d6908eac56fc14
a433588027317f24d8c656447b9990b2bac2ab2e
refs/heads/master
2020-06-14T16:25:34.910455
2008-08-31T17:10:18
2008-08-31T17:10:18
1,352,837
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
a = list() a.append(1) a.append(2) for element in a: element ## type int b = [] b.append((1, 3.14)) b.append((2, "test")) for x, y in b: x ## type int y ## type float|str
UTF-8
Python
false
false
2,008
14,139,032,342,691
8f3d8feaefab809054e2aed76d5cb7330c5450cf
17357d3165781a56e95b56ee8fef1742b8e95259
/remote.py
6f3bc9bbb334558c2358e1e125bb504fab6f8ac0
[]
no_license
jcarlos46/golem-py
https://github.com/jcarlos46/golem-py
2187007def1e52bd6111ed2b85cf76e47e90e907
e3377f918fa08ead5e862ad331c193415bd6c97b
refs/heads/master
2022-01-29T02:01:15.114402
2013-02-25T19:55:17
2013-02-25T19:55:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re import os import paramiko from getpass import getpass def info(path): user = re.search('(.*)@',path).group(1) host = re.search('@(.*):',path).group(1) port = re.search(':(\d+)\/',path).group(1) root = re.search(':\d+(\/.*)',path).group(1) root = os.path.abspath(root) return Info(user, host, port, root) def sftpclient(path): info = info(path) password = getpass(info.host + "\'s password: ") t = paramiko.Transport((info.host,info.port)) t.start_client() t.auth_password(info.user,password) sftp = t.open_session() sftp = paramiko.SFTPClient.from_transport(t) return sftp class Info: def __init__(self, user, host, port, root): self.user = user self.host = host self.port = int(port) self.root = root
UTF-8
Python
false
false
2,013
17,171,279,280,044
836542c960199ba1f7643b66071cd2607c53ca4b
3a9482ae9d2b7bc2f961f6906bc13834be32be37
/udata/tests/frontend/test_organization_frontend.py
7e71279ab0ff4d4a4f7df929cdb221a0367f9847
[ "AGPL-3.0-only" ]
non_permissive
rossjones/udata
https://github.com/rossjones/udata
2a73f14010d1d99bbfdb230d08b064d49648419b
076d8cfd8f8f52d09fbb28101c718f1e3a4a8659
refs/heads/master
2020-12-27T06:14:57.661475
2014-05-15T16:22:39
2014-05-15T16:22:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from flask import url_for from udata.models import Organization, Member from . import FrontTestCase from ..factories import OrganizationFactory class OrganizationBlueprintTest(FrontTestCase): def test_render_list(self): '''It should render the organization list page''' with self.autoindex(): organizations = [OrganizationFactory() for i in range(3)] response = self.get(url_for('organizations.list')) self.assert200(response) rendered_organizations = self.get_context_variable('organizations') self.assertEqual(len(rendered_organizations), len(organizations)) def test_render_list_empty(self): '''It should render the organization list page event if empty''' response = self.get(url_for('organizations.list')) self.assert200(response) def test_render_create(self): '''It should render the organization create form''' response = self.get(url_for('organizations.new')) self.assert200(response) def test_create(self): '''It should create a organization and redirect to organization page''' data = OrganizationFactory.attributes() self.login() response = self.post(url_for('organizations.new'), data) organization = Organization.objects.first() self.assertRedirects(response, organization.get_absolute_url()) def test_render_display(self): '''It should render the organization page''' organization = OrganizationFactory() response = self.get(url_for('organizations.show', org=organization)) self.assert200(response) def test_render_edit(self): '''It should render the organization edit form''' user = self.login() organization = OrganizationFactory(members=[Member(user=user, role='admin')]) response = self.get(url_for('organizations.edit', org=organization)) self.assert200(response) def test_edit(self): '''It should handle edit form submit and redirect on organization page''' user = self.login() organization = OrganizationFactory(members=[Member(user=user, role='admin')]) data = organization.to_dict() del data['members'] data['description'] = 'new description' response = self.post(url_for('organizations.edit', org=organization), data) organization.reload() self.assertRedirects(response, organization.get_absolute_url()) self.assertEqual(organization.description, 'new description') def test_render_edit_members(self): '''It should render the organization member edit page''' user = self.login() organization = OrganizationFactory(members=[Member(user=user, role='admin')]) response = self.get(url_for('organizations.edit_members', org=organization)) self.assert200(response) def test_render_edit_teams(self): '''It should render the organization team edit form''' user = self.login() organization = OrganizationFactory(members=[Member(user=user, role='admin')]) response = self.get(url_for('organizations.edit_teams', org=organization)) self.assert200(response) def test_not_found(self): '''It should render the organization page''' response = self.get(url_for('organizations.show', org='not-found')) self.assert404(response)
UTF-8
Python
false
false
2,014
17,076,790,002,570
3ae38d9caa5b909ff130c1403cf07702631e6184
8b06de46d580fb503f9cc7cedcba9d03dc221e81
/script/app.py
916ff9039e66410cd53c0307e8c542bcda8421cd
[]
no_license
codepongo/webapp
https://github.com/codepongo/webapp
d493333752dbda5f88b454c01c558fe2a4c612ae
f06ee92522e27efe89ee9b5f8577bc8c5c464cc9
refs/heads/master
2020-05-17T05:19:34.302473
2013-12-31T04:08:15
2013-12-31T04:08:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import os sys.path.append(os.path.dirname(__file__)) import web web.config.debug = True import hello import about import whereisip urls = ('/hello/(.*)', hello.hello, '/aboutme.*', about.me, '/whereisip.*', whereisip.whereisip, ) app = web.application(urls, globals()) session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'user':None}) if __name__ == '__main__': app.run() else: application = app.wsgifunc()
UTF-8
Python
false
false
2,013
15,238,543,983,442
10ca1317a536548490eb629c48c900d06fd9533e
2efa926489a9df0140b61f9c2b67cae6ab818831
/tools.py
2d9af57fb7ef4d0f1c1743efbc8e4187f0dccda6
[]
no_license
orbisoptimus/move.is
https://github.com/orbisoptimus/move.is
fcc29b9214cbbcef9a048f6f23d5b81b86caeff8
300cb7d0fefcfed5744f6c27e2dba0a2ae799214
refs/heads/master
2016-08-07T05:54:49.832603
2014-08-14T07:14:35
2014-08-14T07:14:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from move import helpers import codecs import os import os.path import subprocess import json def render_to_html(path, template, md_path=None, json_path=None, **kwargs): doc = None if md_path: doc = helpers.create_document(md_path) ctx = None if json_path: raw = helpers.read_content(helpers.get_content_path(json_path)) ctx = json.loads(raw) try: target_path = os.path.split(os.path.join('output', path))[0] os.mkdir(target_path) except OSError: # 이미 폴더가 존재하는 경우 발생한다. 씹어도 된다. pass with codecs.open(os.path.join('output', path), encoding='utf-8', mode='w') as f: f.write(helpers.render_template(template, md=doc, ctx=ctx, **kwargs)) def copy_static_files(): subprocess.call(['cp', '-r', 'theme/images', 'output/']) subprocess.call(['cp', '-r', 'theme/static', 'output/']) subprocess.call(['cp', '-r', 'theme/CNAME', 'output/'])
UTF-8
Python
false
false
2,014
12,068,858,144,615
25bbac5f3551c9b85506eab19d265f3b7cd44725
497c0a77b40bb144c2a93e836c76211de0aff997
/iosmodules/api/services.py
753245efe7366b746b07bbb2415c789fd70a6b03
[]
no_license
jCarlo0s/djiosnotify
https://github.com/jCarlo0s/djiosnotify
03164753824907581cf2f2070a3390728bec3d6f
bc0561b4d4908af7607059ed5b4692e67eaf1063
refs/heads/master
2015-08-11T18:24:31.681002
2014-05-23T07:16:02
2014-05-23T07:16:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'jCarlo0s' from api.parsers.response_handler import ResponseHandler from django.views.decorators.http import require_http_methods from django.http import HttpResponse from django.conf import settings from django.views.decorators.csrf import csrf_exempt from djiosnotify.models import * from djiosnotify.tools.notifications import NotificationsHandler from api.decorators.decoratos_handler import validate_api_request from api.resources import APNServicesResource, DevicesResource from api.history.history_handler import HistoryHandler import json history = HistoryHandler() @require_http_methods("GET") def get_services(request): """ Get services in the app """ services = APNServicesResource() services_bundle = services.build_bundle(request=request) services_list = services.obj_get_list(services_bundle) bundles = [] for service in services_list: bundle = services.build_bundle(obj=service, request=request) bundles.append( services.full_dehydrate(bundle, for_list=True) ) list_json = services.serialize(None, bundles, "application/json") response = ResponseHandler( status=True, data=json.loads(list_json) ) return response.on_json() @require_http_methods("GET") @validate_api_request(parameters=[ 'service_uuid' ]) def get_devices(request): """ Get devices from service """ service = APNServices.objects.get(uuid=request.GET['service_uuid']) devices = DevicesResource() devices_bundle = devices.build_bundle(request=request) devices_list = devices.obj_get_list(devices_bundle).filter(service=service) bundles = [] for device in devices_list: bundle = devices.build_bundle(obj=device, request=request) bundles.append( devices.full_dehydrate(bundle, for_list=True) ) list_json = devices.serialize(None, bundles, "application/json") response = ResponseHandler( status=True, data=json.loads(list_json) ) return response.on_json() @csrf_exempt @require_http_methods("POST") @validate_api_request(parameters=[ 'service_uuid', 'notification_name', 'notification_message', 'device_uuid' ]) def send_notification(request): """ Send notification to one device """ try: service = APNServices.objects.get(uuid=request.POST['service_uuid']) if 'notification_payload' in request.POST: notification_payload = request.POST['notification_payload'] notification = Notifications.objects.create( apn_service=service, notification_name=request.POST['notification_name'], notification_message=request.POST['notification_message'], notification_payload=notification_payload ) else: notification = Notifications.objects.create( apn_service=service, notification_name=request.POST['notification_name'], notification_message=request.POST['notification_message'], ) device = Devices.objects.get(uuid=request.POST['device_uuid']) notify = NotificationsHandler( service, notification, service.apn_host, settings.NOTIFICATION_PORT ) notify.device_notification(device) # history history.set_to_notification_log(device, notification) response = ResponseHandler( status=True, data=[] ) return response.on_json() except Exception as message: response = ResponseHandler() response.json_response_bad_request(message=message) @csrf_exempt @require_http_methods("POST") @validate_api_request(parameters=[ 'service_uuid', 'device_token' ]) def register_device(request): """ Register device """ try: service = APNServices.objects.get(uuid=request.POST['service_uuid']) device_name = request.POST['device_name'] if 'device_name' in request.POST else None device_id = request.POST['device_id'] if 'device_id' in request.POST else None device = Devices.objects.create( service=service, device_token=request.POST['device_token'], device_name=device_name, device_id=device_id ) response = ResponseHandler( status=True, data={ 'device_uuid': device.uuid, 'device_name': device.device_name, 'device_id': device.device_id } ) return response.on_json() except Exception as message: response = ResponseHandler() return response.json_response_bad_request(message=message) @csrf_exempt @require_http_methods("POST") @validate_api_request(parameters=[ 'device_uuid' ]) def deactivate_device(request): """ Activate/Deactivate device """ try: device = Devices.objects.get(uuid=request.POST['device_uuid']) if device.device_active: device.device_active = False else: device.device_active = True device.save() response = ResponseHandler( status=True, data={ 'device_status': device.device_active } ) return response.on_json() except Exception as message: response = ResponseHandler() response.json_response_bad_request(message=message)
UTF-8
Python
false
false
2,014
3,401,614,135,274
ddf3c6746ceac11440668886d8d62d6002d12406
ee3e1ea10639ac95ed7ed177372b9b74229a35ea
/game/terrain/terrain_gen.py
7714410c84ddf013db23ce30f42b59d6c30c62f3
[]
no_license
gkownack/tc_strategy
https://github.com/gkownack/tc_strategy
74a31cbb5a4b6b0ae0f9051a7fefd4019c3127c7
407e0f6b5beb02fc81e36c0c6a39a857d015d8c9
refs/heads/master
2016-09-05T15:21:07.101891
2014-05-07T22:48:39
2014-05-07T22:48:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import config import random import terrain_classes def get_options(terrain_type): if terrain_type == terrain_classes.Grass: return [terrain_classes.Grass, terrain_classes.Grass, terrain_classes.Grass, terrain_classes.Mountain, terrain_classes.Tree, terrain_classes.Water] else: return [terrain_type, terrain_type, terrain_type] def generate_terrain(width, height, primary=terrain_classes.Grass): terrain = [[terrain_classes.Grass for i in xrange(width)] for i in xrange(height)] for i in xrange(width*height): row = random.randint(1,height-2) col = random.randint(1,width-2) for x in xrange(-1,2): for y in xrange(-1,2): options = [] for j in xrange(-1,2): for k in xrange(-1,2): if row+x+j >= 0 and row+x+j < height and col+y+k >= 0 and col+y+k <width: options.extend(get_options(terrain[row+x+j][col+y+k])) terrain[row+x][col+y] = random.choice(options) if terrain[row+x][col+y] == terrain_classes.Grass: if random.randint(0,1): terrain[row+x][col+y] = primary return terrain
UTF-8
Python
false
false
2,014
2,456,721,306,467
cfb9b2d0f5ff41769cba47416d47364aba8873a5
bf7a29ff732e4b9af2bdd1cc60c5bbd49b87227c
/VBusProtocol.py
885f5e2b2c9c3bf2f38744602a856c116ecc33d8
[]
no_license
ptashek/pyVBus
https://github.com/ptashek/pyVBus
b3f6139f8f7a4ae57d49fb5dfc92f0134de002fc
1d4f9df1b7326b881fb08b50658e48089e72b3f3
refs/heads/master
2016-09-05T17:57:52.798632
2014-10-30T12:57:49
2014-12-07T03:04:24
10,924,188
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Copyright 2013 Lukasz Szmit Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from VBusProtocolException import VBusProtocolException class VBusProtocol(object): version = None packet = None HEADER_LEN = (10, 8) __commands = { 0x0100: 'Answer from module with requested value', 0x0200: 'Write value, acknowledgement required', 0x0300: 'Read value, acknowledgement required', 0x0400: 'Write value, acknowledgement required', 0x0500: 'VBus clearance by master module', 0x0600: 'VBus clearance by slave module', } @property def supported_versions(self): return [1, 2] def __init__(self, packet): self.packet = list(packet) if not self.packet[0] == 0xAA: raise VBusProtocolException('No SYNC byte found') self.version = self.packet[5] / 0x10 if self.version not in self.supported_versions: raise VBusProtocolException('Unsupported protocol version: %s' % self.version) if self.version == 1: offset = 1 length = 8 elif self.version == 2: offset = 1 length = 14 if not self.packet[offset + length] == self.calculate_crc(offset, length): raise VBusProtocolException("Frame header checksum mismatch") def calculate_crc(self, offset, length): crc = 0x7F for i in range(length): crc = (crc - self.packet[offset + i]) & 0x7F return crc def extract_septett(self, offset, length): septett = 0 for i in range(length): if self.packet[offset + i] == 0x80: self.packet[offset + i] &= 0x7F septett |= 1 << i self.packet[offset + length] = septett return septett def inject_septett(self, offset, length): septett = self.packet[offset + length] index = 0 for i in range(length): if not septett & (1 << i) == 0: index = offset + i self.packet[index] |= 0x80 def command_string(self, command_code): try: command_str = self.__commands[command_code] except KeyError: command_str = None return command_str
UTF-8
Python
false
false
2,014
2,748,779,104,272
8bd1104f89fbfe8d81399f7e6f29a7e6087538d7
11844a4b8f96dc49df3ceaff157e1bbddd95c5ba
/bbones/armbone/deadcode/hardware_spi.py
7f9a5b677a8cd9e1b4106d374f6640ee71fc0d73
[]
no_license
cornrn/planepower
https://github.com/cornrn/planepower
b479a061de013b22caf0ee0316017554551d2fcc
c41f38d8f7d540c005394c9baf97b21b357e081d
refs/heads/master
2020-04-07T23:30:12.699403
2014-09-16T15:44:30
2014-09-16T15:44:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import random import string from time import time, sleep import numpy import os import realtime # Currently BROKEN!!! def read_angle_sensors_hardware(): from Adafruit_BBIO.SPI import SPI # For some reason, only the first one of these will # trigger whatever mechanism is using the device files spi1 = SPI(0,0) #/dev/spidev1.0 spi2 = SPI(0,1) #/dev/spidev1.1 spi3 = SPI(1,0) #/dev/spidev2.0 spi4 = SPI(1,1) #/dev/spidev2.1 spis = [spi1, spi2] from numpy import uint8, uint16 spi = spi1 ab = spi.readbytes(2) a = uint16(ab[0]) b = uint16(ab[1]) #print bin(a),bin(b) print "{0:08b}".format(a), "{0:08b}".format(b) realtime.busy_sleep(.02) read_angle_sensors_hardware()
UTF-8
Python
false
false
2,014
19,533,511,268,485
aeaf5de62f47d336a7a994298c1ec503c2b2864f
bc515421c459eeafea3a4be76452c643fbee41af
/script/setup/units.py
5d0f8275576416b7dcd6e50f449aa2c088eb6fe9
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
Kiva-Entertainment/yohk
https://github.com/Kiva-Entertainment/yohk
e43b1de38ee75096f23893214021540c9d2aec36
f10f63b431584e569f32c162fb19d6d745531310
refs/heads/master
2016-08-04T11:50:18.492387
2014-01-27T15:40:05
2014-01-27T15:40:05
14,936,063
6
0
null
false
2014-02-14T02:53:42
2013-12-04T21:16:05
2014-02-14T02:53:42
2014-02-14T02:53:19
15,460
3
0
15
Python
null
null
# Create all units that start on the field # Store in list all units that don't start on field from bge import logic import json from script import unitControl STAGE_DATA_FILENAME = 'stageData.json' # TODO(kgeffen) Remove once better idea align has been hashed out further ALIGNS = ['solarServants', 'martialLegion'] def do(): addActiveUnits() addInactiveUnits() def addActiveUnits(): filepath = logic.expandPath('//stages/') + logic.globalDict['stage'] + '/' + STAGE_DATA_FILENAME # Load all of stage's data from file data = None with open(filepath) as stageDataFile: data = json.load(stageDataFile) # Add active units to field for unit in data['activeUnits']: unitControl.object.add(unit) def addInactiveUnits(): for i in [1, 2]: filepath = logic.expandPath('//parties/') + logic.globalDict['party' + str(i)] + '.json' # Load all of stage's data from file with open(filepath) as partyData: inactiveUnits = json.load(partyData) for unit in inactiveUnits: unit['align'] = ALIGNS[i - 1] unit['team'] = i logic.globalDict['inactiveUnits'].append(unit)
UTF-8
Python
false
false
2,014
3,822,520,932,040
e45692a0333c6be3db87a034790db18b727b920a
79da905a1ebca06533fa9d1baaed8d3147a803cf
/web/src/cashpad/api/handlers.py
6205c9f06e02ef8571d861b5e0ae1ef02d3c2cfe
[]
no_license
dmaulikr/cashpad
https://github.com/dmaulikr/cashpad
c0d836ea4dfa1ab02d091b2494dfa70bc1617d83
4a2d3458145fb1b4ad5e67cbf936e2f458fcb8dd
refs/heads/master
2021-01-22T13:31:44.744562
2011-03-01T19:11:48
2011-03-01T19:11:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import copy import simplejson import datetime import grok from zope.location.location import located from zope.formlib.form import applyData from zope.publisher.interfaces import BadRequest from cashpad.interfaces import IOrder, IItem from cashpad.models import OrderContainer, Order, UserContainer, User, Item class APILayer(grok.IRESTLayer): grok.restskin('api') # class BaseContainerHandler(grok.REST): # grok.baseclass() # grok.layer(APILayer) # FIXME: These should be part of the BaseContainerHandler def validate_proper_contenttype(request): if request.getHeader('Content-Type', '').lower() != 'application/json; charset=utf-8': raise BadRequest('Content is not of type: application/json; charset=utf-8') def parse_json(body): "Return parsed json, otherwise raise BadRequest" try: parsed_body = simplejson.loads(body) except ValueError: raise BadRequest('Content could not be parsed') return parsed_body # XXX PUT requests in grok don't work like you would expect them to? class UserContainerTraverser(grok.Traverser): grok.context(UserContainer) grok.layer(APILayer) def traverse(self, device_id): if self.request.method == 'PUT': validate_proper_contenttype(self.request) # FIXME: This call somehow blocks # body = self.request.bodyStream.read() # user_data = parse_json(body) response = self.request.response user = self.context.get(device_id) if user is None: user = User(name=str(device_id), device_id=str(device_id)) self.context.add(user) response.setStatus('201') else: user.name = str(device_id) response.setStatus('204') # FIXME: user should not be a hardcoded string like this location = located(self.context, self.context.__parent__, self.context.__name__) return location class UserContainerHandler(grok.REST): grok.context(UserContainer) def PUT(self): # XXX We/grok should set the location here. return '' class OrderContainerHandler(grok.REST): grok.context(OrderContainer) def coerce_order_data(self, original_order_data): order_data = copy.deepcopy(original_order_data) # Coerce the created_on timestamp to a datetime order_data['created_on'] = datetime.datetime.fromtimestamp(order_data['created_on']) # Coerce total_price to float order_data['total_price'] = float(order_data['total_price']) return order_data def coerce_item_data(self, original_item_data): item_data = copy.deepcopy(original_item_data) # Coerce unit_price to float item_data['unit_price'] = float(item_data['unit_price']) return item_data def POST(self): validate_proper_contenttype(self.request) order_data = parse_json(self.body) order_data = self.coerce_order_data(order_data) item_list = [] for item_data in order_data['item_list']: item_data = self.coerce_item_data(item_data) item = Item() applyData(item, grok.Fields(IItem), item_data) item_list.append(item) order_data['item_list'] = item_list order = Order() applyData(order, grok.Fields(IOrder), order_data) self.context.add(order) self.response.setHeader('Location', self.url(order)) self.response.setStatus('201') return ''
UTF-8
Python
false
false
2,011
15,384,572,854,508
a326149b39602c4399d23ee280510187cebbf17d
616a450370471ba827746ae905dcfe0d05c637fc
/login.py
90ef2e7c508220c553f73dd6325c843d349924ec
[]
no_license
sivsushruth/Cyberboost
https://github.com/sivsushruth/Cyberboost
4e98fa2dfefcf2cbcf6bd8f0f53134619660acf9
e3364b9f038c06c24441be0f4de1eb416a148404
refs/heads/master
2020-05-16T02:59:14.753854
2013-10-05T19:53:31
2013-10-05T19:53:31
13,309,153
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from threading import Thread from time import sleep from cyberpass import login import cStringIO,StringIO, re import urllib2, os, urllib import os import pycurl import time def login1(): login("","","") if __name__ == "__main__": thread1= Thread(target = login1) thread1.start() thread1.join() print "Done..........."
UTF-8
Python
false
false
2,013
6,588,479,850,676
fd13e8e317bac92dd935abe5cb492607aa4fd69d
6bcafe697aff474a77c6e16461b3240ff032289c
/chapter5/pgm10-izip.py
699e1ce4b50b2b2eeb6c3d62a660f02e45c04c4f
[]
no_license
aslamup/anandhpython
https://github.com/aslamup/anandhpython
fc6089dc353cf7781fbafb8096880d542ccc7b2b
7d7b7a9b61624492455305e9ff8196dd62ebc329
refs/heads/master
2021-01-01T06:12:12.422417
2014-08-28T09:24:38
2014-08-28T09:24:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Implement a function izip that works like itertools.izip. def izip(l1,l2): if len(l1)>len(l2): for i in range(len(l2)): a=l1[i] b=l2[i] yield a,b else: for j in range(len(l1)): a=l1[j] b=l2[j] yield a,b a=izip(["a","b","c"],[1,2,3]) for x,y in list(a): print x,y
UTF-8
Python
false
false
2,014
5,050,881,560,281
c9b602bc2fb7edff5bc60cfb8320184cd2c7ebf5
0b9a28f2aae56a34b73f10b6a936d1e445805883
/2pl-estrito-with-deadlock/src/LockManager.py
4331bc45d827a5c60466c2d7e080f9762a091561
[]
no_license
brodock/ine5616-2pl-estrito
https://github.com/brodock/ine5616-2pl-estrito
155b97a97b4396b441f7ab388284d1ec55535122
5cd21e8d40b3f7c4c30e08572ef8236b7b0752de
refs/heads/master
2021-01-22T01:58:13.238753
2008-07-09T21:10:25
2008-07-09T21:10:25
32,115,546
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time class LockManager(object): def __init__(self, log): ''' The lock table supports the following format: {reg: {Tx: {'S': n} } } or {reg: {Tx: {'X': 1} } } ''' self.lock_table = {} self.log = log def shared_lock(self, tx_id, data_item): '''Acquire shared lock (read) on a data item''' lock_type = self.check_lock(data_item) if lock_type == 'U': self.shared_list(tx_id, data_item) self.log.show_lock('Unlocked -> Shared Lock!', tx_id, data_item) return True elif lock_type == 'S': self.shared_list(tx_id, data_item) self.log.show_lock('Shared Lock -> Shared Lock!', tx_id, data_item) return True else: # lock_type == 'X' self.log.show_lock('Exclusive Lock -> Shared Lock (FALHA)', tx_id, data_item) return False def exclusive_lock(self, tx_id, data_item): '''Acquire exclusive lock (write) on a data item''' lock_type = self.check_lock(data_item) if lock_type == 'U': self.log.show_lock('Unlocked -> Exclusive Lock!', tx_id, data_item) self.exclusive_list(tx_id, data_item) return True elif lock_type == 'S': lock_msg = 'Shared Lock -> Exclusive Lock ' self.log.show_lock(lock_msg + '(TENTANDO)', tx_id, data_item) if self.lock_table[data_item].has_key(tx_id): if len(self.lock_table[data_item]) == 1: # only we have shared lock on it, so upgrade is possible self.log.show_lock(lock_msg + '(CONSEGUIU)!', tx_id, data_item) self.exclusive_list(tx_id, data_item) return True else: self.log.show_lock(lock_msg + '(FALHA: Compartilhando lock)', tx_id, data_item) return False else: self.log.show_lock(lock_msg + '(FALHA: Não possui lock)', tx_id, data_item) return False else: # lock_type == 'X' lock_msg = 'Exclusive Lock -> Exclusive Lock ' if self.lock_table[data_item].has_key(tx_id): if len(self.lock_table[data_item]) == 1: # we already have exclusive lock, so it's ok self.log.show_lock(lock_msg + '(já possui lock exclusivo)', tx_id, data_item) return True self.log.show_lock(lock_msg + '(FALHA: Já existe outro ativo em outra transação)', tx_id, data_item) return False def shared_list(self, tx_id, data_item): '''Add transaction to shared lock list on data item''' if not self.lock_table.has_key(data_item): self.lock_table[data_item] = {} lock_list = self.lock_table[data_item] if lock_list.has_key(tx_id): lock_list[tx_id]['S'] += 1 else: lock_list[tx_id] = {'S': 1} def exclusive_list(self, tx_id, data_item): '''Add transaction to exclusive lock list on data item''' if not self.lock_table.has_key(data_item): self.lock_table[data_item] = {} if not self.lock_table[data_item].has_key(tx_id): self.lock_table[data_item][tx_id] = {'X': 1} self.lock_table[data_item][tx_id]['X'] = 1 def check_lock(self, data_item): ''' Return lock type over a data item: 'U' for unlocked, 'S' for shared and 'X' for exclusive ''' if not self.lock_table.has_key(data_item): return 'U' elif 'X' in self.list_modes(data_item): return 'X' elif 'S' in self.list_modes(data_item): return 'S' else: return 'U' def list_modes(self, data_item): '''List all lock modes for a data item''' values = [] for tx, modes in self.lock_table[data_item].items(): for m in modes: values.append(m) return values def shared_unlock(self, tx_id, data_item): '''Remove one shared lock from a data item''' self.log.show_lock('removendo shared lock', tx_id, data_item) self.lock_table[data_item][tx_id]['S'] -= 1 if self.lock_table[data_item][tx_id]['S'] == 0: del(self.lock_table[data_item][tx_id]['S']) def unlock(self, tx_id, data_item): '''Remove a transaction lock from a data item''' self.log.show_lock('removendo locks', tx_id, data_item) del(self.lock_table[data_item][tx_id]) def unlock_all(self, tx_id): '''Remove all locks held by a transaction''' for data_item, txs in self.lock_table.items(): if tx_id in txs: self.unlock(tx_id, data_item)
UTF-8
Python
false
false
2,008
14,096,082,687,312
a00329c2357f6ba5fce8858cfe38d7bf1d09ff84
26d40aae8ba5c4e34692c070f32ed604894f5fac
/utils/fields.py
b2208fd79c7292da428f10782e75ef12ccc14134
[]
no_license
nanda-ki-shor/Favmeal
https://github.com/nanda-ki-shor/Favmeal
d6124fe27687a839a6a4f4c6cb132dadfe6baf00
25c8b27ce525f218bfd903174a5cc67f1c0ab518
refs/heads/master
2023-03-31T08:22:41.450403
2011-05-23T02:53:33
2011-05-23T02:53:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db.models.fields import CharField class CustomMenuItemsField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 100) CharField.__init__(self, *args, **kwargs)
UTF-8
Python
false
false
2,011
19,628,000,575,136
20e23b74f8bddf8d654fe87ed31373d0a70f6040
923b97be74266e50d40db666e339209f45d1ab7c
/Debugging/fib_bug.py
722e664a4906bbe1d68b106ab7382d5722c86d0b
[]
no_license
juselius/python-tutorials
https://github.com/juselius/python-tutorials
1e6c323c8d2d9cfaa8341bb16c3c44c643356298
4381140e5956b27110297da49e39bf6398255e2a
refs/heads/master
2021-01-21T13:48:58.727515
2013-10-09T06:42:03
2013-10-09T06:42:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def fib2(n = 1000): a, b = 0, 1 result = [] while a < n: result.append(a) a, b = a, a+b return result, a, b if __name__ == '__main__': print fib2(10)
UTF-8
Python
false
false
2,013
2,396,591,790,414
5dbf13a9d96c14673692439e44e46d889d9e4719
99882405db307760a0aa7914872c133105a4bde3
/paper-search.py
1e7ebec42b5b3e0c0d68e900b34583e421b966c5
[]
no_license
efong/household-scripts
https://github.com/efong/household-scripts
b827751a9030819afe45fd2c18d5d7ac1d837ce0
7d921fc6cd20e0dc7e91b331480d15afd68261fd
refs/heads/master
2016-09-10T04:20:53.436712
2014-11-20T20:50:41
2014-11-20T20:50:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import sys import glob import re import subprocess returnos = str(os.getcwd()) print('Please enter a keyword:') ans = str(input()) answer = ans.split(',') print('==================================') ct = 0 matches = list() for filename in glob.glob('*'): for i in range(len(answer)): if re.match('.*{0}.*\.pdf'.format(answer[i]), filename, re.IGNORECASE) and not re.match('.*\.rtf', filename): print('{0} :: {1}'.format(ct, filename)) matches.append(filename) ct += 1 if re.match('.*\.rtf', filename): text = open(filename, 'r').read() pdf = '{0}.pdf'.format(re.sub('_notes.rtf','',filename)) if re.search('.*{0}.*'.format(answer[i]), text, re.IGNORECASE) and pdf not in matches: matches.append(pdf) print('{0} :: {1}'.format(ct, pdf)) ct += 1 else: pass print('==================================') print('{0} matches found'.format(ct)) print('==================================') if ct == 0: sys.exit() print('Please select a file to open.') selection = input() if re.match('.*OPENALL.*', selection): selection = re.sub('OPENALL ', '', selection) newselect = matches[int(selection)] fileparts = newselect.split('_') if re.match('ch.*', fileparts[0]): letter = fileparts[0] else: letter = fileparts[0][0] print(letter) subprocess.call('open {0}*.png'.format(letter), shell=True) elif re.match('exit', selection): print('Exiting ... ') sys.exit() else: selection = int(selection) a = re.sub('.pdf', '', matches[selection]) if re.match('.*\.txt',matches[selection]): subprocess.call('open {0}'.format(matches[selection]), shell=True) else: subprocess.call('open {0}'.format(matches[selection]), shell=True) try: open('{0}_notes.rtf'.format(a),'r') print('Opening notes ...') subprocess.call('open {0}_notes.rtf'.format(a), shell=True) except IOError: print('No notes found for {0}'.format(a)) print('Creating note file ...') open('{0}_notes.rtf'.format(a),'w').write('{\r}') subprocess.call('open {0}_notes.rtf'.format(a), shell=True)
UTF-8
Python
false
false
2,014
970,662,621,656
b5a1e690c30bcf1b30f201a2379a4ea58096b88a
0d259d6d3d41e90c3f5a3d1f1cb2ea77eb416436
/tests/testinstall.py
94d6d02513bce7440e32533763eab9913f1e8639
[ "LGPL-2.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "LGPL-2.1-only", "GPL-2.0-only" ]
non_permissive
turtledb/0install
https://github.com/turtledb/0install
9de091994346d84d7104315f9da8f4d419c1af9d
3ba1d723daf44319c433d0a14aaf5da51c182275
refs/heads/master
2021-01-19T19:32:09.818565
2013-12-19T16:28:39
2013-12-19T16:29:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from basetest import BaseTest import sys, os, subprocess, shlex import unittest sys.path.insert(0, '..') from zeroinstall import support mydir = os.path.dirname(__file__) class Reply: def __init__(self, reply): self.reply = reply def readline(self): return self.reply _template = '''#!/bin/sh exec 0launch %s'%s' "$@" ''' def write_script(stream, interface_uri, main = None, command = None): """Write a shell script to stream that will launch the given program. @param stream: the stream to write to @type stream: file @param interface_uri: the program to launch @type interface_uri: str @param main: the --main argument to pass to 0launch, if any @type main: str | None @param command: the --command argument to pass to 0launch, if any @type command: str | None""" assert "'" not in interface_uri assert "\\" not in interface_uri assert main is None or command is None, "Can't set --main and --command together" if main is not None: option = "--main '%s' " % main.replace("'", "'\\''") elif command is not None: option = "--command '%s' " % command.replace("'", "'\\''") else: option = "" stream.write(support.unicode(_template) % (option, interface_uri)) class TestInstall(BaseTest): maxDiff = None def testHelp(self): out, err = self.run_ocaml([]) assert out.lower().startswith("usage:") assert 'add-feed' in out assert '--version' in out assert err == "Exit status: 1\n", err out2, err = self.run_ocaml(['--help']) assert err == "Exit status: 1\n", err assert out2 == out out, err = self.run_ocaml(['--version']) assert 'Thomas Leonard' in out assert not err, err out, err = self.run_ocaml(['foobar']) assert 'Unknown 0install sub-command' in err, err def testRun(self): out, err = self.run_ocaml(['run']) assert out.lower().startswith("usage:") assert 'URI' in out, out out, err = self.run_ocaml(['run', '--dry-run', 'runnable/Runnable.xml', '--help']) assert not err, err assert 'arg-for-runner' in out, out assert '--help' in out, out def check_man(self, args, expected): out, err = self.run_ocaml(['--dry-run', 'man'] + args) assert '[dry-run] man' in out, (out, err) args = out[len('[dry-run] man '):] man_args = tuple(['man'] + shlex.split(args)) if len(man_args) == 2: arg = man_args[1] if '/tests/' in arg: arg = 'tests/' + man_args[1].rsplit('/tests/', 1)[1] self.assertEqual(expected, arg) else: self.assertEqual(expected, man_args) def testUpdateAlias(self): local_feed = os.path.join(mydir, 'Local.xml') launcher_script = os.path.join(self.config_home, 'my-test-alias') with open(launcher_script, 'w') as stream: write_script(stream, local_feed, None) out, err = self.run_ocaml(['update', 'my-test-alias']) assert err.startswith("Bad interface name 'my-test-alias'.\n(hint: try 'alias:my-test-alias' instead)\n"), err self.assertEqual("", out) def testMan(self): out, err = self.run_ocaml(['man', '--help']) assert out.lower().startswith("usage:") # Wrong number of args: pass-through self.check_man(['git', 'config'], ('man', 'git', 'config')) self.check_man([], ('man',)) local_feed = os.path.realpath(os.path.join(mydir, 'Local.xml')) launcher_script = os.path.join(self.config_home, 'my-test-alias') with open(launcher_script, 'w') as stream: write_script(stream, local_feed, None) self.check_man(['my-test-alias'], 'tests/test-echo.1') self.check_man(['__i_dont_exist'], '__i_dont_exist') self.check_man(['ls'], 'ls') # No man-page binary_feed = os.path.realpath(os.path.join(mydir, 'Command.xml')) launcher_script = os.path.join(self.config_home, 'my-binary-alias') with open(launcher_script, 'w') as stream: write_script(stream, binary_feed, None) out, err = self.run_ocaml(['man', 'my-binary-alias']) assert "Exit status: 1" in err, err assert "No matching manpage was found for 'my-binary-alias'" in out, out with open(os.path.join(self.config_home, 'bad-unicode'), 'wb') as stream: stream.write(bytes([198, 65])) self.check_man(['bad-unicode'], 'bad-unicode') def testAlias(self): local_feed = 'Local.xml' alias_path = os.path.join(mydir, '..', '0alias') child = subprocess.Popen([alias_path, 'local-app', local_feed], stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = child.communicate() assert 'ERROR: "0alias" has been removed; use "0install add" instead' in err, err assert not out, out if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,013
9,079,560,896,528
2442cffaefaff6e1e35fcc7b68cb7fafc8c8de1b
c436ebe21a476b63c374ec13f88b9ce9fa3472a9
/autoprotocol/instruction.py
b8c33df7cd7409bde3130035dfa6017d6d7750e8
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
dotsilverman/autoprotocol-python
https://github.com/dotsilverman/autoprotocol-python
a4313e1c184675aef0c79839785e6dd19a96d6c5
eb2e9c7e47fb8d4046ae59b3dea0c1799bbf5140
refs/heads/master
2021-01-17T17:22:02.684824
2014-12-23T20:46:10
2014-12-23T20:46:10
28,724,981
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json class Instruction(object): def __init__(self, data): super(Instruction, self).__init__() self.data = data self.__dict__.update(data) def json(self): return json.dumps(self.data, indent = 2) class Pipette(Instruction): def __init__(self, groups): super(Pipette, self).__init__({ "op": "pipette", "groups": groups }) @staticmethod def _transferGroup(src, dest, vol): vol = str(vol) + ":microliter" return { "from": src, "to": dest, "volume": vol, } @staticmethod def transfers(srcs, dests, vols): """ Returns a valid list of pipette transfer groups. This can be passed directly to the Pipette constructor as the "groups" argument. srcs - [str] - List of ":ref/:well" to use as the transfer sources dests - [str] - List of ":ref/:well" to use as the transfer destinations vols - [float] - List of volumes in microliters. These should be bare numbers. """ return [{ "transfer": [Pipette._transferGroup(s, d, v) for (s, d, v) in zip(srcs, dests, vols)], }] class Spin(Instruction): def __init__(self, ref, speed, duration): super(Spin, self).__init__({ "op": "spin", "object": ref, "speed": speed, "duration": duration }) class Thermocycle(Instruction): CHANNEL1_DYES = ["FAM","SYBR"] CHANNEL2_DYES = ["VIC","HEX","TET","CALGOLD540"] CHANNEL3_DYES = ["ROX","TXR","CALRED610"] CHANNEL4_DYES = ["CY5","QUASAR670"] CHANNEL5_DYES = ["QUASAR705"] CHANNEL_DYES = [CHANNEL1_DYES, CHANNEL2_DYES, CHANNEL3_DYES, CHANNEL4_DYES, CHANNEL5_DYES] AVAILABLE_DYES = [dye for channel_dye in CHANNEL_DYES for dye in channel_dye] def __init__(self, ref, groups, volume=None, dataref=None, dyes=None, melting=None): if dyes: keys = dyes.keys() if Thermocycle.find_invalid_dyes(keys): dyes = Thermocycle.convert_well_map_to_dye_map(dyes) if bool(dataref) != bool(dyes): raise ValueError("thermocycle instruction supplied `%s` without `%s`" % ("dataref" if bool(dataref) else "dyes", "dyes" if bool(dataref) else "dataref")) if melting and not dyes: raise ValueError("thermocycle instruction supplied `melting` without `dyes`: %s") super(Thermocycle, self).__init__({ "op": "thermocycle", "object": ref, "groups": groups, "dataref": dataref, "volume": volume, "dyes": dyes, "melting": melting }) @staticmethod def find_invalid_dyes(dyes): """ Takes a set or list of dye names and returns the set that are not valid. dyes - [list or set] """ return set(dyes).difference(set(Thermocycle.AVAILABLE_DYES)) @staticmethod def convert_well_map_to_dye_map(well_map): """ Takes a map of wells to the dyes it contains and returns a map of dyes to the list of wells that contain it. well_map - [{well:str}] """ dye_names = reduce(lambda x,y: x.union(y), [set(v) for v in well_map.itervalues()]) if Thermocycle.find_invalid_dyes(dye_names): raise ValueError("thermocycle instruction supplied the following invalid dyes: %s" % ", ".join(Thermocycle.find_invalid_dyes(dye_names))) dye_map = {dye:[] for dye in dye_names} for well,dyes in well_map.iteritems(): for dye in dyes: dye_map[dye] += [well] return dye_map class Incubate(Instruction): WHERE = ["ambient", "warm_37", "cold_4", "cold_20", "cold_80"] def __init__(self, ref, where, duration, shaking = False): if where not in self.WHERE: raise ValueError("specified `where` not contained in: %s" % ", ".join(self.WHERE)) super(Incubate, self).__init__({ "op": "incubate", "object": ref, "where": where, "duration": duration, "shaking": shaking }) class SangerSeq(Instruction): def __init__(self, ref, dataref): super(SangerSeq, self).__init__({ "op": "sangerseq", "object": ref, "dataref": dataref }) class GelSeparate(Instruction): MATRICES = ['agarose(96,2.0%)', 'agarose(48,4.0%)', 'agarose(48,2.0%)', 'agarose(12,1.2%)', 'agarose(8,0.8%)'] LADDERS = ['ladder1', 'ladder2'] def __init__(self, ref, matrix, ladder, duration, dataref): if matrix not in self.MATRICES: raise ValueError("specified `matrix` not contained in: %s" % ", ".join(self.MATRICES)) if ladder not in self.LADDERS: raise ValueError("specified `ladder` not contained in: %s" % ", ".join(self.LADDERS)) super(GelSeparate, self).__init__({ "op": "gel_separate", "ref": ref, "matrix": matrix, "ladder": ladder, "duration": duration, "dataref": dataref }) class Absorbance(Instruction): def __init__(self, ref, wells, wavelength, dataref, flashes = 25): super(Absorbance, self).__init__({ "op": "absorbance", "object": ref, "wells": wells, "wavelength": wavelength, "num_flashes": flashes, "dataref": dataref }) class Fluorescence(Instruction): def __init__(self, ref, wells, excitation, emission, dataref, flashes = 25): super(Fluorescence, self).__init__({ "op": "fluorescence", "object": ref, "wells": wells, "excitation": excitation, "emission": emission, "num_flashes": flashes, "dataref": dataref }) class Seal(Instruction): def __init__(self, ref): super(Seal, self).__init__({ "op": "seal", "object": ref }) class Unseal(Instruction): def __init__(self, ref): super(Unseal, self).__init__({ "op": "unseal", "object": ref }) class Cover(Instruction): def __init__(self, ref, lid): super(Cover, self).__init__({ "op": "cover", "object": ref, "lid": lid }) class Uncover(Instruction): def __init__(self, ref): super(Uncover, self).__init__({ "op": "uncover", "object": ref })
UTF-8
Python
false
false
2,014
3,221,225,516,837
7ae30429c38f5f10d79a823e57b345bc133af72e
1017c7edc562fd58dda5659ce9d1149280f14ef7
/person/views.py
1d73cc04915ec60c97361e96aa83e8cac0f7a8bb
[]
no_license
suhailvs/quiz
https://github.com/suhailvs/quiz
5f3cfc0a28dfbf4b0486b6da6d99785c525e790d
db75c60bb5d4740d4489442c4008e9ad1b47743b
refs/heads/master
2021-03-12T21:33:14.839933
2013-08-27T09:21:53
2013-08-27T09:21:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render # Create your views here. #from django.contrib.auth.decorators import login_required from exam.models import ExamType,ExamSubjects from exam import helper #@login_required def exam(request): ename='JEE Main 2013'#request.GET['examtype'] etype=ExamType.objects.get(name=ename) exam,dur=helper.start_exam(etype) min_left=dur/60 e_subjs=ExamSubjects.objects.filter(examtype = etype) return render(request,'persons/pages/showexam.html', {'exam_id':exam.id,'min_left':min_left, 'subjects':e_subjs,'etype':ename})
UTF-8
Python
false
false
2,013
6,803,228,199,915
d045b2a27a4b8d082439161069267a9e0e2d7d48
8ce2f3e04d1358efe4460a3e547700b19cd54e30
/application/elements.py
4167169a06edfd3b52a5553428b70368ad4837c3
[]
no_license
lee811/console-gui
https://github.com/lee811/console-gui
d23f13f7ff854fa0c1720ff5fd8219352b41c107
4bd8d705783436d2a499d2a79a0a25962eac9f59
refs/heads/master
2021-01-22T09:57:58.517668
2013-09-13T19:10:07
2013-09-13T19:10:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import urwid, sys from subprocess import Popen, PIPE, STDOUT class Menu(): def __init__(self, title=None, question=None, choices=None): if choices is None: self.choices = [] else: self.choices = choices if title is None: self.title = '' else: self.title = title if question is None: self.question = '' else: self.question = question def get_widget(self, callback): title = urwid.Text(('underline', self.title)) question = [title, urwid.Divider(), urwid.Text(self.question), urwid.Divider()] for c in self.choices: button = urwid.Button(c) urwid.connect_signal(button, 'click', callback, c) question.append( urwid.AttrMap(button, None, focus_map='reversed')) return urwid.ListBox(urwid.SimpleFocusListWalker(question)) class QnA(): def __init__(self, title=None, question=None): if title is None: self.title = '' else: self.title = title if question is None: self.question = '' else: self.question = question self.answer = '' def get_widget(self, callback): title = urwid.Text(('underline', self.title)) question = urwid.Text(self.question) answer = urwid.Edit('') button = urwid.Button('Ok') div = urwid.Divider() urwid.connect_signal(button, 'click', callback, self) urwid.connect_signal(answer, 'change', self.__on_change) return urwid.Filler( urwid.Pile([title, div, question, div, answer, div, button]), valign='top') def __on_change(self, edit, new_edit_text): self.answer = new_edit_text class Text(): def __init__(self, title=None, text=None): if title is None: self.title = '' else: self.title = title if text is None: self.text = '' else: try: with open(text) as text_file: self.text = text_file.read() except IOError: self.text = text self.answer = '' def get_widget(self, callback): title = urwid.Text(('underline', self.title)) text = urwid.Text(self.text) button = urwid.Button('Ok') div = urwid.Divider() urwid.connect_signal(button, 'click', callback) return urwid.Filler( urwid.Pile([title, div, text, div, button]), valign='top') class Execute(): def __init__(self, cmd=None): if cmd is None: self.cmd = '' else: self.cmd = cmd def update_widget(self, callback): output = '' process = Popen(self.cmd.split(), stdout=PIPE, stderr=STDOUT) # Poll process for new output until finished while True: nextline = process.stdout.readline() if nextline == '' and process.poll() != None: break output += str(nextline) response = urwid.Text([output, '\n']) callback(widget=urwid.Filler(urwid.Pile([response]))) response = urwid.Text([output, '\n']) done = urwid.Button('Ok') urwid.connect_signal(done, 'click', callback) widget = urwid.Filler(urwid.Pile([response, urwid.AttrMap(done, None, focus_map='reversed')])) callback(widget=widget)
UTF-8
Python
false
false
2,013
17,961,553,246,139
8caa074dcc192bd73ae23d2bfde83e6391885e56
d4f9bde982e434e9ff1b5b2b0997bcd97da6f469
/tracebuf2module/trace_setup.py
bc721fd85bea709f104b7c409e114a481cdee11e
[]
no_license
osop/osop-python-ew
https://github.com/osop/osop-python-ew
d3a31dacf89b4e1eb4242b59afe9e187d7a027e8
915532d6e9fc7a0a27079e30022251567787f866
refs/heads/master
2021-01-17T21:57:28.135951
2013-08-12T14:46:29
2013-08-12T14:46:29
9,330,624
2
1
null
true
2013-08-12T14:46:30
2013-04-09T20:15:39
2013-08-12T14:46:29
2013-08-12T14:46:29
84
null
1
0
C
null
null
from distutils.core import setup, Extension libs = '/path/to/ew/lib/' includes = '/path/to/ew/includes/' module = Extension(name = 'tracebuf2module', sources = ['tracebuf2module.c'], include_dirs = [includes], libraries = [libs], extra_objects = ['%sringwriter.o' % libs, '%sringreader.o' % libs, '%stransport.o' % libs, '%sgetutil.o' % libs, '%skom.o' % libs, '%ssleep_ew.o' % libs, '%slogit.o' % libs, '%stime_ew.o' % libs, '%sswap.o' % libs], extra_compile_args = ['-m32', '-Dlinux', '-D__i386', '-D_LINUX', '-D_INTEL', '-D_USE_SCHED', '-D_USE_PTHREADS', '-D_USE_TERMIOS'], extra_link_args = ['-lm', '-lpthread']) setup (name = 'tracebuf2module', version = '1.0', description = 'Writes/reads a TYPE_TRACEBUF2 message into/from a ring.', ext_modules = [module])
UTF-8
Python
false
false
2,013
19,018,115,225,275
a6458ae902a7a72610b54b0b4b92da10d4e3b2e1
7f35c644382aef173574223b12f49cd1e6eba448
/checks/uptime
8ea01d4d3db1cf8b2659b7fbd831b19df0ff56cd
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause-Views" ]
non_permissive
underlayer/tiletable-agent
https://github.com/underlayer/tiletable-agent
18c05eca76b4d7fc19bb2008414adaab65367793
ef1510c80151dfdb7a047a10cb15ac7581006555
refs/heads/master
2016-08-07T23:15:28.488367
2014-10-11T13:49:08
2014-10-11T13:49:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """ tiletable check uptime checks uptime against defined warn and crit (max days) stdout: events as json: [{"name": "uptime", "perfdata": 120}] usage: ./uptime warn crit """ """ Copyright: 2014 Nils Bartels <github.com/brtz> License: FreeBSD License """ import re from subprocess import Popen, PIPE import sys import platform import json warn = float(sys.argv[1]) if len(sys.argv) > 1 else 2 crit = float(sys.argv[2]) if len(sys.argv) > 2 else 3 events = [] # osx if platform.system() == 'Darwin': uptime_command = ['uptime'] # fallback to linux else: uptime_command = ['uptime'] try: p = Popen(uptime_command, stdout=PIPE) except OSError as e: exit(3) output = p.communicate()[0] fields = output.split("up") uptime = int(fields[1].split(" ")[1]) event = {} event['name'] = 'uptime' event['perfdata'] = uptime event['severity'] = 0 if uptime > warn: event['severity'] = 1 if uptime > crit: event['severity'] = 2 events.append(event) # print uptime sys.stdout.write(json.dumps(events))
UTF-8
Python
false
false
2,014
10,909,216,965,717
afb6e3a264c2e9d38a99120753304419f08602c4
a1c0685a80e9a581fec9a88ff7655c639af6ffd6
/9.py
6a625bc3b32bbdb07d60458f3b0e0cde0828e6dd
[]
no_license
fguan/proj-euler
https://github.com/fguan/proj-euler
734c8278b37949f979cdb197b80f95adc529a754
2486d6e5611326aa3f5385989a6e29bc05d71265
refs/heads/master
2020-06-06T10:16:31.361733
2014-09-03T05:11:55
2014-09-03T05:11:55
1,130,655
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python """ https://projecteuler.net/problem=9 """ for a in range(1, 1000): for b in range(1, 1000): c = 1000-a-b if c > 0: if c*c == a*a + b*b: print(a*b*c)
UTF-8
Python
false
false
2,014
12,532,714,614,898
8ca36b454b2ff64332727f1f090c946d52bc9fb2
111789e330216caac5ecc5a4c709ad261c534d82
/Attic_from_svn_import/easyshop.mpay24/easyshop/mpay24/browser/payment_response.py
26937681499fe78aa725971b75ebc3a203bcc9a4
[]
no_license
Easyshop/Easyshop
https://github.com/Easyshop/Easyshop
b0b328d0016f6a1a800007db055331e26c0bbc05
26e9a40f8e25684a1c156ac1cea08e6796e4c2d7
refs/heads/master
2021-01-19T05:53:54.872702
2010-06-30T17:30:17
2010-06-30T17:30:17
749,559
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from AccessControl.SecurityManagement import getSecurityManager, \ newSecurityManager, setSecurityManager from AccessControl.User import UnrestrictedUser from Products.Five import BrowserView from Products.CMFCore.utils import getToolByName from Products.CMFPlone.utils import log from easyshop.mpay24.config import REDIR_COOKIE_NAME from easyshop.core.interfaces import IOrderManagement, \ ICartManagement, \ IStockManagement class PaymentConfirmation(BrowserView): def __call__(self): om = IOrderManagement(self.context) tid = self.request.get('TID','') order = getattr(om.orders,tid,None) log("\n%s\n%s\n%s" % (order, tid, self.request.get('STATUS'))) if order and self.request.get('STATUS') in ['RESERVED','BILLED']: # Set order to payed (Mails will be sent) wftool = getToolByName(self.context, "portal_workflow") # We need a new security manager here, because this transaction # should usually just be allowed by a Manager except here. old_sm = getSecurityManager() tmp_user = UnrestrictedUser( old_sm.getUser().getId(), '', ['Manager'], '' ) portal = getToolByName(self.context, 'portal_url').getPortalObject() tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) try: # set to pending (send emails) wftool.doActionFor(order, "submit") # set to payed wftool.doActionFor(order, "pay_not_sent") except Exception, msg: self.status = msg # Reset security manager setSecurityManager(old_sm) # delete redirection cookie self.request.response.expireCookie(REDIR_COOKIE_NAME, path='/') return "OK: received"
UTF-8
Python
false
false
2,010
738,734,409,424
65ac2d45605da59a1d15c6c9bdb39f9c73ce5a81
e23d610d2320b3c64294441eeaed6604d75b9ac7
/builddist.py
9cbaee59c75fde84f30fe687ca4648a8c55a69b5
[]
no_license
JJewell2k/Jeneric
https://github.com/JJewell2k/Jeneric
2b56a00a2e8fd13a37e928e52abec32944a3f06e
246309d3125853de0f5fa05f4180832b31dce62f
refs/heads/master
2023-03-16T01:43:07.796651
2012-05-02T13:58:40
2012-05-02T13:58:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# builddist # Build create a jeneric instance # - compile JS files into a bundle # - minify minifiable js # - append JS that cannot be minified # - append base system distro files # - update build number # - change offline manifest # remember to include a stylesheet and some JS files from the below, also in manifest import sys, urllib2, urllib, time, os.path, string, os, commands COMPILE_FILES = [ "ratbird/DataRequestor.js", "ratbird/json2.js", "os/ierange-m2.js", # and this "os/csshover3.js", # TODO: make it not load by default - IE sucks "os/excanvas.js", # fuck IE "os/fauxconsole.js", # this too "os/md5.js", "ratbird/jsdefs.js", "ratbird/jsparse.js", "ratbird/objj.js", "ratbird/jsexec.js", "os/gears_init.js", "os/jsobject.js", "os/Orbited.js", "os/xmlsax.js", "os/jsdom2.js", "os/jsdom.js", "os/canvaswrapper.js", "os/orbited_init.js", "os/stomp.js", "os/eosinit.js" ] DONTCOMPILE_FILES = [ "os/fixed.js" ] BASE_SOURCES = [ "os/readonly.jn", "os/anarchic.jn", "os/ramstore.jn", "os/st.jn", "os/st_acl.jn", "os/tmpstore.jn", "os/ic.jn", "os/totinit.jn", # "os/st.jn", "os/terminal.jn" ] MANIFEST_FILES = [ "os/fauxconsole.css", "os/jnext/jnext.js", "os/jnext/sockets.js", "os/CFInstall.min.js", "/eos.html" ] MANIFEST_PATH = "os/jeneric.manifest" url = "http://closure-compiler.appspot.com/compile"; FILE_SPLIT_MARK = "// -*- FILE SPLIT HERE -*-" def fbundle( lFiles, postlen = 0): b = ""; lp = [] tp = 0 tot = 0 for f in lFiles: print " Bundling", f, "...", tb = open(f).read(); print int(len(tb)/1024), "kb" i = 1 for fpart in tb.split(FILE_SPLIT_MARK): print " part", i, int(len(fpart)/1024), "kb" tb = fpart if postlen: tp += len(tb) if tp >= postlen: tp -= len(tb) lp.append(b) b = tb print "Created POST bundle of", int(tp/1024), "kb" tot += tp tp = len(tb) else: b += tb else: b += tb tot += len(tb) i +=1 if postlen: lp.append(b) tot += len(b) print "Created POST bundle of", int(tp/1024), "kb" print "Total: ", int(tot/1024), "kb" if postlen: return lp else: return b def closure_local(data): if os.path.isfile("compiler.jar"): print "Found google closure compiler" d = string.join(data, "\n"); print "Compiling... in=", int(len(d)/1024), "kb", file("/tmp/clos.tmp.js", "w").write(d) print commands.getoutput("java -jar compiler.jar --compilation_level SIMPLE_OPTIMIZATIONS --js /tmp/clos.tmp.js --js_output_file /tmp/clos.tmp.c.js") out = file("/tmp/clos.tmp.c.js").read(); print int(len(out)/1024), "kb" os.remove("/tmp/clos.tmp.js") os.remove("/tmp/clos.tmp.c.js") return out return None def fcompile(data): cdata = "" print "Compressing using Google Closure: " ret = closure_local(data) if ret: return ret print "WARNING! Local installation of google closure compiler not found, using API" for d in data: print " <in:", int(len(d)/1024), "kb, out:", params = urllib.urlencode({ 'js_code': d, # 'compilation_level': "WHITESPACE_ONLY", 'compilation_level': "SIMPLE_OPTIMIZATIONS", "output_format": "text", "output_info": "compiled_code" }) r = urllib.urlopen(url, params) gout = r.read() if len(gout) < 1024: print gout sys.exit(-1); if len(gout) == 0: print "FAILED. Retreiving info:" print "----------------" params = urllib.urlencode({ 'js_code': d, # 'compilation_level': "WHITESPACE_ONLY", 'compilation_level': "SIMPLE_OPTIMIZATIONS", "output_format": "text", "output_info": "errors" }) r = urllib.urlopen(url, params) print r.read() print "----------------" sys.exit(-1) cdata += gout print int(len(gout)/1024), "kb>" print "done" print "Total compressed:", int(len(cdata)/1024), "kb" return cdata def fsource(lFiles): print "Bundling base system distribution objects...", i=0 rdata = "\nBUNDLED_FILES={" for f in lFiles: rdata += '"%s": ' % f d = open(f).read().replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n\\\n") if i < (len(lFiles) - 1): rdata += "'%s'," % d else: rdata += "'%s'" % d i+=1 rdata += "};" print i, "files of length", int(len(rdata)/1024), "kb" return rdata def builddist(): ts = time.time(); compiled = fcompile(fbundle(COMPILE_FILES, 100000)); # google max is 200kb bundled = fbundle(DONTCOMPILE_FILES); sources = fsource(BASE_SOURCES); print "\n\nTotal jeneric size is: ", int((len(compiled) + len(bundled) + len(sources))/1024), "kb" try: buildver = int(open(MANIFEST_PATH).read().split("\n")[1][8:]) except: buildver = 0 buildver +=1 fd = open("os/jeneric.js", "w") fd.write("JENERIC_BUILD=%s;\n" % str(buildver)) fd.write(compiled); fd.write("\n"); fd.write(bundled); fd.write("\n"); fd.write(sources); fd.close() # and finally write manifest! print "Build version", buildver print "Writing manifest... ", len(MANIFEST_FILES), "files" build_str = "# BUILD "+str(buildver) MANIFEST = "CACHE MANIFEST\n%s\n" % build_str for f in MANIFEST_FILES: MANIFEST += f+"\n" MANIFEST += "\nFALLBACK:\n/ eos.html\n/index.php eos.html\n/index.html eos.html\n" file(MANIFEST_PATH, 'w').write(MANIFEST) print "build time: ", int(time.time() - ts), "s" if __name__ == '__main__': builddist()
UTF-8
Python
false
false
2,012
11,201,274,721,913
6e799961ab87bef04e81c5fa2b5a37cf7fcf68e9
44ab707b75d26bbb4cbcf3e8862a9b8f69b97c47
/articles/admin.py
138cdfc0258cca35a122c7e3163570855e2e7430
[]
no_license
katbailey/kango
https://github.com/katbailey/kango
d88d5027aef3aa73ed35fb4383bcc78e0c561229
730bb3bcee7130c3c880205d65789d36dc18d910
refs/heads/master
2019-02-24T23:57:17.198336
2011-01-14T05:46:34
2011-01-14T05:46:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from katblog.articles.models import Post from django.contrib import admin # New code will go here later on class PostAdmin(admin.ModelAdmin): list_display = ('author', 'pub_date', 'title') list_filter = ('author', 'pub_date') admin.site.register(Post, PostAdmin)
UTF-8
Python
false
false
2,011
9,234,179,731,241
6815e38a48cd343948aee1a210c12fd4a4b3ada9
1e6e2736a3db6766eff427a2ae85a391d31a2e3e
/tp.py
8e82bc941cef443b90fe349c727e6d385d26e8bb
[ "GPL-1.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-public-domain" ]
non_permissive
MostAwesomeDude/madsnippets
https://github.com/MostAwesomeDude/madsnippets
2a3e91461dc97625fde93054366ebcabfe942b8c
d4e0c74ee7c9f6256706d60347bec94d284fa428
refs/heads/master
2021-01-13T02:15:02.805380
2014-05-22T03:43:35
2014-05-22T03:43:35
284,488
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from itertools import product class Box: def __init__(self, (x, y)): self.x = x self.y = y def __repr__(self): return "<Box (%d, %d)>" % (self.x, self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def loc(self): return self.x, self.y def left(self): return self.x - 1, self.y def right(self): return self.x + 1, self.y def up(self): return self.x, self.y - 1 def down(self): return self.x, self.y + 1 def neighbors(self): return self.left(), self.right(), self.up(), self.down() grid = {t: Box(t) for t in product(range(5), range(6))} del grid[2, 0] del grid[0, 3] del grid[4, 3] del grid[0, 4] del grid[4, 4] del grid[0, 5] del grid[1, 5] del grid[3, 5] del grid[4, 5] def step(w, g1, g2): if w.left() in grid: if w.left() not in (g1.loc(), g2.loc(), g2.right()): wn = Box(w.left()) g1n = Box(g1.left()) if g1.left() in grid else g1 g2n = Box(g2.right()) if g2.right() in grid else g2 yield wn, g1n, g2n if w.right() in grid: if w.right() not in (g1.loc(), g2.loc(), g2.left()): wn = Box(w.right()) g1n = Box(g1.right()) if g1.right() in grid else g1 g2n = Box(g2.left()) if g2.left() in grid else g2 yield wn, g1n, g2n if w.up() in grid: if w.up() not in (g1.loc(), g2.loc(), g2.down()): wn = Box(w.up()) g1n = Box(g1.up()) if g1.up() in grid else g1 g2n = Box(g2.down()) if g2.down() in grid else g2 yield wn, g1n, g2n if w.down() in grid: if w.down() not in (g1.loc(), g2.loc(), g2.up()): wn = Box(w.down()) g1n = Box(g1.down()) if g1.down() in grid else g1 g2n = Box(g2.up()) if g2.up() in grid else g2 yield wn, g1n, g2n wolf = Box((2, 3)) golem1 = Box((2, 5)) golem2 = Box((2, 1)) def win(g1, g2): return ((g1.loc() == (1, 1) and g2.loc() == (3, 1)) or (g1.loc() == (3, 1) and g2.loc() == (1, 1))) stacks = [[(wolf, golem1, golem2)]] count = 0 winner = None while winner is None: count += 1 print "Considering moveset", count newstacks = [] for stack in stacks: for move in step(*stack[-1]): s = list(stack) if move in s: # print "Dropping recursive stack" continue s.append(move) if win(move[1], move[2]): winner = s break newstacks.append(s) stacks = newstacks def d(b1, b2): if b1.x < b2.x: return "left" elif b1.x > b2.x: return "right" elif b1.y < b2.y: return "up" else: return "down" print "Found a winner!" print "Winner:", winner previous = None for i, entry in enumerate(winner): if previous: print "Move", i, ":", entry, d(entry[0], previous[0]) else: print "Move", i, ":", entry previous = entry
UTF-8
Python
false
false
2,014
13,907,104,127,485
77b41a75a7bf67ea95fbf7b3848908e8d6539bb5
87e1eac25d8a89cc5f694a53f73433b75dea5597
/tests/run_step.py
54b7c3a4457f10ed8c0da463b1acdf914b268a5a
[ "MIT" ]
permissive
soofaloofa-zz/gae_bingo
https://github.com/soofaloofa-zz/gae_bingo
c85473fe28acc0d80406cbb5c093e6f721d4ce43
f5285b9ad17dde72991fe123f23095520a554cbf
refs/heads/master
2021-01-16T19:05:25.994691
2013-08-08T01:50:25
2013-08-08T01:50:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import copy import os # use json in Python 2.7, fallback to simplejson for Python 2.5 try: import json except ImportError: import simplejson as json from google.appengine.ext.webapp import RequestHandler from google.appengine.api import memcache from gae_bingo.api import ControlExperiment from gae_bingo.cache import BingoCache, BingoIdentityCache from gae_bingo.gae_bingo import ab_test, bingo, choose_alternative, create_redirect_url from gae_bingo.gae_bingo import ExperimentController import gae_bingo.identity from gae_bingo.models import _GAEBingoExperiment, ConversionTypes import gae_bingo.persist import gae_bingo.instance_cache # See gae_bingo/tests/run_tests.py for the full explanation/sequence of these tests # TODO(kamens): this whole file and ad-hoc test process should be replaced w/ # our real unit testing or end-to-end testing framework. class RunStep(RequestHandler): def get(self): if not os.environ["SERVER_SOFTWARE"].startswith('Development'): return step = self.request.get("step") v = None if step == "delete_all": v = self.delete_all_experiments() elif step == "get_identity": v = self.get_identity() elif step == "refresh_identity_record": v = self.refresh_identity_record() elif step == "participate_in_monkeys": v = self.participate_in_monkeys() elif step == "participate_in_gorillas": v = self.participate_in_gorillas() elif step == "participate_in_skunks": v = self.participate_in_skunks() elif step == "participate_in_chimpanzees": v = self.participate_in_chimpanzees() elif step == "participate_in_crocodiles": v = self.participate_in_crocodiles() elif step == "participate_in_hippos": v = self.participate_in_hippos() elif step == "participate_in_doppleganger_on_new_instance": v = self.participate_in_doppleganger_on_new_instance() elif step == "count_doppleganger_experiments": v = self.count_doppleganger_experiments() elif step == "add_conversions": v = self.add_conversions() elif step == "get_experiments": v = self.get_experiments() elif step == "get_archived_experiments": v = self.get_experiments(archives=True) elif step == "print_cache": v = self.print_cache() elif step == "convert_in": v = self.convert_in() elif step == "count_participants_in": v = self.count_participants_in() elif step == "count_conversions_in": v = self.count_conversions_in() elif step == "count_experiments": v = self.count_experiments() elif step == "end_and_choose": v = self.end_and_choose() elif step == "persist": v = self.persist() elif step == "flush_hippo_counts_memcache": v = self.flush_hippo_counts_memcache() elif step == "flush_bingo_cache": v = self.flush_bingo_cache() elif step == "flush_all_cache": v = self.flush_all_cache() elif step == "create_monkeys_redirect_url": v = self.create_monkeys_redirect_url() elif step == "create_chimps_redirect_url": v = self.create_chimps_redirect_url() elif step == "archive_monkeys": v = self.archive_monkeys() self.response.out.write(json.dumps(v)) def delete_all_experiments(self): bingo_cache = BingoCache.get() for experiment_name in bingo_cache.experiments.keys(): bingo_cache.delete_experiment_and_alternatives( bingo_cache.get_experiment(experiment_name)) bingo_cache_archives = BingoCache.load_from_datastore(archives=True) for experiment_name in bingo_cache_archives.experiments.keys(): bingo_cache_archives.delete_experiment_and_alternatives( bingo_cache_archives.get_experiment(experiment_name)) return (len(bingo_cache.experiments) + len(bingo_cache_archives.experiments)) def get_identity(self): return gae_bingo.identity.identity() def refresh_identity_record(self): BingoIdentityCache.get().load_from_datastore() return True def participate_in_monkeys(self): return ab_test("monkeys") def archive_monkeys(self): bingo_cache = BingoCache.get() bingo_cache.archive_experiment_and_alternatives(bingo_cache.get_experiment("monkeys")) return True def participate_in_doppleganger_on_new_instance(self): """Simulate participating in a new experiment on a "new" instance. This test works by loading memcache with a copy of all gae/bingo experiments before the doppleganger test exists. After the doppleganger test has been created once, all future calls to this function simulate being run on machines that haven't yet cleared their instance cache and loaded the newly created doppleganger yet. We do this by replacing the instance cache'd state of BingoCache with the deep copy that we made before doppleganger was created. A correctly functioning test will still only create one copy of the experiment even though multiple clients attempted to create a new experiment. """ # First, make a deep copy of the current state of bingo's experiments bingo_clone = memcache.get("bingo_clone") if not bingo_clone: # Set the clone by copying the current bingo cache state memcache.set("bingo_clone", copy.deepcopy(BingoCache.get())) else: # Set the current bingo cache state to the cloned state gae_bingo.instance_cache.set(BingoCache.CACHE_KEY, bingo_clone) return ab_test("doppleganger") def count_doppleganger_experiments(self): experiments = _GAEBingoExperiment.all().run() return len([e for e in experiments if e.name == "doppleganger"]) def participate_in_gorillas(self): return ab_test("gorillas", ["a", "b", "c"]) def participate_in_chimpanzees(self): # Multiple conversions test return ab_test("chimpanzees", conversion_name=["chimps_conversion_1", "chimps_conversion_2"]) def participate_in_skunks(self): # Too many alternatives return ab_test("skunks", ["a", "b", "c", "d", "e"]) def participate_in_crocodiles(self): # Weighted test return ab_test("crocodiles", {"a": 100, "b": 200, "c": 400}) def participate_in_hippos(self): # Multiple conversions test return ab_test("hippos", conversion_name=["hippos_binary", "hippos_counting"], conversion_type=[ConversionTypes.Binary, ConversionTypes.Counting]) # Should be called after participate_in_hippos to test adding # conversions mid-experiment def add_conversions(self): return ab_test("hippos", conversion_name=["hippos_binary", "hippos_counting", "rhinos_counting"], conversion_type=[ConversionTypes.Binary, ConversionTypes.Counting, ConversionTypes.Counting]) def get_experiments(self, archives=False): if archives: bingo_cache = BingoCache.load_from_datastore(archives=True) else: bingo_cache = BingoCache.get() return str(bingo_cache.experiments) def try_this_bad(self): cache = BingoCache.get() return len(cache.get_experiment_names_by_canonical_name("hippos")) def convert_in(self): bingo(self.request.get("conversion_name")) return True def create_monkeys_redirect_url(self): return create_redirect_url("/gae_bingo", "monkeys") def create_chimps_redirect_url(self): return create_redirect_url("/gae_bingo", ["chimps_conversion_1", "chimps_conversion_2"]) def end_and_choose(self): with ExperimentController() as dummy: bingo_cache = BingoCache.get() choose_alternative( self.request.get("canonical_name"), int(self.request.get("alternative_number"))) def count_participants_in(self): return sum( map(lambda alternative: alternative.latest_participants_count(), BingoCache.get().get_alternatives(self.request.get("experiment_name")) ) ) def count_conversions_in(self): dict_conversions = {} for alternative in BingoCache.get().get_alternatives(self.request.get("experiment_name")): dict_conversions[alternative.content] = alternative.latest_conversions_count() return dict_conversions def count_experiments(self): return len(BingoCache.get().experiments) def persist(self): gae_bingo.persist.persist_task() return True def flush_hippo_counts_memcache(self): experiments, alternative_lists = BingoCache.get().experiments_and_alternatives_from_canonical_name("hippos") for experiment in experiments: experiment.reset_counters() return True def flush_bingo_cache(self): memcache.delete(BingoCache.CACHE_KEY) gae_bingo.instance_cache.delete(BingoCache.CACHE_KEY) return True def flush_all_cache(self): memcache.flush_all() gae_bingo.instance_cache.flush() return True
UTF-8
Python
false
false
2,013
6,081,673,732,597
7df2bfc5f6ae80340ce5a534cd38d7d440e64586
0c82f4056cc4d131a28300f5632c4f6246f039a7
/wwwjobby/userprofile/models.py
8ada2222b811520b09a6af2dbcd079fffcb919d3
[]
no_license
TimSijstermans/Jobby
https://github.com/TimSijstermans/Jobby
e37a66163f954933c38b21baf9497b8d8127f6e6
b5f14d8810b6115633f392f5123c1ef8282909ae
refs/heads/master
2021-01-22T07:11:23.686040
2014-05-15T11:13:35
2014-05-15T11:13:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models # Create your models here. class Usertype(models.Model): typename = models.CharField("Type titel",max_length=200) def __unicode__(self): return self.typename class User(models.Model): userType = models.ForeignKey(Usertype) userType.verbose_name = "Soort gebruiker" username = models.CharField("Gebruikers naam", max_length=200) password = models.CharField("Wachtwoord", max_length=200) firstname = models.CharField("Voornaam", max_length=200) middlename = models.CharField("Tussenvoegsel", max_length=200, blank=True) lastname = models.CharField("Achternaam", max_length=200) def __unicode__(self): return self.username class CV(models.Model): user = models.ForeignKey(User) summary = models.TextField() def __unicode__(self): return self.user class Vacancy(models.Model): user = models.ForeignKey(User) summary = models.TextField() class Match(models.Model): user = models.ForeignKey(User) cv = models.ForeignKey(CV) vacancy = models.ForeignKey(Vacancy)
UTF-8
Python
false
false
2,014
1,288,490,191,091
b6b05c975d8e1f4b8d924a8f650c782d7e8c7799
29048456a7c3c3bb0f06a9a48b65b04fd3ec8509
/check_elasticsearch
e5c4c833dfb17274f166d6fb0d0731f25e3b5b46
[ "BSD-2-Clause" ]
permissive
saj/nagios-plugin-elasticsearch
https://github.com/saj/nagios-plugin-elasticsearch
fbbd2d67bec027896f0ad478490e51aaf549ec76
372fdd7c1fd9070fa20727846ea0e39ce767e824
refs/heads/master
2015-08-04T05:13:46.795871
2013-05-07T10:20:59
2013-05-07T10:20:59
6,291,833
3
2
null
false
2015-03-19T14:08:06
2012-10-19T08:21:04
2014-12-05T05:16:30
2013-05-07T10:23:12
133
8
10
5
Python
null
null
#!/usr/bin/python from nagioscheck import NagiosCheck, UsageError from nagioscheck import PerformanceMetric, Status import urllib2 try: import json except ImportError: import simplejson as json HEALTH = {'red': 0, 'yellow': 1, 'green': 2} RED = HEALTH['red'] YELLOW = HEALTH['yellow'] GREEN = HEALTH['green'] HEALTH_MAP = {0: 'critical', 1: 'warning', 2: 'ok'} SHARD_STATE = {'UNASSIGNED': 1, 'INITIALIZING': 2, 'STARTED': 3, 'RELOCATING': 4} class ESShard(object): def __init__(self, state): self.state = state class ESIndex(object): def __init__(self, name, n_shards, n_replicas): self.name = name self.n_shards = n_shards self.n_replicas = n_replicas class ESNode(object): def __init__(self, name=None, esid=None, attributes={}): self.esid = esid self.name = name self.attributes = attributes class ElasticSearchCheck(NagiosCheck): version = '0.2.0' def __init__(self): NagiosCheck.__init__(self) self.health = HEALTH['green'] self.add_option('f', 'failure-domain', 'failure_domain', "A " "comma-separated list of ElasticSearch " "attributes that make up your cluster's " "failure domain. This should be the same list " "of attributes that ElasticSearch's location-" "aware shard allocator has been configured " "with. If this option is supplied, additional " "checks are carried out to ensure that primary " "and replica shards are not stored in the same " "failure domain.") self.add_option('H', 'host', 'host', "Hostname or network " "address to probe. The ElasticSearch API " "should be listening here. Defaults to " "'localhost'.") self.add_option('m', 'master-nodes', 'master_nodes', "Issue a " "warning if the number of master-eligible " "nodes in the cluster drops below this " "number. By default, do not monitor the " "number of nodes in the cluster.") self.add_option('p', 'port', 'port', "TCP port to probe. " "The ElasticSearch API should be listening " "here. Defaults to 9200.") def check(self, opts, args): host = opts.host or "localhost" port = int(opts.port or '9200') failure_domain = [] if (isinstance(opts.failure_domain, str) and len(opts.failure_domain) > 0): failure_domain.extend(opts.failure_domain.split(",")) if opts.master_nodes is not None: try: if int(opts.master_nodes) < 1: raise ValueError("'master_nodes' must be greater " "than zero") except ValueError: raise UsageError("Argument to -m/--master-nodes must " "be a natural number") # # Data retrieval # # Request cluster 'health'. /_cluster/health is like a tl;dr # for /_cluster/state (see below). There is very little useful # information here. We are primarily interested in ES' cluster # 'health colour': a little rating ES gives itself to describe # how much pain it is in. es_health = get_json(r'http://%s:%d/_cluster/health' % (host, port)) their_health = HEALTH[es_health['status'].lower()] # Request cluster 'state'. This be where all the meat at, yo. # Here, we can see a list of all nodes, indexes, and shards in # the cluster. This response will also contain a map detailing # where all shards are living at this point in time. es_state = get_json(r'http://%s:%d/_cluster/state' % (host, port)) # Request a bunch of useful numbers that we export as perfdata. # Details like the number of get, search, and indexing # operations come from here. es_stats = get_json(r'http://%s:%d/_cluster/nodes/_local/' 'stats?all=true' % (host, port)) myid = es_stats['nodes'].keys()[0] n_nodes = es_health['number_of_nodes'] n_dnodes = es_health['number_of_data_nodes'] # Unlike n_dnodes (the number of data nodes), we must compute # the number of master-eligible nodes ourselves. n_mnodes = 0 for esid in es_state['nodes']: master_elig = True # ES will never elect 'client' nodes as masters. try: master_elig = not (booleanise( es_state['nodes'][esid]['attributes'] ['client'])) except KeyError, e: if e.args[0] != 'client': raise try: master_elig = (booleanise( es_state['nodes'][esid]['attributes'] ['master'])) except KeyError, e: if e.args[0] != 'master': raise if master_elig: n_mnodes += 1 n_active_shards = es_health['active_shards'] n_relocating_shards = es_health['relocating_shards'] n_initialising_shards = es_health['initializing_shards'] n_unassigned_shards = es_health['unassigned_shards'] n_shards = (n_active_shards + n_relocating_shards + n_initialising_shards + n_unassigned_shards) # # Map construction # # String all the dumb ES* objects into a bunch of transitive # associations so that we may make some useful assertions about # them. esid_node_map = {} # ESID : <ESNode> index_primary_map = {} # <ESIndex> : { 0: <ESShard>, ... } name_index_map = {} # 'bar' : <ESIndex> name_node_map = {} # 'foo' : <ESNode> node_esid_map = {} # <ESNode> : ESID node_location_map = {} # <ESNode> : ('mars',) node_shard_map = {} # <ESNode> : [ <ESShard>, ... ] primary_replica_map = {} # <ESShard> : [ <ESShard>, ... ] shard_location_map = {} # <ESShard> : ('mars',) # Build node maps: # # - esid_node_map # - name_node_map # - node_esid_map # - node_location_map (data nodes only) # nodes = es_state['nodes'] for n in nodes: name = nodes[n]['name'] attrs = nodes[n]['attributes'] node = ESNode(name, n, attrs) name_node_map[name] = node esid_node_map[n] = node node_esid_map[node] = n node_shard_map[node] = [] if len(failure_domain) > 0: node_location_map[node] = tuple() try: node_location_map[node] = ( tuple(map(lambda a: attrs[a], failure_domain))) except KeyError, e: # Nodes that do not store shards (e.g.: 'client' # nodes) cannot be expected to have been configured # with locational attributes. if 'data' not in attrs or booleanise(attrs['data']): missing_attr = e.args[0] raise Status('warning', ("Node '%s' missing location " "attribute '%s'" % (name, missing_attr),)) # Build index maps: # # - name_index_map # indices = es_state['metadata']['indices'] for i in indices: idx_stns = indices[i]['settings'] idx = ESIndex(i, int(idx_stns['index.number_of_shards']), int(idx_stns['index.number_of_replicas'])) name_index_map[i] = idx # Build shard maps: # # - index_primary_map # - node_shard_map # - primary_replica_map # - shard_location_map # for i in name_index_map: idx = name_index_map[i] if idx not in index_primary_map: index_primary_map[idx] = dict(map(lambda n: (n, None), range(idx.n_shards))) idx_shards = (es_state['routing_table']['indices'] [i]['shards']) for d in idx_shards: primary = None replicas = [] for s in idx_shards[d]: shard = ESShard(SHARD_STATE[s['state'].upper()]) if s['primary']: primary = shard else: replicas.append(shard) if s['state'] != 'UNASSIGNED': node = esid_node_map[s['node']] node_shard_map[node].append(shard) if len(failure_domain) > 0: loc = node_location_map[esid_node_map[s['node']]] shard_location_map[shard] = loc index_primary_map[idx][int(d)] = primary if primary is not None: primary_replica_map[primary] = replicas # # Perfdata # perfdata = [] def dict2perfdata(base, metrics): for metric in metrics: if len(metric) == 2: label, path = metric unit = "" elif len(metric) > 2: label, path, unit = metric else: continue keys = path.split(".") value = base for key in keys: if value is None: break try: value = value[key] except KeyError: value = None break if value is not None: metric = PerformanceMetric(label=label, value=value, unit=unit) perfdata.append(metric) def other2perfdata(metrics): for metric in metrics: if len(metric) == 2: label, value = metric unit = "" elif len(metric) > 2: label, value, unit = metric else: continue if value is not None: metric = PerformanceMetric(label=label, value=value, unit=unit) perfdata.append(metric) # Add cluster-wide metrics first. If you monitor all of your ES # cluster nodes with this plugin, they should all report the # same figures for these labels. Not ideal, but 'tis better to # graph this data multiple times than not graph it at all. metrics = [["cluster_nodes", n_nodes], ["cluster_master_eligible_nodes", n_mnodes], ["cluster_data_nodes", n_dnodes], ["cluster_active_shards", n_active_shards], ["cluster_relocating_shards", n_relocating_shards], ["cluster_initialising_shards", n_initialising_shards], ["cluster_unassigned_shards", n_unassigned_shards], ["cluster_total_shards", n_shards]] other2perfdata(metrics) metrics = [["storesize", 'indices.store.size_in_bytes', "B"], ["documents", 'indices.docs.count'], ["index_ops", 'indices.indexing.index_total', "c"], ["index_time", 'indices.indexing.' 'index_time_in_millis', "c"], ["query_ops", 'indices.search.query_total', "c"], ["query_time", 'indices.search.' 'query_time_in_millis', "c"], ["flush_ops", 'indices.flush.total', "c"], ["flush_time", 'indices.flush.' 'total_time_in_millis', "c"]] dict2perfdata(es_stats['nodes'][myid], metrics) # # Assertions # detail = [] # Collect error messages into this list msg = "Monitoring cluster '%s'" % es_health['cluster_name'] # Assertion: Each shard has one primary in STARTED state. downgraded = False for idx_name, idx in name_index_map.iteritems(): for shard_no in range(idx.n_shards): primary = index_primary_map[idx][shard_no] if primary is None: downgraded |= self.downgrade_health(RED) detail.append("Index '%s' missing primary on " "shard %d" % (idx_name, shard_no)) else: if primary.state != SHARD_STATE['STARTED']: downgraded |= self.downgrade_health(RED) detail.append("Index '%s' primary down on " "shard %d" % (idx_name, shard_no)) if downgraded: msg = ("One or more indexes are missing primary shards. " "Use -vv to list them.") # Assertion: Each primary has replicas in STARTED state. downgraded = False for idx_name, idx in name_index_map.iteritems(): expect_replicas = idx.n_replicas for shard_no in range(idx.n_shards): primary = index_primary_map[idx][shard_no] if primary is None: continue has_replicas = len(primary_replica_map[primary]) if has_replicas < expect_replicas: downgraded |= self.downgrade_health(YELLOW) detail.append("Index '%s' missing replica on " "shard %d" % (idx_name, shard_no)) for replica in primary_replica_map[primary]: if replica.state != SHARD_STATE['STARTED']: downgraded |= self.downgrade_health(YELLOW) detail.append("Index '%s' replica down on " "shard %d" % (idx_name, shard_no)) if downgraded: msg = ("One or more indexes are missing replica shards. " "Use -vv to list them.") # Assertion: You have as many master-eligible nodes in the # cluster as you think you ought to. # # To be of any use in detecting split-brains, this value must be # set to the *total* number of master-eligible nodes in the # cluster, not whatever you set in ElasticSearch's # 'discovery.zen.minimum_master_nodes' configuration parameter. # (See ES issue #2488.) Of course, this will trip whenever a # node is taken down for maintenance, so we raise only a warning # -- not a critical -- status condition. downgraded = False if opts.master_nodes is not None: if n_mnodes < int(opts.master_nodes): downgraded |= self.downgrade_health(YELLOW) detail.append("Expected to find %d master-eligible " "nodes in the cluster but only found %d" % (int(opts.master_nodes), n_mnodes)) if downgraded: msg = ("Missing master-eligible nodes") # Assertion: Replicas are not stored in the same failure domain # as their primary. downgraded = False if len(failure_domain) > 0: for idx_name, idx in name_index_map.iteritems(): # Suppress this test if the index has not been # configured with replicas. if idx.n_replicas == 0: continue for shard_no in range(idx.n_shards): loc_redundancy = set() vulnerable_shards = set() primary = index_primary_map[idx][shard_no] if primary is None: continue try: loc = shard_location_map[primary] except KeyError: continue loc_redundancy.add(loc) vulnerable_shards.add(primary) for replica in primary_replica_map[primary]: try: loc = shard_location_map[replica] except KeyError: continue loc_redundancy.add(loc) vulnerable_shards.add(replica) # Suppress the problem unless at least one of the # vulnerable shards is on this data node. my_shards = set(node_shard_map[esid_node_map[myid]]) if vulnerable_shards.isdisjoint(my_shards): continue if len(loc_redundancy) == 1: downgraded |= self.downgrade_health(YELLOW) loc = ",".join(list(loc_redundancy)[0]) detail.append("Index '%s' shard %d only exists " "in location '%s'" % (idx_name, shard_no, loc)) if downgraded: msg = ("One or more index shards are not being replicated " "across failure domains. Use -vv to list them.") # ES detected a problem that we did not. This should never # happen. (If it does, you should work out what happened, then # fix this code so that we can detect the problem if it happens # again.) Obviously, in this case, we cannot provide any useful # output to the operator. if their_health < self.health: raise Status('critical', ("Cluster reports degraded health: '%s'" % es_health['status'],), perfdata) raise Status(HEALTH_MAP[self.health], (msg, None, "%s\n\n%s" % (msg, "\n".join(detail))), perfdata) def downgrade_health(self, new_health): if new_health < self.health: self.health = new_health return True return False def booleanise(b): """Normalise a 'stringified' Boolean to a proper Python Boolean. ElasticSearch has a habit of returning "true" and "false" in its JSON responses when it should be returning `true` and `false`. If `b` looks like a stringified Boolean true, return True. If `b` looks like a stringified Boolean false, return False. Raise ValueError if we don't know what `b` is supposed to represent. """ s = str(b) if s.lower() == "true": return True if s.lower() == "false": return False raise ValueError("I don't know how to coerce %r to a bool" % b) def get_json(uri): try: f = urllib2.urlopen(uri) except urllib2.HTTPError, e: raise Status('unknown', ("API failure", None, "API failure:\n\n%s" % str(e))) except urllib2.URLError, e: # The server could be down; make this CRITICAL. raise Status('critical', (e.reason,)) body = f.read() try: j = json.loads(body) except ValueError: raise Status('unknown', ("API returned nonsense",)) return j if __name__ == '__main__': ElasticSearchCheck().run()
UTF-8
Python
false
false
2,013
7,172,595,424,966
38b5bf25f33fcee7f8e807d7f1fbc88e562f72dd
bcaac7216b8223b53409060e3f4f9d3d48a53075
/smsing/messaging.py
54a7d059e1f229cac2b7212bd4948074c5e098d8
[]
no_license
goksie/django-smsing
https://github.com/goksie/django-smsing
133b5dd227449843ce53fd3b7a1ff13ca676d741
3fab4f97309c6f345c6b111cf66d3edd4c457556
refs/heads/master
2021-01-16T22:57:33.146897
2012-12-15T13:26:15
2012-12-15T13:26:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from smsing.api import get_connection class Message(object): """ An SMS message """ def __init__(self, to=None, text='', connection=None, **kwargs): """ `to` argument should always be a list or tuple. `text` argument should be a maximum of 160 characters unless kannel has been configured for long messages. """ if to: assert not isinstance(to, basestring), 'please use a list or \ tuple for the `to` argument' self.to = to else: self.to = [] self.text = text self.connection = connection def send(self, fail_silently=False): """ Sends an SMS """ if not self.to: # Nobody to send to so fail return 0 sent = self.connect(fail_silently).send_messages([self]) return sent def connect(self, fail_silently=False): """ Finds a backend connection to use """ if not self.connection: self.connection = get_connection(fail_silently=fail_silently) return self.connection
UTF-8
Python
false
false
2,012
14,207,751,819,235
8f2497ed1c5a3b3789e18d350213f2cb5e8197c8
eb1146c895f526f359f65ed511508d1832ff522e
/wstfil/rules/lex/base.py
d309a67d1ee83b4013e1caa9a6e1412368017cee
[]
no_license
joehillen/WSTFIL
https://github.com/joehillen/WSTFIL
c3fff504141aeafb92bfd5d5e204a2496c13002d
adb18428083bf1ce38724e344fd168f122d79093
refs/heads/master
2021-03-12T19:20:12.167726
2012-09-04T09:57:01
2012-08-30T01:59:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def t_error(t): print "Illegal character '{0}' @ {1},{2}".format(t.value[0],t.lexer.lineno,t.lexer.lexpos) t.lexer.skip(1) t_ignore = ''
UTF-8
Python
false
false
2,012
8,014,408,978,153
3f10c3969b574131a14047871532d89a9b7a0e72
e471bca38bc4633057f50bbe68bf9f0f0f234b74
/GenericPlugins/SearchSystem/Searcher.py
33a3d4ac6a1d840c12983cedf0a5492a09a6d11b
[ "GPL-2.0-only", "LGPL-2.0-or-later" ]
non_permissive
styx/scribes
https://github.com/styx/scribes
4e3a9b2fc5228a0e3b8357aa09144fc584512c0b
2a9112fec5a5bc34980a6695e972913fbd37de22
refs/heads/master
2016-03-30T10:20:21.526437
2011-10-03T06:58:40
2011-10-03T06:58:40
1,041,343
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from gettext import gettext as _ message = _("No matches found") class Searcher(object): def __init__(self, manager, editor): self.__init_attributes(manager, editor) self.__sigid1 = manager.connect("destroy", self.__destroy_cb) self.__sigid2 = manager.connect("search-boundary", self.__boundary_cb) self.__sigid3 = manager.connect("new-regex", self.__regex_cb) self.__sigid4 = manager.connect("regex-flags", self.__regex_flags_cb) self.__sigid5 = manager.connect("search-mode-flag", self.__search_mode_cb) from gobject import idle_add idle_add(self.__precompile_methods, priority=9999) def __init_attributes(self, manager, editor): self.__manager = manager self.__editor = editor self.__text = None self.__regex_flags = None self.__regex_mode = False return def __destroy(self): self.__editor.disconnect_signal(self.__sigid1, self.__manager) self.__editor.disconnect_signal(self.__sigid2, self.__manager) self.__editor.disconnect_signal(self.__sigid3, self.__manager) self.__editor.disconnect_signal(self.__sigid4, self.__manager) self.__editor.disconnect_signal(self.__sigid5, self.__manager) del self self = None return def __find_matches(self, regex_object): iterator = regex_object.finditer(self.__text) matches = [match.span() for match in iterator] match_object = regex_object.search(self.__text) if self.__regex_mode else None self.__manager.emit("match-object", match_object) self.__manager.emit("found-matches", matches) if not matches: self.__manager.emit("search-complete") if not matches: self.__editor.update_message(message, "fail", 10) return def __destroy_cb(self, *args): self.__destroy() return False def __boundary_cb(self, manager, boundary): self.__text = self.__editor.textbuffer.get_text(*(boundary)).decode("utf-8") return False def __regex_cb(self, manager, regex_object): self.__find_matches(regex_object) return False def __regex_flags_cb(self, manager, flags): self.__regex_flags = flags return False def __precompile_methods(self): methods = (self.__find_matches,) self.__editor.optimize(methods) return False def __search_mode_cb(self, manager, search_mode): self.__regex_mode = True if search_mode == "regex" else False return False
UTF-8
Python
false
false
2,011
5,884,105,211,164
6dd607803f34c71dcc1669c9a6a9c6ff8f505683
764a56233e25ed1b22fb409ff29b311accf72702
/src/msec/tools.py
b628d9687fbecd6072be98c6c80bc4dd41c5ec28
[ "GPL-2.0-only" ]
non_permissive
eugeni/msec
https://github.com/eugeni/msec
cc84889ba5da901c353890405303653553d7b556
536bb0bf9da8c22e81739ec6473460003307a365
refs/heads/master
2020-12-24T17:44:38.267810
2011-05-25T12:32:40
2011-05-25T12:32:40
2,108,538
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # # msec: helper tools # import os import stat import sys import time import locale # localization import gettext try: gettext.install("msec") except IOError: _ = str # constants FIREWALL_CMD = "drakfirewall &" UPDATE_CMD = "MandrivaUpdate &" def find_firewall_info(log): """Finds information about firewall""" # read firewall settings firewall_entries = [] try: data = os.popen("iptables -S").readlines() for l in data: if l[:3] == "-A ": firewall_entries.append(l.strip()) except: log.error(_("Unable to parse firewall configuration: %s") % sys.exc_value) # not find out if the firewall is enabled if len(firewall_entries) == 0: firewall_status = _("Disabled") else: firewall_status = _("Enabled, with %d rules") % len(firewall_entries) return firewall_status def get_updates_status(log, updatedir="/var/lib/urpmi"): """Get current update status""" # just find out the modification time of /var/lib/urpmi try: ret = os.stat(updatedir) updated = time.localtime(ret[stat.ST_MTIME]) updated_s = time.strftime(locale.nl_langinfo(locale.D_T_FMT), updated) status = _("Last updated: %s") % updated_s except: log.error(_("Unable to access %s: %s") % (updatedir, sys.exc_value)) status = _("Unable to determine update status") return status def periodic_check_status(log): """Determines the state of last periodic checks""" checks = [] for check in [ "daily", "weekly", "monthly", "manual" ]: current_log = "/var/log/security/mail.%s.today" % check if os.access(current_log, os.R_OK): ret = os.stat(current_log) last_run = time.localtime(ret[stat.ST_MTIME]) updated_s = time.strftime(locale.nl_langinfo(locale.D_T_FMT), last_run) checks.append((check, current_log, last_run, updated_s)) else: checks.append((check, current_log, None, None)) return checks
UTF-8
Python
false
false
2,011
7,318,624,286,706
7647024d405887a1786581875e9dc8b4a9f37017
51887e9ddd7e3ab0c934f070f7e5bea84d267bb7
/py/ltsTileCheck.py
be09ad93f7c6ca5f6262f2189e41dfb56333a603
[ "LGPL-2.1-only" ]
non_permissive
artemp/MapQuest-Render-Stack
https://github.com/artemp/MapQuest-Render-Stack
d38a83294b9fdfebf4ee9d1cab75be694eb56bbe
181bb1c9ce63214689a2d82bd44ebe672638adb9
refs/heads/master
2020-05-02T20:01:42.914617
2012-02-17T13:41:35
2012-02-17T13:41:35
3,495,984
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python #------------------------------------------------------------------------------ # # Checks if tiles are in storage # # Author: [email protected] # Author: [email protected] # # Copyright 2010-1 Mapquest, Inc. All Rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # #------------------------------------------------------------------------------ import sys sys.path.append( "../" ) from ConfigParser import ConfigParser import tile_storage import fileinput import dqueue import re import getopt FORMAT_LOOKUP = { "png256": dqueue.ProtoFormat.fmtPNG, "png": dqueue.ProtoFormat.fmtPNG, "jpeg": dqueue.ProtoFormat.fmtJPEG, "jpg": dqueue.ProtoFormat.fmtJPEG, "gif": dqueue.ProtoFormat.fmtGIF, "json": dqueue.ProtoFormat.fmtJSON } #load the storage configuration from file def load(configFile): config = ConfigParser() config.read(configFile) storage_conf = dict(config.items('storage')) storage = tile_storage.TileStorage(storage_conf) return storage def Usage(): print>>sys.stderr,'Usage: ./lts.py config tiles.txt' print>>sys.stderr,'-c=config\t\tStorage config' print>>sys.stderr,'-f=file\t\t\tFile of urls' print>>sys.stderr,'-v=freq\t\t\tVerbose mode print status after freq lines processed' #grab the value for a parameter that was passed in def GetParam(optionName, options, inputs, default=None): try: value = inputs[options.index(optionName)] return value if value != '' else default except: return default if __name__ == '__main__': try: #no long arguments, too lazy to implement for now... opts, args = getopt.getopt(sys.argv[1:], "c:f:v:", []) options = [option[0] for option in opts] inputs = [input[1] for input in opts] required = set(['-c', '-f']) if required.intersection(options) != required: raise getopt.error('Usage', 'Missing required parameter') except getopt.GetoptError: Usage() sys.exit(2) #get the storage object storage = load(GetParam('-c', options, inputs)) #get the verbosity try: verbosity = int(GetParam('-v', options, inputs)) except: verbosity = None #for each line count = 0 for line in fileinput.input(GetParam('-f',options,inputs), inplace = 0): line = line.lstrip().rstrip() if verbosity is not None and count % verbosity == 0: print 'finished %d lines' % count count = count + 1 #get the style z x y format parts = re.split(r'[/\.]',line) parts = [x for x in parts if len(x) > 0] if len(parts) != 5: continue #make the job and ask for it job = dqueue.TileProtocol() try: job.x = int(parts[2]) job.y = int(parts[3]) job.z = int(parts[1]) except: continue job.style = parts[0] if FORMAT_LOOKUP.has_key(parts[4]) == False: continue job.format = FORMAT_LOOKUP[parts[4]] #only care about single tile in the metatile handle = storage.get(job) if handle.exists() == False: print line
UTF-8
Python
false
false
2,012
11,914,239,310,976
db7fc741b57493a7a211382f25ff087e0c46589a
318cb59713f51ba1e7881aa48f5f7a6b1a2a173d
/collective/gallery/tests/test_link.py
fc210b5a9c31b106b48f165029cdd90840e56245
[]
no_license
jltavares/collective.gallery
https://github.com/jltavares/collective.gallery
b4533bc2075842bc9dbd0f098e9272a2d821e5d9
e0ef40aedd35151036951534e7827fba39594224
refs/heads/master
2020-12-25T16:26:11.118687
2012-09-18T07:21:34
2012-09-18T07:21:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from collective.gallery.tests import base from collective.gallery.tests import utils class Test(base.UnitTestCase): def setUp(self): super(Test, self).setUp() from collective.gallery import link self.view = link.BaseLinkView(self.context, self.request) self.view.settings = utils.FakeProperty def testPhotos(self): imgs = self.view.photos() self.failUnless(not imgs) self.failUnless(len(imgs) == 0) def testCreator(self): self.failUnless(self.view.creator == self.view.context.Creators()[0]) class TestIntegration(base.TestCase): def setUp(self): super(TestIntegration, self).setUp() self.folder.invokeFactory(id='mylink', type_name='Link') self.link = self.folder.mylink self.link.setRemoteUrl('http://notsupported.com/agallery') def testProperties(self): view = self.link.unrestrictedTraverse('@@gallery') self.failUnless(view.width == 400) self.portal.portal_properties.gallery_properties._updateProperty('photo_max_size', 500) self.failUnless(view.width == 500) def test_suite(): return base.build_test_suite((Test, TestIntegration))
UTF-8
Python
false
false
2,012
11,201,274,725,591
9d4967c5b8c53cf259a3315076511c1ce080bbe1
8c77b8d3a710a2177217479b04366295343eb734
/models/Message.py
2e76b58ba5b026aeb34420b1e53c6df9a6f40386
[]
no_license
Modulus/MessageApplication
https://github.com/Modulus/MessageApplication
05c1711f30298d42ae241ba45051c7d85b31352b
9b3f1170ff67394a92a5123a056b5af4636c5e82
refs/heads/master
2021-01-21T12:40:51.035375
2014-11-11T12:57:03
2014-11-11T12:57:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from mongoengine import Document, StringField, ListField, EmbeddedDocumentField from models.User import User __author__ = 'johska' class Message(Document): meta = { 'collection': 'messages' } header = StringField(required=False, max_length=128) message = StringField(required=True, max_length=512, min_length=1) receivers = ListField(EmbeddedDocumentField(document_type='User', required=False)) sender = StringField(required=True)
UTF-8
Python
false
false
2,014
10,230,612,140,360
4875146771577e9b9666e57f52e5c8aa17ecc8a9
88be787cf52fa2ea396ecb15cae0e6d383acd5d4
/check.py
010227a7ac49c82f1ed6b1a8655d793fef967c74
[]
no_license
arcus-io/docker-py-healthcheck
https://github.com/arcus-io/docker-py-healthcheck
14a25655554b632a80e66a612bebe2ebbd08e398
f42c23e8e2043ba4a94969adf58ca64fce864f3e
refs/heads/master
2021-01-10T20:36:37.257038
2013-10-09T06:23:25
2013-10-09T06:23:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask import Flask import socket app = Flask(__name__) @app.route('/') def index(): return "Alive from {}".format(socket.gethostname()) if __name__=='__main__': app.run()
UTF-8
Python
false
false
2,013
3,624,952,406,779
5e6207f99c59a70b1d0741f126a2480922a1c03f
a8a37ea3f787d7b3a86c2a1aeb3a14092069d6cf
/renderPDF.py
30acea128db1d2b86baff7d2aee289105f1c381b
[]
no_license
simonlu47401/C2PDF14
https://github.com/simonlu47401/C2PDF14
657da28f248ab7befadac00179c244178823097a
53127ef31c6c5f52da07f47569b4f0037fd9b08b
refs/heads/master
2021-01-19T13:24:31.498034
2014-10-27T05:04:23
2014-10-27T05:04:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-*-coding: utf-8-*- # renderPDF - draws Drawings onto a canvas #__version__=''' $Id: renderPDF.py 3959 2012-09-27 14:39:39Z robin $ ''' #__doc__="""显示画图对象 within others PDFs or standalone import wx,time,os #from reportlab.graphics.shapes import _baseGFontName, _baseGFontNameBI from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.pdfmetrics import registerFont #from reportlab.platypus import tableofcontents #from reportlab.lib.styles import ParagraphStyle as PS #from reportlab.lib.units import inch #from reportlab.tools.docco.rl_doc_utils import * #from reportlab.platypus.tableofcontents import TableOfContents from reportlab.lib import pdfencrypt from os.path import basename from reportlab.pdfgen.canvas import Canvas ## ###from reportlab.graphics.shapes import * ##from reportlab.pdfbase.pdfmetrics import stringWidth ##from reportlab.lib.utils import getStringIO ##from reportlab import rl_config ##from reportlab.graphics.renderbase import Renderer, StateTracker, getStateDelta, renderScaledDrawing ## ## ### the main entry point for users... ##def draw(drawing, canvas, x, y, showBoundary=rl_config._unset_): ## """As it says""" ## R = _PDFRenderer() ## R.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary) ## ##class _PDFRenderer(Renderer): ## """This draws onto a PDF document. It needs to be a class ## rather than a function, as some PDF-specific state tracking is ## needed outside of the state info in the SVG model.""" ## ## def __init__(self): ## self._stroke = 0 ## self._fill = 0 ## self._tracker = StateTracker() ## ## dt = MyFileDropTarget(self) ## self.SetDropTarget(dt) ## ## ## def drawNode(self, node): ## """This is the recursive method called for each node ## in the tree""" ## #print "pdf:drawNode", self ## #if node.__class__ is Wedge: stop ## if not (isinstance(node, Path) and node.isClipPath): ## self._canvas.saveState() ## ## #apply state changes ## deltas = getStateDelta(node) ## self._tracker.push(deltas) ## self.applyStateChanges(deltas, {}) ## ## #draw the object, or recurse ## self.drawNodeDispatcher(node) ## ## self._tracker.pop() ## if not (isinstance(node, Path) and node.isClipPath): ## self._canvas.restoreState() ## ## def drawRect(self, rect): ## if rect.rx == rect.ry == 0: ## #plain old rectangle ## self._canvas.rect( ## rect.x, rect.y, ## rect.width, rect.height, ## stroke=self._stroke, ## fill=self._fill ## ) ## else: ## #cheat and assume ry = rx; better to generalize ## #pdfgen roundRect function. TODO ## self._canvas.roundRect( ## rect.x, rect.y, ## rect.width, rect.height, rect.rx, ## fill=self._fill, ## stroke=self._stroke ## ) ## ## def drawImage(self, image): ## path = image.path ## # currently not implemented in other renderers ## if path and (hasattr(path,'mode') or os.path.exists(image.path)): ## self._canvas.drawInlineImage( ## path, ## image.x, image.y, ## image.width, image.height ## ) ## ## def drawLine(self, line): ## if self._stroke: ## self._canvas.line(line.x1, line.y1, line.x2, line.y2) ## ## def drawCircle(self, circle): ## self._canvas.circle( ## circle.cx, circle.cy, circle.r, ## fill=self._fill, ## stroke=self._stroke ## ) ## ## def drawPolyLine(self, polyline): ## if self._stroke: ## assert len(polyline.points) >= 2, 'Polyline must have 2 or more points' ## head, tail = polyline.points[0:2], polyline.points[2:], ## path = self._canvas.beginPath() ## path.moveTo(head[0], head[1]) ## for i in range(0, len(tail), 2): ## path.lineTo(tail[i], tail[i+1]) ## self._canvas.drawPath(path) ## ## def drawWedge(self, wedge): ## centerx, centery, radius, startangledegrees, endangledegrees = \ ## wedge.centerx, wedge.centery, wedge.radius, wedge.startangledegrees, wedge.endangledegrees ## yradius, radius1, yradius1 = wedge._xtraRadii() ## if yradius is None: yradius = radius ## angle = endangledegrees-startangledegrees ## path = self._canvas.beginPath() ## if (radius1==0 or radius1 is None) and (yradius1==0 or yradius1 is None): ## path.moveTo(centerx, centery) ## path.arcTo(centerx-radius, centery-yradius, centerx+radius, centery+yradius, ## startangledegrees, angle) ## else: ## path.arc(centerx-radius, centery-yradius, centerx+radius, centery+yradius, ## startangledegrees, angle) ## path.arcTo(centerx-radius1, centery-yradius1, centerx+radius1, centery+yradius1, ## endangledegrees, -angle) ## path.close() ## self._canvas.drawPath(path, ## fill=self._fill, ## stroke=self._stroke) ## ## def drawEllipse(self, ellipse): ## #need to convert to pdfgen's bounding box representation ## x1 = ellipse.cx - ellipse.rx ## x2 = ellipse.cx + ellipse.rx ## y1 = ellipse.cy - ellipse.ry ## y2 = ellipse.cy + ellipse.ry ## self._canvas.ellipse(x1,y1,x2,y2,fill=self._fill,stroke=self._stroke) ## ## def drawPolygon(self, polygon): ## assert len(polygon.points) >= 2, 'Polyline must have 2 or more points' ## head, tail = polygon.points[0:2], polygon.points[2:], ## path = self._canvas.beginPath() ## path.moveTo(head[0], head[1]) ## for i in range(0, len(tail), 2): ## path.lineTo(tail[i], tail[i+1]) ## path.close() ## self._canvas.drawPath( ## path, ## stroke=self._stroke, ## fill=self._fill ## ) ## ## def drawString(self, stringObj): ## if self._fill: ## S = self._tracker.getState() ## text_anchor, x, y, text, enc = S['textAnchor'], stringObj.x,stringObj.y,stringObj.text, stringObj.encoding ## if not text_anchor in ['start','inherited']: ## font, font_size = S['fontName'], S['fontSize'] ## textLen = stringWidth(text, font, font_size, enc) ## if text_anchor=='end': ## x -= textLen ## elif text_anchor=='middle': ## x -= textLen*0.5 ## elif text_anchor=='numeric': ## x -= numericXShift(text_anchor,text,textLen,font,font_size,enc) ## else: ## raise ValueError, 'bad value for textAnchor '+str(text_anchor) ## t = self._canvas.beginText(x,y) ## t.textLine(text) ## self._canvas.drawText(t) ## ## def drawPath(self, path): ## from reportlab.graphics.shapes import _renderPath ## pdfPath = self._canvas.beginPath() ## drawFuncs = (pdfPath.moveTo, pdfPath.lineTo, pdfPath.curveTo, pdfPath.close) ## isClosed = _renderPath(path, drawFuncs) ## if isClosed: ## fill = self._fill ## else: ## fill = 0 ## if path.isClipPath: ## self._canvas.clipPath(pdfPath, fill=fill, stroke=self._stroke) ## else: ## self._canvas.drawPath(pdfPath, ## fill=fill, ## stroke=self._stroke) ## ## def setStrokeColor(self,c): ## self._canvas.setStrokeColor(c) ## ## def setFillColor(self,c): ## self._canvas.setFillColor(c) ## ## def applyStateChanges(self, delta, newState): ## """This takes a set of states, and outputs the PDF operators ## needed to set those properties""" ## for key, value in delta.items(): ## if key == 'transform': ## self._canvas.transform(value[0], value[1], value[2], ## value[3], value[4], value[5]) ## elif key == 'strokeColor': ## #this has different semantics in PDF to SVG; ## #we always have a color, and either do or do ## #not apply it; in SVG one can have a 'None' color ## if value is None: ## self._stroke = 0 ## else: ## self._stroke = 1 ## self.setStrokeColor(value) ## elif key == 'strokeWidth': ## self._canvas.setLineWidth(value) ## elif key == 'strokeLineCap': #0,1,2 ## self._canvas.setLineCap(value) ## elif key == 'strokeLineJoin': ## self._canvas.setLineJoin(value) ### elif key == 'stroke_dasharray': ### self._canvas.setDash(array=value) ## elif key == 'strokeDashArray': ## if value: ## if isinstance(value,(list,tuple)) and len(value)==2 and isinstance(value[1],(tuple,list)): ## phase = value[0] ## value = value[1] ## else: ## phase = 0 ## self._canvas.setDash(value,phase) ## else: ## self._canvas.setDash() ## elif key == 'fillColor': ## #this has different semantics in PDF to SVG; ## #we always have a color, and either do or do ## #not apply it; in SVG one can have a 'None' color ## if value is None: ## self._fill = 0 ## else: ## self._fill = 1 ## self.setFillColor(value) ## elif key in ['fontSize', 'fontName']: ## # both need setting together in PDF ## # one or both might be in the deltas, ## # so need to get whichever is missing ## fontname = delta.get('fontName', self._canvas._fontname) ## fontsize = delta.get('fontSize', self._canvas._fontsize) ## self._canvas.setFont(fontname, fontsize) ## elif key=='fillOpacity': ## if value is not None: ## self._canvas.setFillAlpha(value) ## elif key=='strokeOpacity': ## if value is not None: ## self._canvas.setStrokeAlpha(value) ## elif key=='fillOverprint': ## self._canvas.setFillOverprint(value) ## elif key=='strokeOverprint': ## self._canvas.setStrokeOverprint(value) ## elif key=='overprintMask': ## self._canvas.setOverprintMask(value) ## ##from reportlab.platypus import Flowable ##class GraphicsFlowable(Flowable): ## """Flowable wrapper around a Pingo drawing""" ## def __init__(self, drawing): ## self.drawing = drawing ## self.width = self.drawing.width ## self.height = self.drawing.height ## ## def draw(self): ## draw(self.drawing, self.canv, 0, 0) ## ##def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1): ## """Makes a one-page PDF with just the drawing. ## ## If autoSize=1, the PDF will be the same size as ## the drawing; if 0, it will place the drawing on ## an A4 page with a title above it - possibly overflowing ## if too big.""" ## d = renderScaledDrawing(d) ## c = Canvas(fn) ## if msg: ## c.setFont(rl_config.defaultGraphicsFontName, 36) ## c.drawString(80, 750, msg) ## c.setTitle(msg) ## ## if autoSize: ## c.setPageSize((d.width, d.height)) ## draw(d, c, 0, 0, showBoundary=showBoundary) ## else: ## #show with a title ## c.setFont(rl_config.defaultGraphicsFontName, 12) ## y = 740 ## i = 1 ## y = y - d.height ## draw(d, c, 80, y, showBoundary=showBoundary) ## ## c.showPage() ## c.save() ## if sys.platform=='mac' and not hasattr(fn, "write"): ## try: ## import macfs, macostools ## macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ") ## macostools.touched(fn) ## except: ## pass ## ##def drawToString(d, msg="", showBoundary=rl_config._unset_,autoSize=1): ## "Returns a PDF as a string in memory, without touching the disk" ## s = getStringIO() ## drawToFile(d, s, msg=msg, showBoundary=showBoundary,autoSize=autoSize) ## return s.getvalue() def drawFooter(c,page,srcFile,no): #2013.10.10 srcFile = srcFile.decode('utf8')#? line = "Page %d-%d %s : %s %s"%(no,page,wx.GetHostName(),wx.GetUserName(),srcFile) t=time.localtime() ctime = '%04d-%02d-%02d %02d:%02d:%02d'%(t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec) c.setFont("MyFont",8) c.line(5, 25, 590,25) c.drawString(10, 10, line) c.drawRightString(585, 10, ctime) c.line(5, 810, 590,810) line = u"2014级程序设计原理与C语言" c.drawString(10, 820, line) line = "Principles of Programming for grade 2014" c.drawRightString(585, 820, line) def anySplit(x,sep): for c in sep: splitpoint = x[:81].rfind(c) if splitpoint>=70: break if splitpoint<70: splitpoint=80 return x[:splitpoint+1],x[splitpoint+1:] ######################################################### # # test code. First, define a bunch of drawings. # Routine to draw them comes at the end. # ######################################################### def test(srcFiles,values={ },passwd='C2014',outfile=None): srcFiles = sorted(srcFiles,key=basename) registerFont(UnicodeCIDFont('STSong-Light')) from reportlab.pdfbase import ttfonts # font = ttfonts.TTFont('MyFont', r'C:\Windows\Fonts\simhei.ttf') font = ttfonts.TTFont('MyFont', r'msyhbd.ttf') # font = ttfonts.TTFont('MyFont', 'msyhbd.ttf') registerFont(font) user = values.get('user','') if user: user = user.encode('utf8') name = values.get('name','').encode('utf8') password = values.get('passwd','') if password.strip(): passwd=password.encode('utf8')#? if values.get('lab','')!='': labv = int(values.get('lab','0')) else: labv=0 if 0<labv<20: lab = ('Lab%d'%labv).encode('utf8') else: lab=u'' # if user.startswith('10132130') and 0<labv<20: # 2013.10.10 if user.startswith('101') and len(user)==11 and 0<labv<20: # 2013.10.10 # outfile = (os.getcwd()+'/'+user.encode('utf8')+'_'+'%02d.c'%labv).encode('utf8') #? outfile = (os.getcwdu()+u'/'+user.encode('utf8')+u'_'+u'%02d.PDF'%labv) if outfile==None: # if srcFiles[0].rfind('.')!=-1: # pdffile = srcFiles[0][:srcFiles[0].rfind('.')] # else: pdffile = srcFiles[0] # 2013.10.10 bname=basename(srcFiles[0]) if bname.rfind('.')!=-1: pdffile = bname[:bname.rfind('.')] else: pdffile = bname pdffile = os.getcwd()+'/'+pdffile # 2013.10.10 pdffile=unicode(pdffile.decode('utf8'))#? else: if outfile.rfind('.')!=-1: pdffile = outfile[:outfile.rfind('.')] else: pdffile = outfile # 2013.10.10 # pdffile --> pdffile.encode('gbk') if passwd=="C2014": c = Canvas(pdffile.encode('utf8')+'.pdf') else: c = Canvas(pdffile.encode('utf8')+'.pdf',\ encrypt=pdfencrypt.StandardEncryption\ (passwd,ownerPassword='c14c',canPrint=0,canCopy=0)) # c = Canvas(pdffile+'.pdf') c.showOutline() c.setAuthor(u"LU") c.setTitle(u"2014级程序设计原理与C语言作业") c.setSubject(u"作业") c.setCreator(u"C2PDF") c.setKeywords(['C语言','程序设计','作业','2014级']) blank = "","" line1 = u"课程名", u"2014级程序设计原理与C语言"+' '+u"Principles of Programming & C" chost = u"机器名",wx.GetHostName() cuser = u"用户名",wx.GetUserName() ID = u"学号",user USER = u"姓名",name grade = u"成绩",u" " labName = u"作业名",lab lines = (line1,chost,cuser,ID,USER,blank,labName,grade) c.setFont("MyFont",12) x,y,delta=50,800,20 for line in lines: c.drawString(x, y, line[0]) from reportlab.lib.colors import pink, black, red, blue, green if line[0]==u"成绩": # c.saveState() c.setFillColor(red) c.setFont("MyFont",20) y -= 15 c.drawString(x+70, y, line[1]) c.setFont("MyFont",12) c.setFillColor(black) # c.restoreState() else: c.drawString(x+70, y, line[1]) y -= delta filelist=srcFiles s0="Table of Contents" c.bookmarkPage(s0,'FitH') c.addOutlineEntry(s0,s0) for no,f in enumerate(filelist): # c.addOutlineEntry(basename(f),f) # 2013.10.10 c.addOutlineEntry(basename(f).decode('utf8'),f)#? y -= delta # c.drawString(x, y, "%2d: %s"%(no+1,f)) # 2013.10.10 c.drawString(x, y, "%2d: %s"%(no+1,f.decode('utf8')))#? c.linkRect("", f,(x,y+delta-5,x+400,y-5), Border='[0 0 0]') t = time.localtime() ctime = '%04d-%02d-%02d %02d:%02d:%02d'%(t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec) c.drawString(x+70, y-2*delta, ctime) c.showPage() for no,f in enumerate(filelist): outOneFile(f,c,no+1) """ from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, Frame styles = getSampleStyleSheet() toc = TableOfContents() PS = ParagraphStyle toc.levelStyles = [ PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1',\ leftIndent=20, firstLineIndent=-20, spaceBefore=5, leading=16), PS(fontSize=12, name='TOCHeading2',\ leftIndent=40, firstLineIndent=-20, spaceBefore=0, leading=12) ] styleN = styles['Normal'] styleH = styles['Heading1'] styleH2 = styles['Heading2'] story = [ ] story.append(Paragraph("This is a Heading<font size=54> abc[&alpha;] <greek>e</greek> <greek>p</greek> </font>",styleH)) story.append(Spacer(inch,inch)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) story.append(Paragraph("This is a Heading2 style.", styleH2)) toc.addEntry(0, 'txt', 1) toc.addEntry(1, 'txt1', 2) story.append(toc) f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story,c) """ c.save() # print 'saved PDF file for '+pdffile return pdffile+u'.pdf' def outOneFile(srcFile,c,no): c.bookmarkPage(srcFile,'FitH') c.setFont("MyFont", 18) c.drawString(10, 780, 'Code Listing') from reportlab.graphics import testshapes drawings =[] for i,line in enumerate(open(srcFile)): line="%3d: %s"%( i+1, line.rstrip('\n')) try: x=line.decode('utf8') except: x=line.decode('gbk') first=True while len(x)>85: r = anySplit(x,''' ,=;'"+-*/)''') drawings.append(r[0]) x=' '*10+r[1] drawings.append(x) y = 770 i = 1 page = 0 for line in drawings: if y < 50: #allows 5-6 lines of text page+=1 drawFooter(c,page,srcFile,no) c.showPage() y = 800 y = y - 18 c.setFont("MyFont",12) c.drawString(10, y, line) i = i + 1 if y!=800: page+=1 drawFooter(c,page,srcFile,no) c.showPage() if __name__=='__main__': srcFiles = (r"renderpdf.py","help.txt") outfile = r"renderpdf.pdf" test(srcFiles,outfile=outfile)
UTF-8
Python
false
false
2,014