__id__
int64 17.2B
19,722B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
133
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 3
values | repo_name
stringlengths 7
73
| repo_url
stringlengths 26
92
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 12
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 61.3k
283M
⌀ | star_events_count
int64 0
47
| fork_events_count
int64 0
15
| gha_license_id
stringclasses 5
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
82
⌀ | gha_forks_count
int32 0
25
⌀ | gha_open_issues_count
int32 0
80
⌀ | gha_language
stringclasses 5
values | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 19
187k
| src_encoding
stringclasses 4
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | year
int64 2k
2.01k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
523,986,049,062 |
fa1da512ee6b64b91c87a65c8d4ce875a9fdf473
|
2a20624152b36d212e2802755b6c02d19961c71f
|
/app.py
|
cdd11512a31c1bb5ff9e6d197014f5bb0eddaef0
|
[
"MIT"
] |
permissive
|
jimr/relish-race-results
|
https://github.com/jimr/relish-race-results
|
026fb49eff1e6ce4974909b345852a00ee5ecaad
|
dae5b6a6c95967ce6e93cef49f9f2b168f542c17
|
refs/heads/master
| 2021-01-10T20:22:10.754659 | 2014-10-02T21:39:19 | 2014-10-02T21:39:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mimetypes
import rrr
from flask import Flask, make_response, request, render_template
from flask.ext.heroku import Heroku
from werkzeug import secure_filename
app = Flask(__name__)
heroku = Heroku(app)
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def results():
fmt = request.form.get('format', 'csv')
pdf = request.files['file']
filename = '{}.{}'.format(pdf.filename[:-4], fmt)
response = make_response(rrr.results(pdf, fmt))
response.headers['Content-Type'] = mimetypes.guess_type(filename)[0]
response.headers['Content-Disposition'] = (
'attachment; filename={}'.format(filename)
)
return response
if __name__ == '__main__':
app.debug = True
app.run(port=5000)
|
UTF-8
|
Python
| false | false | 2,014 |
5,634,997,093,356 |
9902b112a22dfa9589cba7eba60d47ff77d1af8d
|
dc46671e6d1a476a57d830e2809e1d04192db7f1
|
/horizon_client/models.py
|
7f919fa01dde4a6ebad977b65279b44091076676
|
[] |
no_license
|
c2j/pdlib
|
https://github.com/c2j/pdlib
|
a26d30650937988bde0c722eef1148fabda71f22
|
ca496975ccc150bac24790c87551cff0f16fa785
|
refs/heads/master
| 2020-06-01T09:51:32.188189 | 2014-07-13T15:11:45 | 2014-07-13T15:11:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#from django.db import models
from mongoengine import *
# Create your models here.
class Book(Document):
url = StringField(required=True)
title = StringField(required=True)
authors = ListField(StringField())
issuer = StringField()
|
UTF-8
|
Python
| false | false | 2,014 |
18,210,661,338,326 |
6c9d54694656ecf7493160d637bcd4627be33ca8
|
348639419be641dd8a34c4b1e2c3cca71ebe0e19
|
/patches/june_2012/alter_tabsessions.py
|
4e0310bffb0b59648b711580badcd6dac3bf363c
|
[
"GPL-1.0-or-later",
"CC-BY-SA-3.0",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] |
non_permissive
|
umairsy/erpnext
|
https://github.com/umairsy/erpnext
|
aa900c509489a7d72324ba371ed3b6ee79689b52
|
9f80c14f8ddf423d1b9e3bad1374466141cb10bb
|
refs/heads/master
| 2022-02-17T21:41:27.924968 | 2013-07-17T06:47:53 | 2013-07-17T06:47:53 | 2,036,108 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from __future__ import unicode_literals
def execute():
import webnotes
webnotes.conn.commit()
webnotes.conn.sql("alter table `tabSessions` modify user varchar(180)")
webnotes.conn.begin()
|
UTF-8
|
Python
| false | false | 2,013 |
16,810,501,997,299 |
cff2b8d68707dd7ebcffe86e961fa90fff62029f
|
be138468218872ab0471185167c86f5061cbbd74
|
/trunk/SUAVE/Methods/Utilities/create_state_data.py
|
4d2ba60c89e0fd683d6f89a31ac7d0316b8f2925
|
[
"CC-BY-NC-SA-4.0",
"CC-BY-SA-3.0"
] |
non_permissive
|
thearn/SUAVE
|
https://github.com/thearn/SUAVE
|
e203816b73591c30e57b33a71ce3f44a46db1bac
|
bcca96e2e1dab5c482dc4447d8e6752406f80fbe
|
refs/heads/master
| 2021-01-18T06:52:35.804639 | 2014-08-20T22:14:52 | 2014-08-20T22:14:52 | 23,135,993 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
""" Utilities.py: Mathematical tools and numerical integration methods for ODEs """
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import numpy as np
#import ad
from scipy.optimize import root #, fsolve, newton_krylov
from SUAVE.Structure import Data
from SUAVE.Attributes.Results import Segment
# ----------------------------------------------------------------------
# Methods
# ----------------------------------------------------------------------
def create_state_data(z,u,problem,eta=[]):
N, m = np.shape(z)
# scale data
if problem.dofs == 2: # 2-DOF
z[:,0] *= problem.scale.L
z[:,1] *= problem.scale.V
z[:,2] *= problem.scale.L
z[:,3] *= problem.scale.V
elif problem.dofs == 3: # 3-DOF
z[:,0] *= problem.scale.L
z[:,1] *= problem.scale.V
z[:,2] *= problem.scale.L
z[:,3] *= problem.scale.V
z[:,4] *= problem.scale.L
z[:,5] *= problem.scale.V
else:
print "something went wrong in dimensionalize"
return []
state = State()
if problem.powered:
state.compute_state(z,u,problem.planet,problem.atmosphere, \
problem.config.Functions.Aero,problem.config.Functions.Propulsion,eta,problem.flags)
else:
state.compute_state(z,u,problem.planet,problem.atmosphere, \
problem.config.Functions.Aero,flags=problem.flags)
return state
|
UTF-8
|
Python
| false | false | 2,014 |
11,656,541,258,275 |
73bb46b44a83ffccf690f4f631895cb5805ca77e
|
ea1188412a085711d6b4de84eb30bd50d32a271f
|
/wscript
|
98ea898b11710caf448509159e4c4ecd245fe98a
|
[
"MIT"
] |
permissive
|
gflarity/node-dbus
|
https://github.com/gflarity/node-dbus
|
2f2b026e5889fc2906ee0c8bfe27c1d879a975b2
|
0e4da1d584ac0580c51085d0ce69159f5ecefec8
|
refs/heads/master
| 2020-12-25T17:13:19.280845 | 2012-09-27T17:17:22 | 2012-09-27T17:17:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import Options
from os import unlink, symlink, popen
from os.path import exists
from shutil import copy2
srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'
built = 'build/Release/dbus.node'
dest = 'lib/dbus.node'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
conf.check(header_name='expat.h', mandatory = True)
conf.env.append_value("LIB_EXPAT", "expat");
conf.check_cfg(package='dbus-1', args='--cflags --libs', uselib_store='DBUS');
conf.check_cfg(package='dbus-glib-1', args='--cflags --libs', uselib_store='GDBUS');
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'dbus'
obj.source = '''
src/dbus.cc
src/context.cc
src/dbus_introspect.cc
src/dbus_register.cc
'''
obj.lib = 'expat'
obj.uselib = 'DBUS GDBUS EXPAT'
def shutdown():
if Options.commands['clean']:
if exists('dbus.node'):
unlink('dbus.node')
else:
if exists(built):
copy2(built, dest)
|
UTF-8
|
Python
| false | false | 2,012 |
9,139,690,451,595 |
e76c9141762d669e2d9d2addca41dd27016396d7
|
63a6c806450736fe85f1a97a5fd20ed3847e8e14
|
/website/models/blog.py
|
eca23f73f31574922840b5fda6de8d87a6620e1d
|
[
"GPL-1.0-or-later",
"GPL-2.0-only"
] |
non_permissive
|
CaptainHayashi/lass
|
https://github.com/CaptainHayashi/lass
|
244529950378cd4405ec2451e3e7c4b85aeaf718
|
025cd8438db7204f96d2c97ce96cb123c40721a6
|
refs/heads/master
| 2021-01-15T23:01:46.034885 | 2013-08-30T16:41:18 | 2013-08-30T16:41:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
Temporary glue code for the old URY site blogs system.
"""
from metadata.models import Type
from django.db import models
from urysite import model_extensions as exts
class Blog(Type):
"""
A blog in the old URY site blogs system.
"""
id = exts.primary_key('blogid')
rss_uri = models.TextField()
blog_uri = models.TextField()
class Meta(Type.Meta):
db_table = 'blog'
app_label = 'website'
|
UTF-8
|
Python
| false | false | 2,013 |
1,769,526,550,515 |
948d90ebcb19741b22ec14079665c3283ae72d5a
|
25ff11eac6c312f9c98327cc06edcd0e74600ad1
|
/probs/e_43.py
|
6e06b424275121b5c6cd8c529e349115c920ec47
|
[] |
no_license
|
newgiin/project-euler
|
https://github.com/newgiin/project-euler
|
5df9357e5f970d335c38904da5b1ada39ae63741
|
37db8e25e6fbe7142525aada30a36d6d63e2e4c7
|
refs/heads/master
| 2021-01-19T07:41:46.466534 | 2014-02-24T20:25:43 | 2014-02-24T20:25:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def main():
sum = 0
primes = e_util.get_primes(18)
for p in e_util.get_perms("0123456789"):
flag = True
for i in xrange(1, 8):
if int(p[i : i + 3]) % primes[i - 1] != 0:
flag = False
break
if flag:
sum += int(p)
print sum
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,014 |
6,846,177,884,330 |
7d1ab10802d07a305d998f54ab42d63e0d1b75e6
|
a341923fd6df836c1c3f8a61020b37b515adc28a
|
/src/strategy/strategy.py
|
b79a66b661e939b4353a69f94f423f2e6f2ca9f9
|
[] |
no_license
|
peidright/plt_dev
|
https://github.com/peidright/plt_dev
|
0b020e9ee6fcf0c1bfe67330ab3ad47f03512fd1
|
775f9a104c3e96f3df215db7069d4c5850d0205f
|
refs/heads/master
| 2016-09-06T19:22:31.326293 | 2014-06-22T06:45:45 | 2014-06-22T06:45:45 | 17,791,996 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
from ctypes import *
from libs import apiop
from libs import apistruct
from libs import sframe
class sbase(object):
"Strategy base "
sf=None;
sid=None;
msg2rsp={};
def __init__(self):
pass
def run_init(self):
pass
def run_clear(self):
pass
def run_except(self):
pass
def is_running(self):
return True;
def init(self):
self.sf=sframe.sframe(self);
def rsp(self,msg):
pass
def rsp_default(self,msg):
#exp,run sbase rsp
pass
def profit_stat(self,msg):
pass
def run(self):
self.sf.run();
def expand(self):
pass
#s=sbase();
#s.init();
#s.run();
|
UTF-8
|
Python
| false | false | 2,014 |
12,472,585,066,480 |
401ef2fbce5362ae12a3d36956ea43a35c942082
|
813d893e618ee015834257fcb455919a9d5fba7c
|
/apps/carddirector/cd_app_upload/entities.py
|
182a73f4a02a69122a3d98c7591c6557dbdd16c5
|
[] |
no_license
|
devshark/CardManager
|
https://github.com/devshark/CardManager
|
9b30be52886b07df21fcbe74f193c39102f41e72
|
4cc6df3718fb81c61bd9aeefa580fb57b802fbbd
|
refs/heads/master
| 2018-03-10T15:31:00.065973 | 2013-08-13T08:43:59 | 2013-08-13T08:43:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from carddirector.cd_app_upload import utils
class KycFileReportEntry(object):
def __init__(self):
self.line_number = None
self.client_card_reference = None
self.original_filename = None
self.kyc_file = None
self.exist = None #match pp or poa name
self.info = None
self.is_kyc_submitted = False
|
UTF-8
|
Python
| false | false | 2,013 |
4,372,276,714,285 |
1c1c9e49325c7cf9b447ba59395450131d96adde
|
64f87e51133638e56228c3b1f196ed8f59af7201
|
/ssocket.py
|
11e5dcf783f3e4ab5fa7e193f4305917dff12366
|
[] |
no_license
|
siddharthm/IPmessenger
|
https://github.com/siddharthm/IPmessenger
|
19ace9fb2ffaf49dc2951e0a483d62642ccdb8ef
|
315c4f24fbccec400234b184beb3522518d4600e
|
refs/heads/master
| 2021-01-19T08:55:10.866590 | 2013-10-05T18:56:46 | 2013-10-05T18:56:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import socket
class ssocket:
# Siddharth Socket
def __init__(self,sock=None):
self.CHUNK_SIZE=512
if sock is None:
self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
else:
self.sock=sock
def connect(self,host,port):
self.sock.connect((host,port))
def send(self,msg):
msg_len=str(len(msg)).zfill(12) # can represent upto 1TB of data
self.sock.send(msg_len)
len_sent=0
while len_sent!=len(msg):
sent=self.sock.send(msg[len_sent:])
if sent==0:
raise RuntimeError("Socket Connection broken")
len_sent+=sent
return len(msg)
def send_file(self,file_path):
with open(file_path,"r+") as f:
file_data=f.read(self.CHUNK_SIZE)
position=0
while file_data:
position+=self.send(file_data)
f.seek(position)
file_data=f.read(self.CHUNK_SIZE)
def recv(self):
msg=""
msg_len_str=self.sock.recv(12)
if msg_len_str=="":
return ""
msg_len=int(msg_len_str)
len_recv=0
while len_recv!=msg_len:
recv_msg=self.sock.recv(msg_len-len_recv)
if recv_msg==0:
raise RuntimeError("Socket Connection broken")
len_recv+=len(recv_msg)
msg=msg+recv_msg
return msg
def recv_file(self,file_path):
with open(file_path,"w+") as f:
file_data=self.recv()
while file_data:
f.write(file_data)
file_data=self.recv()
|
UTF-8
|
Python
| false | false | 2,013 |
18,270,790,889,230 |
b949a716ded981f39301a0696639e6b62d83e9ee
|
40a4e3dcf6758bda15b4786fed17b7e18eb2faa8
|
/myexporter/forms.py
|
dc18b4bbb920edeccacc9fec6782439bdc17f375
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
non_permissive
|
mtezzo/ecoach_flat_phase2
|
https://github.com/mtezzo/ecoach_flat_phase2
|
e4eda26ad03a07cf540e350b6185ef32be07fa9c
|
da9618d7d882f17abf5e49abbcbfc8d7d1fc7f40
|
refs/heads/master
| 2021-01-09T07:47:50.210814 | 2014-11-10T22:34:56 | 2014-11-10T22:34:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django import forms
from django.conf import settings
from .models import *
from datetime import datetime
from django.utils.importlib import import_module
#mydata = import_module(settings.MYDATA)
#Source1 = mydata.models.Source1
class Select_Table_Form(forms.Form):
db_table = forms.ChoiceField(required=False)
def __init__(self, *args, **kwargs):
super(Select_Table_Form, self).__init__(*args, **kwargs)
self.fields['db_table'].choices = self.table_choices()
def table_choices(self):
available = [
('Message', 'Message'),
('ELog', 'ELog'),
('Source1', 'Source1')
#('Common1', 'Common1')
]
return available
class Select_Columns_Form(forms.Form):
columns = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple)
seperator = forms.CharField(required=False, max_length=1)
download_name = forms.CharField(required=False)
def __init__(self, column_choices, *args, **kwargs):
super(Select_Columns_Form, self).__init__(*args, **kwargs)
self.fields['columns'].choices = column_choices
class Download_File_Form(forms.Form):
pass
class Archive_Form(forms.Form):
download = forms.ModelChoiceField(required=False, queryset=Download.objects.all().order_by('-id'))
#def __init__(self, *args, **kwargs):
#super(Select_Table_Form, self).__init__(*args, **kwargs)
|
UTF-8
|
Python
| false | false | 2,014 |
5,076,651,377,386 |
a86ad7e269cc44642a343824db472f91881dd9a3
|
4569d707a4942d3451f3bbcfebaa8011cc5a128d
|
/latexformulamacro/0.8/formula.py
|
e010d858f0206f4838d32cff7a1a37a759e154f4
|
[] |
no_license
|
woochica/trachacks
|
https://github.com/woochica/trachacks
|
28749b924c897747faa411876a3739edaed4cff4
|
4fcd4aeba81d734654f5d9ec524218b91d54a0e1
|
refs/heads/master
| 2021-05-30T02:27:50.209657 | 2013-05-24T17:31:23 | 2013-05-24T17:31:23 | 13,418,837 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
Convert a latex formula into an image.
by Valient Gough <vgough@pobox.com>
Changes:
2005-10-03:
* make image format selectable via 'image_format' configuration option
(defaults to 'jpg')
* allow paths to executables to be specified in configuration by
setting 'latex_path', 'dvips_path', 'convert_path' to point to
executable. Based on code by Reed Cartwright.
2005-10-01:
* add #display and #fleqn options to add html formatting around image
(Christian Marquardt).
2005-09-21:
* add #center and #indent options to add html formatting around image.
2005-08-02:
* remove hard-coded paths, read from configuration. Fixes #26
2005-07-27:
* figured out how to get rid of the annoying internal error after latex
was run. Redirected latex output to /dev/null..
* found out that {{{#!figure ... }}} runs wiki macro, and doesn't have
the problem of not being able to use paranthesis. So this is the
default usage now. Can still use [[formula(...)]] for simple formula.
* add "nomode" command, which can be used to turn off automatic
enclosure of commands in display-math mode ("$$ ... $$")
2005-07-26: first release
Installation:
1. Copy into wiki-macros directory.
2. Edit conf/trac.ini and add a [latex] group with three values:
[latex]
# temp_dir points to directory where temporary files are created
temp_dir = /var/tmp/trac
# image_path is directory where final images are written
image_path = /var/www/html/formula
# display_path is URL where formula images can be accessed
display_path = http://foo.net/formula
# Set to 1 for fleqn style equations (default is centered)
fleqn = 0
# Indentation width for fleqn style equations
fleqn_width = '5%'
Usage:
{{{
#!formula
[latex code]
}}}
or, additional keywords can be specified before the latex code:
{{{
#!formula
#density=100
[latex code]
}}}
Optional keywords (must be specified before the latex code):
#density=100
Density defaults to 100. Larger values produces larger images.
#nomode
Disable the default display mode setting. Use this if you want to
include things outside of tex's display mode.
#display
Create a displayed equation (either centered or fleqn style,
depending on the fleqn variable in the config file.
#center
Center the equation on the page.
#fleqn
fleqn style equation; indentation is controlled by fleqn_witdh in
conf/trac.ini.
#indent [=class name]
places image link in a paragraph <p>...</p>
If class name is specified, then it is used to specify a CSS class for
the paragraph.
Notes:
A matrix macro is included in the tex code. This allows you to do things
like:
\mat{1&2\\3&4} to get a 2x2 matrix. The "\\" separates rows, and "&"
separates columns. Any size up to around 25? will work..
Images are automatically named based on a sha1 hash of the formula, the
density, and the script version. This way the image doesn't have to be
regenerated every time it is used, and if anything is changed then a new image
is created.
Note that temporary files can build up in the tmpdir, and every time a formula
is modified, a new image will be created in the imagePath directory. These can
be considered as cached files. You can safely let the tmp file cleaner process
remove old files from these directories.
PS. This is my first python program, so it is probably pretty ugly by python
standards (whatever those may be). Feedback is welcome, but complaints about
ugliness will be redirected to /dev/null.
"""
# if the output version string changes, then images will be regenerated
outputVersion = "0.1"
import re
import string
import os
import sha
def render(hdf, env, texData, density, fleqnMode, mathMode):
# gets paths from configuration
tmpdir = env.get_config('latex', 'temp_dir')
imagePath = env.get_config('latex', 'image_path')
displayPath = env.get_config('latex', 'display_path')
fleqnIndent = env.get_config('latex', 'fleqn_indent')
latexPath = env.get_config('latex', 'latex_path')
dvipsPath = env.get_config('latex', 'dvips_path')
convertPath = env.get_config('latex', 'convert_path')
texMag = env.get_config('latex', 'text_mag')
imageFormat = env.get_config('latex', 'image_format')
if not tmpdir or not imagePath or not displayPath:
return "<b>Error: missing configuration settings in 'latex' macro</b><br>"
# set defaults
if not fleqnIndent:
fleqnIndent = '5%'
if not latexPath:
latexPath = 'latex'
if not dvipsPath:
dvipsPath = 'dvips'
if not convertPath:
convertPath = 'convert'
if not texMag:
texMag = 1000 # I'm told this is latex's default value
if not imageFormat:
imageFormat = 'jpg'
path = tmpdir # + hdf.getValue("project.name.encoded", "default")
# create temporary directory if necessary
try:
if not os.path.exists(path):
mkdir(path)
except:
return "Unable to create temporary directory " + path
# generate final image name. Use a hash of the parameters which affect
# the image, so we don't have to recreate it unless they change.
hash = sha.new(texData)
# include some options in the hash, as they affect the output image
hash.update( "%d %d" % (density, int(texMag)) )
hash.update( outputVersion )
name = hash.hexdigest()
imageFile = "%s/%s.%s" % (imagePath, name, imageFormat)
log = "<br>"
if not os.path.exists(imageFile):
# latex writes out lots of stuff to the current directory, so we have
# to run it from there.
cwd = os.getcwd()
os.chdir(path)
texFile = name + ".tex"
makeTexFile(texFile, texData, mathMode, texMag)
# the output from latex on stdout seems to cause problems, so sent it
# to /dev/null
cmd = "%s %s > /dev/null" % (latexPath, texFile)
log += execprog( cmd )
os.chdir(cwd)
# use dvips to convert to eps
dviFile = "%s/%s.dvi" % (path, name)
epsFile = "%s/%s.eps" % (path, name)
cmd = "%s -q -D 600 -E -n 1 -p 1 -o %s %s" % (dvipsPath, epsFile, dviFile)
log += execprog( cmd )
# and finally, ImageMagick to convert from eps to [imageFormat] type
cmd = "%s -antialias -density %ix%i %s %s" % (convertPath, density, density, epsFile, imageFile)
log += execprog( cmd )
if fleqnMode:
margin = " margin-left: %s" % fleqnIndent
else:
margin = ""
html = "<img src='%s/%s.%s' border='0' style='vertical-align: middle;%s' alt='formula' />" % (displayPath, name, imageFormat, margin)
return html
def execprog(cmd):
os.system( cmd )
return cmd + "<br>"
def makeTexFile(texFile, texData, mathMode, texMag):
tex = "\\batchmode\n"
tex += "\\documentclass{article}\n"
tex += "\\usepackage{amsmath}\n"
tex += "\\usepackage{amssymb}\n"
tex += "\\usepackage{epsfig}\n"
tex += "\\pagestyle{empty}\n"
tex += "\\mag=%s\n" % texMag
# matrix macro
tex += "\\newcommand{\\mat}[2][rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr]{\n"
tex += " \\left[\\begin{array}{#1}\n"
tex += " #2\\\\\n"
tex += " \\end{array}\n"
tex += " \\right]}\n"
# start the document
tex += "\\begin{document}\n"
if mathMode:
tex += "$$\n"
tex += "%s\n" % texData
if mathMode:
tex += "$$\n"
tex += "\\pagebreak\n"
tex += "\\end{document}\n"
FILE = open(texFile, "w")
FILE.write( tex )
FILE.close()
# arguments start with "#" on the beginning of a line
def execute(hdf, text, env):
# TODO: unescape all html escape codes
text = text.replace("&", "&")
# defaults
density = 100
mathMode = 1 # default to using display-math mode for LaTeX processing
displayMode = 0 # default to generating inline formula
fleqnMode = env.get_config('latex', 'fleqn')
centerImage = 0
indentImage = 0
indentClass = ""
# find some number of arguments, followed by the formula
command = re.compile('^\s*#([^=]+)=?(.*)')
formula = ""
errors = ""
for line in text.split("\n"):
m = command.match(line)
if m:
if m.group(1) == "density":
density = int(m.group(2))
elif m.group(1) == "nomode":
mathMode = 0
elif m.group(1) == "center":
centerImage = 1
fleqnMode = 0
elif m.group(1) == "indent":
indentImage = 1
indentClass = m.group(2)
elif m.group(1) == "display":
displayMode = 1
elif m.group(1) == "fleqn":
displayMode = 1
fleqnMode = 1
else:
errors = '<br>Unknown <i>formula</i> command "%s"<br>' % m.group(1)
else:
formula += line + "\n"
# Set display and fleqn defaults
if displayMode:
if fleqnMode:
centerImage = 0
else:
centerImage = 1
# Render formula
format = '%s'
if centerImage:
format = '<center>%s</center>' % format
if indentImage:
if indentClass:
format = '<p class="%s">%s</p>' % (indentClass, format)
else:
format = '<p>%s</p>' % format
result = errors + render(hdf, env, formula, density, fleqnMode, mathMode)
return format % result
|
UTF-8
|
Python
| false | false | 2,013 |
7,112,465,892,157 |
019a4c7ddf56fd2f9d4f59f9c029054fafe45447
|
3bd23f869d82c2082c35aaf5c0cf80686ab9874d
|
/findTicket.py
|
713eff32355bff9b8d05a088278c52a2489c5cde
|
[] |
no_license
|
KIDJourney/Python-Scripts
|
https://github.com/KIDJourney/Python-Scripts
|
22b3af965de01e87bcdef1ef3f35adae93c0de2e
|
b0ba173a2d9944e4a5731877d3324c285545a7b7
|
refs/heads/master
| 2021-01-18T02:17:21.915434 | 2014-12-30T04:26:49 | 2014-12-30T04:26:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#-*- coding: UTF-8 -*-
import sys, os
import urllib2
import ConfigParser
import json
import time
import smtplib
from datetime import datetime
class FindYW(object):
def __init__(self):
self.base_dir = os.path.dirname(__file__)
config = ConfigParser.RawConfigParser()
config.read(os.path.join(self.base_dir, "config.ini"))
self.target_email = config.get('ticket', 'target_email')
self.query_url = config.get('ticket', 'query_url')
self.train_code = config.get('ticket', 'train_code')
self.ticket_type = config.get('ticket', 'ticket_type')
self.email_password = config.get('ticket', 'password')
self.send_email = False
self.loop()
def loop(self):
while (not self.send_email):
self.seek()
time.sleep(10)
sys.exit(0)
def getTrain(self):
now = datetime.now()
print now
data_json = urllib2.urlopen(self.query_url).read()
data = json.loads(data_json)
for train in data['data']:
if train['queryLeftNewDTO']['station_train_code'] == self.train_code:
self.train = train['queryLeftNewDTO']
break
def sendEmail(self):
smtp = smtplib.SMTP()
password = self.email_password
msg = 'Subject: 主人主人~ 人家新发现了一张车票,请赶快去抢吧~ 喵呜~~~'
smtp.connect('smtp.qq.com', '25')
smtp.login('hetong583', password)
smtp.sendmail('hetong583@qq.com', self.target_email, msg)
smtp.sendmail('hetong583@qq.com', 'hetong583@qq.com', msg)
smtp.quit()
def seek(self):
try:
self.getTrain()
num = self.train[self.ticket_type]
none = u'\u65e0'
if num != none:
self.sendEmail()
self.send_email = True
else:
print "no ticket, do next try after 10 seconds"
except KeyError:
print 'Error:', 'query failed'
except Exception as e:
print 'Error:', e
FindYW()
|
UTF-8
|
Python
| false | false | 2,014 |
18,863,496,378,268 |
a4794ebe2514b313de7201a67ed545c0c805b54e
|
3c7170e5e4518f7bdef0260a1980d96af3da5cd5
|
/config.py
|
b4923bf7b680e32eb60fe63c4397056eca011a4c
|
[] |
no_license
|
yhan819/health_check
|
https://github.com/yhan819/health_check
|
05dbedbe6a08f1cf6ffb1e0d59f0ba9a01ffa497
|
342136669dc2f2df0357848b1dafb7afccfbb307
|
refs/heads/master
| 2020-05-29T12:33:20.065901 | 2013-07-03T18:01:15 | 2013-07-03T18:01:15 | 11,031,749 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
SERVICES = {
"learning":{"host":"50.17.210.180", "port":5001}, #learning service
"email":{"host":"50.17.210.180", "port":5567}, #email service (not connected)
}
def get_service(service):
return SERVICES[service]
|
UTF-8
|
Python
| false | false | 2,013 |
15,281,493,657,927 |
49f21490be93c58140c030c5bc36796dcb8d3178
|
bf5da2d34d78ca87b89c2b007cda75be2e7ba8e6
|
/2013-05-15_fizzbuzz/test_fizzbuzz.py
|
94590131d6c2de0cccc5d9fa6f412ca7e59a3d6b
|
[] |
no_license
|
tonnydourado/dojo-unioeste
|
https://github.com/tonnydourado/dojo-unioeste
|
a007215cf6c09b29ac765b6056f7fae1ac65697f
|
167145b810e185382c5fd40ba95bc075e2c1b68e
|
refs/heads/master
| 2021-01-19T06:13:32.591168 | 2013-05-20T19:53:39 | 2013-05-20T19:53:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from fizzbuzz import fizzbuzz
import unittest
class Teste(unittest.TestCase):
def setUp(self):
self.fizzbuzz = fizzbuzz(20)
def test_fizz(self):
self.assertEqual(self.fizzbuzz[2], 'fizz')
def test_buzz(self):
self.assertEqual(self.fizzbuzz[4], 'buzz')
def test_number(self):
self.assertEqual(self.fizzbuzz[6], 7)
def test_fizzbuzz(self):
self.assertEqual(self.fizzbuzz[14], 'fizzbuzz')
if __name__ == '__main__':
unittest.main()
|
UTF-8
|
Python
| false | false | 2,013 |
12,764,642,832,776 |
319d2570035c336605584645cbd7e5abb5f2546f
|
92a026bbfdaa6bab9349e0985c44681041f9c905
|
/RSGraviton/RSAnalyzer/python/Fall10/W3j_100to300_cff.py
|
e266714c015718b5241cc417547e0380354ab167
|
[] |
no_license
|
trtomei/usercode
|
https://github.com/trtomei/usercode
|
63f7d912b8ac2c425348ecb1fc7fb5eda6d89179
|
9e14c1d93c9f868747e180ca7adfa3638ea52eb0
|
refs/heads/master
| 2020-05-14T21:52:08.941759 | 2012-05-14T19:16:01 | 2012-05-14T19:16:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import FWCore.ParameterSet.Config as cms
maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
readFiles = cms.untracked.vstring()
secFiles = cms.untracked.vstring()
source = cms.Source ('PoolSource',fileNames = readFiles, secondaryFileNames = secFiles)
readFiles.extend( [
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_4_1_6XO.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_8_1_eKF.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_6_1_J1r.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_9_1_tvK.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_3_1_xfV.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_2_1_9r7.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_5_1_8B6.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_7_1_uiQ.root",
"/store/user/tomei/Fall2010Backgrounds/W3j_100to300/W3j_100to300/patTuple_1_1_qgJ.root",
]);
|
UTF-8
|
Python
| false | false | 2,012 |
11,682,311,081,680 |
d9be67421be1e7d9e3eeff7bef871e25b9810dee
|
00cfd94166c8eb36105677e38a4ee8d7328bbf87
|
/src/get_asr_output.py
|
1a343b1d29433673241e5ada02f12d0898fecf0f
|
[] |
no_license
|
pgoel92/AutoAnnotator
|
https://github.com/pgoel92/AutoAnnotator
|
1c3c65c0984b60f3bca723be2fbf3ac4980398ae
|
c1d52ce3591f2590d90df1388b04040d1ae3d6ef
|
refs/heads/master
| 2021-01-10T21:24:22.886926 | 2014-11-26T01:02:25 | 2014-11-26T01:02:25 | 26,790,615 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
import sys
def list_decrement(ls,x):
newls = []
for elt in ls:
newls.append(str(int(elt)-x));
return newls
def list_increment(ls,x):
newls = []
for elt in ls:
newls.append(str(int(elt)+x));
return newls
try:
f = open('../etc/'+ sys.argv[1] + '/seg.txt')
tr = f.readlines()
f.close();
words = []
SFrm = []
EFrm = []
previous = 0;
p=0
f = open('../etc/' + sys.argv[1] + '/decoded','w')
for phrase in tr:
p = p+1
phrase = phrase.split();
words = phrase[12::4]
#SFrm = list_increment(phrase[9::4],previous)
EFrm = list_increment(list_decrement(phrase[13::4],1),previous);
previous = int(EFrm[-1]) + 1;
for i in range(0,len(words)-1):
if words[i] != '<sil>':
if len(words[i]) > 3:
if words[i][-2] == '2' or words[i][-2] == '3':
f.write(words[i][:-3]+" ");
else:
f.write(words[i]+" ");
else:
f.write(words[i]+" ");
words = []
SFrm = []
EFrm = []
f.close();
except IOError:
sys.exit(1);
|
UTF-8
|
Python
| false | false | 2,014 |
15,307,263,463,667 |
d203cd81261ebaeb215818c45e261cbd79fb791c
|
80b26c59b5dfd1b4546190e317b86ab2fc006ebe
|
/bamboo/tests/test_profile.py
|
6a16d811d1149c2a62def4d30a8b28536ef5967a
|
[
"BSD-3-Clause"
] |
permissive
|
biswapanda/bamboo
|
https://github.com/biswapanda/bamboo
|
032a17d800abb086007c4ffcb2f8e70120a19dc8
|
72fc260822a27ce52cbe65de178f8fa1b60311f3
|
refs/heads/master
| 2020-12-31T04:06:12.145582 | 2013-12-08T09:45:57 | 2013-12-08T09:45:57 | 15,037,628 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import json
import os
from tempfile import NamedTemporaryFile
from pandas import concat
from bamboo.controllers.datasets import Datasets
from bamboo.models.dataset import Dataset
from bamboo.tests.decorators import run_profiler
from bamboo.tests.mock import MockUploadedFile
from bamboo.tests.test_base import TestBase
class TestProfile(TestBase):
TEST_CASE_SIZES = {
'tiny': (1, 1),
'small': (2, 2),
'large': (4, 40),
}
def setUp(self):
TestBase.setUp(self)
self.datasets = Datasets()
self.tmp_file = NamedTemporaryFile(delete=False)
def tearDown(self):
os.unlink(self.tmp_file.name)
def _expand_width(self, df, exponent):
for i in xrange(0, exponent):
other = df.rename(
columns={col: '%s-%s' % (col, idx) for (idx, col) in
enumerate(df.columns)})
df = df.join(other)
df.rename(columns={col: str(idx) for (idx, col) in
enumerate(df.columns)}, inplace=True)
return df
def _grow_test_data(self, dataset_name, width_exp, length_factor):
df = self.get_data(dataset_name)
df = self._expand_width(df, width_exp)
return concat([df] * length_factor)
def test_tiny_profile(self):
self._test_profile('tiny')
def test_small_profile(self):
self._test_profile('small')
def test_large_profile(self):
self._test_profile('large')
@run_profiler
def _test_profile(self, size):
print 'bamboo/bamboo: %s' % size
self._test_create_data(*self.TEST_CASE_SIZES[size])
print 'saving dataset'
self._test_save_dataset()
self._test_get_info()
self._test_get_summary()
self._test_get_summary_with_group('province')
self._test_get_summary_with_group('school_zone')
def _test_create_data(self, width_exp, length_factor):
self.data = self._grow_test_data(
'kenya_secondary_schools_2007.csv', width_exp, length_factor)
print 'bamboo/bamboo rows: %s, columns: %s' % (
len(self.data), len(self.data.columns))
def _test_save_dataset(self):
self.data.to_csv(self.tmp_file)
self.tmp_file.close()
mock_uploaded_file = MockUploadedFile(open(self.tmp_file.name, 'r'))
result = json.loads(self.datasets.create(csv_file=mock_uploaded_file))
self.assertTrue(isinstance(result, dict))
self.assertTrue(Dataset.ID in result)
self.dataset_id = result[Dataset.ID]
def _test_get_info(self):
result = json.loads(self.datasets.info(self.dataset_id))
self.assertTrue(isinstance(result, dict))
def _test_get_summary(self):
result = json.loads(self.datasets.summary(
self.dataset_id,
select=self.datasets.SELECT_ALL_FOR_SUMMARY))
self.assertTrue(isinstance(result, dict))
def _test_get_summary_with_group(self, group):
result = json.loads(self.datasets.summary(
self.dataset_id, group=group,
select=self.datasets.SELECT_ALL_FOR_SUMMARY))
self.assertTrue(isinstance(result, dict))
|
UTF-8
|
Python
| false | false | 2,013 |
13,219,909,370,279 |
8de8ce5e9b2f647ac3804cb3626af553002c19a9
|
8b5cf67adfd73d30d94ba40abc8b21ed099a59f5
|
/resources/libs/mc.py
|
2ca8245f91b388684a9665d893df0c01312ba382
|
[] |
no_license
|
HooliganHarls/MLB2.bundle
|
https://github.com/HooliganHarls/MLB2.bundle
|
44dd1ed9ef9cec9a5814d424bbabc1d05196e033
|
936a83885cb813e2602d59041348c9a47f1619a8
|
refs/heads/master
| 2021-01-20T23:44:37.860271 | 2011-03-26T19:12:51 | 2011-03-26T19:12:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os, sys, stat, re
import xbmc, xbmcgui, xbmcaddon
import urllib2, binascii, urllib
from BeautifulSoup import BeautifulStoneSoup
try:
import cPickle as pickle
except:
import pickle
#import types
class Window(xbmcgui.WindowXML):
def __init__( self, start, path, skin):
xbmcgui.WindowXML.__init__( self, start, path, skin )
self.doModal()
def load(var):
if var == 'id':
fileid = os.path.join(GetTempDir(),'boxee.init')
if os.access(fileid, os.F_OK):
return open(fileid, 'r').read()
elif var == 'windows':
filewindow = os.path.join(GetTempDir(),'boxee.windows')
if os.access(filewindow, os.F_OK):
data = open(filewindow, 'r').read()
return pickle.loads(binascii.unhexlify(data))
def start(addon_id, addon_windows):
fileid = os.path.join(GetTempDir(),'boxee.init')
file = open(fileid, 'w')
file.write(addon_id)
file.close()
filewindow = os.path.join(GetTempDir(),'boxee.windows')
data = pickle.dumps(addon_windows)
file = open(filewindow, 'w')
file.write(binascii.hexlify(data))
file.close()
def ListStart(obj, var):
settings = GetLocalConfig()
try: listcontrol = int(settings.GetValue('listcontrol'))
except: listcontrol = 0
position = obj.getControl(var).getSelectedPosition()
if int(position) == 0 and int(position) == listcontrol:
settings.SetValue('listcontrol', str(position))
return True
else:
settings.SetValue('listcontrol', str(position))
return False
def ListEnd(obj, var):
settings = GetLocalConfig()
try: listcontrol = int(settings.GetValue('listcontrol'))
except: listcontrol = 0
position = obj.getControl(var).getSelectedPosition()
size = obj.getControl(var).size() - 1
if int(position) == int(size) and int(position) == listcontrol:
settings.SetValue('listcontrol', str(position))
return True
else:
settings.SetValue('listcontrol', str(position))
return False
#Boxee mc Emulation
class Http(object):
def __init__(self):
self.headers = {}
def SetUserAgent(self, var):
self.headers['User-Agent'] = var
def SetHttpHeader(self, var1, var2):
self.headers[var1] = var2
def Post(self, url, params):
values = params.split('&')
post = {}
for value in values:
id, val = value.split('=')
post[id] = val
encoded_params = urllib.urlencode( post )
opener = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( opener )
headers = [(x, y) for x, y in self.headers.iteritems()]
opener.addheaders = headers
_file = opener.open( url, encoded_params )
response = _file.read()
_file.close()
return response
def Get(self, url):
opener = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( opener )
headers = [(x, y) for x, y in self.headers.iteritems()]
opener.addheaders = headers
_file = opener.open( url )
response = _file.read()
_file.close()
return response
class GetApp(object):
def GetLocalConfig(self):
return GetLocalConfig()
def GetAppDir(self):
return os.getcwd().replace(";","")
def GetId(self):
return load('id')
def CloseWindow():
window.close()
def GetActiveWindow():
return GetWindow()
def GetInfoString(var):
return xbmc.getInfoLabel(var)
def GetLocalizedString(int):
return xbmc.getLocalizedString(int)
def ShowDialogWait():
progress = xbmcgui.DialogProgress()
progress.create('XBMC - Addon', 'Loading...')
return progress
#xbmcgui.lock()
def HideDialogWait(obj):
#xbmcgui.unlock()
obj.close()
def ShowDialogNotification(var):
xbmc.executebuiltin('Notification("Info",'+var+',1500 )')
def ShowDialogOk(title, var):
dialog = xbmcgui.Dialog()
return dialog.ok(title, var)
def ShowDialogConfirm(title, var, no='No', yes='Yes'):
dialog = xbmcgui.Dialog()
return dialog.yesno(heading=title, line1=var, nolabel=no, yeslabel=yes)
def LogDebug(var):
xbmc.log(msg=var,level=xbmc.LOGDEBUG)
def LogError(var):
xbmc.log(msg=var,level=xbmc.LOGERROR)
def LogInfo(var):
xbmc.log(msg=var,level=xbmc.LOGINFO)
def ShowDialogKeyboard(title='', var='', bool=False):
keyboard = xbmc.Keyboard(var, title, bool)
keyboard.doModal()
if keyboard.isConfirmed(): return keyboard.getText()
else: return
class GetLocalConfig(object):
def __init__(self):
self.id = load('id')
if len(self.id) > 2:
self.settings = xbmcaddon.Addon(id=self.id)
def GetValue(self, val):
data = val.split('{')
i = 0
if len(data) > 1:
i = data[1][:-1]
val_id = data[0]
else: val_id = val
return self.settings.getSetting(id=val_id+'{'+str(i)+'}')
def SetValue(self, val1, val2):
if not '{' in val1: stringid = val1+'{0}'
else: stringid = val1
self.settings.setSetting(id=stringid, value=val2)
def PushBackValue(self, val1, val2):
i = 0
while True:
if self.settings.getSetting(id=val1+'{'+str(i)+'}') != '':
i += 1
else:
break
self.settings.setSetting(id=val1+'{'+str(i)+'}', value=val2)
def Reset(self, val):
if '{' in val: stringid = val.split('{')[0]
else: stringid = val
i = 0
list = []
while True:
if self.settings.getSetting(id=stringid+'{'+str(i)+'}') != '':
list.append(i)
i += 1
else:
break
if len(list) > 0:
for i in list:
self.settings.setSetting(id=stringid+'{'+str(i)+'}', value='')
def ResetAll(self):
path = os.path.join(xbmc.translatePath('special://userdata'), 'addon_data', self.id, 'settings.xml')
if os.access(path, os.F_OK):
os.chmod(path, stat.S_IWUSR)
os.remove(path)
def GetTempDir():
return xbmc.translatePath('special://temp')
class ActivateWindow(object):
def __init__(self, window_id, var=''):
self.settings = xbmcaddon.Addon(id=load('id'))
self.modules = {}
self.windows = load('windows')
self.load()
self.run(str(window_id), var)
def path(self):
return self.settings.getAddonInfo('path')
def run(self, id, var):
ui = self.modules[id].skin( self.windows[id]+'.xml' , self.path(), "Default", var)
del ui
def load(self):
for key in self.windows.keys():
importstring = 'skin.' + self.windows[key]
mod = __import__(importstring)
components = importstring.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
self.modules[key] = mod
class GetWindow(object):
def __init__( self, int=''):
self.xbmc = window
def GetControl(self, var):
return Control(self.xbmc, self.xbmc.getControl(var), var)
def GetLabel(self, var):
return Control(self.xbmc, self.xbmc.getControl(var), var)
def GetImage(self, var):
return Control(self.xbmc, self.xbmc.getControl(var), var)
def GetList(self, var):
return Listmc(self.xbmc, self.xbmc.getControl(var), var)
class Control(object):
def __init__( self, window, control, var):
self.window = window
self.control = control
self.id = var
def SetVisible(self, var):
self.control.setVisibleCondition(str(var))
def SetSelected(self, bool):
self.control.setSelected(bool)
def SetTexture(self, var):
self.control.setImage(var)
def SetLabel(self, var):
self.control.setLabel(var)
def GetLabel(self):
return self.control.getLabel()
def SetFocus(self):
self.window.setFocus(self.control)
def IsVisible(self):
return xbmc.getCondVisibility( "Control.IsVisible(%i)" % self.id )
class Listmc(object):
def __init__( self, window, control, var):
self.window = window
self.list = control
self.id = var
self.infolabels = {'genre':'genre','year':'year','episode':'episode','season':'season','top250':'top250','tracknumber':'tracknumber','contentrating':'rating','watched':'watched','viewcount':'playcount',
'overlay':'overlay','cast':'cast','castandrole':'castandrole','director':'director','mpaa':'mpaa','plot':'plot','plotoutline':'plotoutline','title':'title','duration':'duration','studio':'studio',
'tagline':'tagline','writer':'writer','tvshowtitle':'tvshowtitle','premiered':'premiered','status':'status','code':'code','aired':'aired','credits':'credits','lastplayed':'lastplayed','album':'album','votes':'votes','trailer':'trailer',
'artist':'artist','lyrics':'lyrics', 'picturepath':'picturepath', 'exif':'exif'}
def SetContentURL(url):
req = urllib2.Request(url)
response = urllib2.urlopen(req)
link=response.read()
response.close()
soup = BeautifulStoneSoup(link, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
channel = soup.channel.title.string
channel_link = soup.channel.link.string
channel_description = soup.channel.description.string
try:
channel_image = soup.channel.image.string
except:
channel_image = ''
try:
channel_language = soup.channel.language.string
except:
channel_language = ''
try:
channel_expiry = soup.channel('boxee:expiry')[0].string
except:
channel_expiry = ''
items = soup('item')
for item in items:
try:
title = item.title.string
except:
title = ''
try:
link = item.link.string
except:
link = ''
try:
guid = item.guid.string
except:
guid = ''
try:
description = item.description.string
except:
description = ''
try:
custom_display = item('boxee:property',attrs={'name' : "custom:display"})[0].string
except:
custom_display = ''
try:
custom_myteam = item('boxee:property', attrs={'name' : "custom:myteam"})[0].string
except:
custom_myteam = ''
try:
thumbnail = item('media:thumbnail')[0]['url']
except:
thumbnail = ''
try:
genre = item('media:category', attrs={'scheme' : 'urn:boxee:genre'})[0].string
except:
genre = ''
try:
boxee_type = item('boxee:media-type')[0]['type']
except:
boxee_type = ''
try:
release_date = item('boxee:release-date')[0].string
except:
release_date = ''
try:
episode = item('media:category', attrs={'scheme' : "urn:boxee:episode"})[0].string
except:
episode = ''
try:
season = item('media:category', attrs={'scheme' : "urn:boxee:season"})[0].string
except:
season = ''
try:
media_url = item('media:content')[0]['url']
except:
media_url = ''
try:
media_duration = item('media:content')[0]['duration']
except:
media_duration = ''
try:
media_type = item('media:content')[0]['type']
except:
media_type = ''
try:
media_height = item('media:content')[0]['height']
except:
media_height = ''
try:
media_width = item('media:content')[0]['width']
except:
media_width = ''
try:
media_lang = item('media:content')[0]['lang']
except:
media_lang = ''
def GetFocusedItem(self):
return self.list.getSelectedPosition()
def SetItems(self, lst):
xbmcgui.lock()
self.list.reset()
for i in lst:
itm = i.list
item=xbmcgui.ListItem(label=itm['Label'])
infolist = {}
for key in itm.keys():
if key == 'Label':
item.setLabel(itm[key])
elif key == 'Thumbnail':
item.setThumbnailImage(itm[key])
elif key == 'Icon':
item.setIconImage(itm[key])
else:
if key == 'path':
item.setPath(itm[key])
if key in self.infolabels.keys():
infolist[self.infolabels[key]] = itm[key]
item.setProperty(key, itm[key])
self.list.addItem(item)
xbmcgui.unlock()
def SetFocusedItem(self, int):
self.list.selectItem(int)
def GetItem(self, int):
return ListInfo(self.list.getListItem(int))
def GetItems(self):
listitems = []
for i in range(self.list.size()):
listitems.append(ListInfo((self.list.getListItem(i))))
return listitems
def GetSelected(self):
return ListInfo(self.list.getSelectedItem().isSelected())
def ListItems():
return []
class ListInfo(object):
def __init__( self, item):
self.item = item
def GetLabel(self):
try:
return self.item.getLabel()
except:
return ""
def GetThumbnail(self):
try:
return self.item.getProperty('Thumbnail')
except:
return ""
def GetPath(self):
try:
return self.item.getProperty('path')
except:
return ""
def GetAlbum(self):
try:
return self.item.getProperty('album')
except:
return ""
def GetArtist(self):
try:
return self.item.getProperty('artist')
except:
return ""
def GetAuthor(self):
try:
return self.item.getProperty('author')
except:
return ""
def GetComment(self):
try:
return self.item.getProperty('comment')
except:
return ""
def GetContentType(self):
try:
return self.item.getProperty('mime')
except:
return ""
def GetDate(self):
try:
return self.item.getProperty('date')
except:
return ""
def GetDescription(self):
try:
return self.item.getProperty('description')
except:
return ""
def GetDirector(self):
try:
return self.item.getProperty('director')
except:
return ""
def GetDuration(self):
try:
return self.item.getProperty('duration')
except:
return ""
def GetEpisode(self):
try:
return self.item.getProperty('episode')
except:
return ""
def GetGenre(self):
try:
return self.item.getProperty('genre')
except:
return ""
def GetIcon(self):
try:
return self.item.getProperty('Icon')
except:
return ""
def GetKeywords(self):
try:
return self.item.getProperty('keywords')
except:
return ""
def GetProviderSource(self):
try:
return self.item.getProperty('providersource')
except:
return ""
def GetContentRating(self):
try:
return self.item.getProperty('contentrating')
except:
return ""
def GetSeason(self):
try:
return self.item.getProperty('season')
except:
return ""
def GetStarRating(self):
try:
return self.item.getProperty('starrating')
except:
return ""
def GetStudio(self):
try:
return self.item.getProperty('studio')
except:
return ""
def GetTagLine(self):
try:
return self.item.getProperty('tagline')
except:
return ""
def GetTrackNumber(self):
try:
return self.item.getProperty('tracknumber')
except:
return ""
def GetTVShowTitle(self):
try:
return self.item.getProperty('tvshowtitle')
except:
return ""
def GetTiSetViewCounttle(self):
try:
return self.item.getProperty('viewcount')
except:
return ""
def GetWriter(self):
try:
return self.item.getProperty('writer')
except:
return ""
def GetYear(self):
try:
return self.item.getProperty('year')
except:
return ""
def GetProperty(self, var):
try:
return self.item.getProperty(var)
except:
return ""
class ListItem(object):
MEDIA_UNKNOWN = 'video'
MEDIA_AUDIO_MUSIC = 'music'
MEDIA_AUDIO_SPEECH = 'music'
MEDIA_AUDIO_RADIO = 'music'
MEDIA_AUDIO_OTHER = 'music'
MEDIA_VIDEO_MUSIC_VIDEO = 'video'
MEDIA_VIDEO_FEATURE_FILM = 'video'
MEDIA_VIDEO_TRAILER = 'video'
MEDIA_VIDEO_EPISODE = 'video'
MEDIA_VIDEO_CLIP = 'video'
MEDIA_VIDEO_OTHER = 'video'
MEDIA_PICTURE = 'pictures'
MEDIA_FILE = 'pictures'
def __init__( self, var ):
self.list = {}
self.type = var
def SetLabel(self, var):
self.list['Label'] = var
def SetTitle(self, var):
self.list['title'] = var
def SetThumbnail(self, var):
self.list['Thumbnail'] = var
def SetPath(self, var):
self.list['path'] = var
def SetProperty(self, var1, var2):
self.list[var1] = var2
def SetAddToHistory(self, var):
pass
def SetAlbum(self, var):
self.list['album'] = var
def SetArtist(self, var):
self.list['artist'] = var
def SetAuthor(self, var):
self.list['author'] = var
def SetComment(self, var):
paself.list['comment'] = varss
def SetContentType(self, var):
self.list['mime'] = var
def SetDate(self, var):
self.list['date'] = var
def SetDescription(self, var):
self.list['description'] = var
def SetDirector(self, var):
self.list['director'] = var
def SetDuration(self, var):
self.list['duration'] = var
def SetEpisode(self, var):
self.list['episode'] = var
def SetGenre(self, var):
self.list['genre'] = var
def SetIcon(self, var):
self.list['Icon'] = var
def SetKeywords(self, var):
self.list['keywords'] = var
def SetProviderSource(self, var):
self.list['providersource'] = var
def SetContentRating(self, var):
self.list['contentrating'] = var
def SetExternalItem(self, var):
pass
def SetReportToServer(self, var):
pass
def SetSeason(self, var):
self.list['season'] = var
def SetStarRating(self, var):
self.list['starrating'] = var
def SetStudio(self, var):
self.list['studio'] = var
def SetTagLine(self, var):
self.list['tagline'] = var
def SetTrackNumber(self, var):
self.list['tracknumber'] = var
def SetTVShowTitle(self, var):
self.list['tvshowtitle'] = var
def SetTiSetViewCounttle(self, var):
self.list['viewcount'] = var
def SetWriter(self, var):
self.list['writer'] = var
def SetYear(self, var):
self.list['year'] = var
def GetPlayer(var=xbmc.PLAYER_CORE_AUTO):
return Player(var)
class Player(object):
def __init__( self, var):
self.xbmc = xbmc.Player(var)
self.infolabels = {'genre':'genre','year':'year','episode':'episode','season':'season','top250':'top250','tracknumber':'tracknumber','contentrating':'rating','watched':'watched','viewcount':'playcount',
'overlay':'overlay','cast':'cast','castandrole':'castandrole','director':'director','mpaa':'mpaa','plot':'plot','plotoutline':'plotoutline','title':'title','duration':'duration','studio':'studio',
'tagline':'tagline','writer':'writer','tvshowtitle':'tvshowtitle','premiered':'premiered','status':'status','code':'code','aired':'aired','credits':'credits','lastplayed':'lastplayed','album':'album','votes':'votes','trailer':'trailer',
'artist':'artist','lyrics':'lyrics', 'picturepath':'picturepath', 'exif':'exif'}
def Play(self, obj):
#if isinstance(lst, types.ListType):
# for i in lst:
# items.append(self.convertitem(i.list))
#else:
url, item = self.convertitem(obj)
self.xbmc.play(url, item, False)
def convertitem(self, i):
itm = i.list
item=xbmcgui.ListItem(label=itm['Label'])
infolist = {}
try: type = itm['mime']
except: type = ''
if type in ('video/x-ms-asf', 'video/x-ms-asx'):
itm['path'] = self.CheckAsx(itm['path'])
if ('.asx' or '.asf') in itm['path']:
itm['path'] = self.CheckAsx(itm['path'])
for key in itm.keys():
if key == 'Label':
item.setLabel(itm[key])
elif key == 'Thumbnail':
item.setThumbnailImage(itm[key])
elif key == 'Icon':
item.setIconImage(itm[key])
else:
if key == 'path':
item.setPath(itm[key])
if key in self.infolabels.keys():
infolist[self.infolabels[key]] = itm[key]
item.setProperty(key, itm[key])
if infolist:
item.setInfo(i.type, infolist)
return itm['path'], item
def CheckAsx(self, url):
http = Http()
data = http.Get(url).decode('utf-8')
try:
urlplay = re.compile('[Rr]ef href="mms://([^"]+)"', re.DOTALL + re.IGNORECASE + re.M).findall(data)[0]
urlplay = 'mms://'+ urlplay
except:
try:
urlplay = re.compile('http\://(.*?)"', re.DOTALL + re.IGNORECASE + re.M).findall(data)[0]
urlplay = 'http://'+ urlplay
except:
urlplay = url
return urlplay
def GetPlayingItem(self):
return self.xbmc.getPlayingFile()
def GetTime(self):
return self.xbmc.getTime()
def GetTotalTime(self):
return self.xbmc.getTotalTime()
def GetVolume(self):
#possibility to use JSON_RPC - http://wiki.xbmc.org/index.php?title=JSON_RPC#XBMC.GetVolume
pass
def IsCaching(self):
pass
def IsForwarding(self):
pass
def IsPaused(self):
pass
def IsPlaying(self):
return self.xbmc.isPlaying()
def IsPlayingAudio(self):
return self.xbmc.isPlayingAudio()
def IsPlayingVideo(self):
return self.xbmc.isPlayingVideo()
def LockPlayerAction(self):
pass
def Pause(self):
return self.xbmc.pause()
def Player():
return Player()
def PlayInBackground(self):
pass
def PlayNext(self):
return self.xbmc.playnext()
def PlayPrevious(self):
return self.xbmc.playprevious()
def PlaySelected(self):
return self.xbmc.playselected()
def PlayWithActionMenu(self):
pass
def SeekTime(self):
return self.xbmc.seekTime()
def SetLastPlayerAction(self):
pass
def SetLastPlayerEvent(self):
pass
def SetVolume(self, int):
xbmc.executebuiltin('SetVolume('+str(int)+')')
def Stop(self):
return self.xbmc.stop()
def ToggleMute(self):
xbmc.executebuiltin('Mute')
#Keyboard variables
ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_UP = 3
ACTION_MOVE_DOWN = 4
ACTION_PAGE_UP = 5
ACTION_PAGE_DOWN = 6
ACTION_SELECT_ITEM = 7
ACTION_HIGHLIGHT_ITEM = 8
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_SHOW_INFO = 11
ACTION_PAUSE = 12
ACTION_STOP = 13
ACTION_NEXT_ITEM = 14
ACTION_PREV_ITEM = 15
ACTION_CONTEXT_MENU = 117
ACTION_MOUSE_MOVE = 90
ACTION_MOUSE_MOVE_WIN = 107
ACTION_MOUSE_SCROLL_UP = 104
ACTION_MOUSE_SCROLL_DOWN = 105
ACTION_MOUSE_SCROLL_BAR = 106
ACTION_UPDOWN = (ACTION_MOVE_UP, ACTION_MOVE_DOWN, ACTION_PAGE_DOWN, ACTION_PAGE_UP)
ACTION_LEFTRIGHT = (ACTION_MOVE_LEFT, ACTION_MOVE_RIGHT)
ACTION_EXIT_CONTROLS = (ACTION_PREVIOUS_MENU, ACTION_PARENT_DIR)
ACTION_CONTEXT_MENU_CONTROLS = (ACTION_CONTEXT_MENU, ACTION_SHOW_INFO)
ACTION_MOUSE_MOVEMENT = (ACTION_MOUSE_MOVE, ACTION_MOUSE_MOVE_WIN, ACTION_MOUSE_SCROLL_DOWN, ACTION_MOUSE_SCROLL_UP, ACTION_MOUSE_SCROLL_BAR)
#Load init
window = ''
|
UTF-8
|
Python
| false | false | 2,011 |
11,690,901,012,612 |
b0f4542cfc95cf8aebb449272c2bee8a5165db44
|
b97a791996e8e91229057d8996681cec7f8bbd72
|
/test/urlmap.py
|
f14a063d6913d13ff34c230377311a3b69eb6723
|
[] |
no_license
|
azer/dasornis
|
https://github.com/azer/dasornis
|
d0db3da1cde75d5c84c456968b3e1a42408fbac7
|
8823beee86f922a61807bd81463127f16ea056f2
|
refs/heads/master
| 2021-01-20T20:56:56.600120 | 2013-10-17T18:29:02 | 2013-10-17T18:29:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import unittest,sys,os.path
sys.path.append(os.path.dirname(__file__)+'../')
from dasornis.core.urlmap import URLMap
import unittest
from pdb import set_trace
reqhandler1,reqhandler2,reqhandler3,reqhandler4,reqhandler5 = lambda *args: args, lambda *args: args, lambda *args: args, lambda *args: args, lambda *args: args
print('=====')
print('HANDLER ID\'S >> 1:',reqhandler1,id(reqhandler1),' 2:',reqhandler2,id(reqhandler2),' 3:',reqhandler3,id(reqhandler3),' 4:',reqhandler3,id(reqhandler5),' 5:',reqhandler5,id(reqhandler5))
print('=====')
map2 = URLMap(
('^/?$',reqhandler4),
('^/cherry/?(\w*)$',reqhandler5)
)
map1 = URLMap(
('^/?$',reqhandler1),
('^/spam/?$',reqhandler2),
('^/\w+\?bar\=(\d+)\&spam=(\w+)\#([a-z]{0,3})([0-9]{0,2})$',reqhandler3),
('^/fr(ui)ts',map2)
)
class UrlTest(unittest.TestCase):
def testMatching(self):
self.assertEqual(map1.match('/')[0],reqhandler1)
self.assertEqual(map1.match('')[0],reqhandler1)
self.assertEqual(map1.match('/spam')[0],reqhandler2)
self.assertEqual(map1.match('/spam/')[0],reqhandler2)
self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey')[0],reqhandler3)
self.assertEqual(map1.match('/foo?bar=12&spam=faking#99')[0],reqhandler3)
self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey99')[0],reqhandler3)
def testSubMapMatching(self):
self.assertEqual(map1.match('/fruits/')[0],reqhandler4)
self.assertEqual(map1.match('/fruits/cherry')[0],reqhandler5)
def testArguments(self):
self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey')[1],('12','faking','hey',''))
self.assertEqual(map1.match('/foo?bar=12&spam=faking#99')[1],('12','faking','','99'))
self.assertEqual(map1.match('/foo?bar=12&spam=faking#hey99')[1],('12','faking','hey','99'))
def testSubMapArguments(self):
self.assertEqual(map1.match('/fruits/')[1],('ui',))
self.assertEqual(map1.match('/fruits/cherry/hellyeah')[1],('ui','hellyeah'))
if __name__ == '__main__':
unittest.main()
|
UTF-8
|
Python
| false | false | 2,013 |
3,075,196,590,684 |
f70ac82613d612c2c48a5f4b1c7190c901fbcb87
|
c7b37206a775b8dc5a54a3cadb6191fee71bfe39
|
/speed-test/run.py
|
1ca1cc709887351c09a29136adeec3299fc51184
|
[
"BSD-2-Clause"
] |
permissive
|
kmackay/emk
|
https://github.com/kmackay/emk
|
bde6d606c7c0e8a33895a0fd2b5027b320e81cd4
|
5b1db66bbaae882cc4a301aced4793d99312b39e
|
refs/heads/master
| 2020-03-25T18:41:45.922911 | 2014-12-20T07:28:04 | 2014-12-20T07:28:04 | 7,495,847 | 10 | 0 | null | false | 2014-12-15T06:02:07 | 2013-01-08T04:58:52 | 2014-07-03T22:24:49 | 2014-12-15T06:02:06 | 1,231 | 3 | 2 | 0 |
Python
| null | null |
#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import re
time_regex = re.compile(r'real\s+(\d+\.\d+)')
tests = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 32, 48, 64]
try:
os.remove("results.txt")
except OSError:
pass
for num in tests:
proc = subprocess.Popen(["../emk", "num=%d" % (num), "clean"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.communicate()
proc = subprocess.Popen(["time", "-p", "../emk", "num=%d" % (num), "log=critical"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc_stdout, proc_stderr = proc.communicate()
match = time_regex.search(proc_stderr)
if match:
with open("results.txt", "a+") as f:
f.write("%d %s\n" % (num * 1000, match.group(1)))
else:
print("Error running test for %d" % (num * 1000))
break
print("Finished %d file compile test" % (num * 1000))
|
UTF-8
|
Python
| false | false | 2,014 |
7,052,336,316,512 |
b1751fd93483b4a161e4be8dce2ddd541911fd1f
|
08c79ea8d1fbba1d48789608d9d13d507f58a68e
|
/slurp.py
|
9061dc62c82b7ed9e7aa8d66a9bf1b3b92983543
|
[] |
no_license
|
mrdan/Slurp
|
https://github.com/mrdan/Slurp
|
9200a4c70e3154a9635b7897039903ebc0ee3028
|
0633002fe9de72ebf0415eef4cac0840e9551aca
|
refs/heads/master
| 2020-12-24T15:32:19.111113 | 2011-04-13T11:36:25 | 2011-04-13T11:36:25 | 1,603,573 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# coding: utf-8
##
## RSS IMG Slurp - Takes an rss feed and takes the first image from each entry (designed for use with google reader "starred item" feeds)
##
#TODO: some feeds stick in 1x1 images, probably for analytics, so they get counted. Annoying. !!seems you need to instal PIL to work with image details!!
import feedparser
import os
import urllib, string, getopt, sys, time, logging, re, random, codecs
from pickle import dump, load
from HTMLParser import HTMLParser
_filedir = "./slurped/"
userid = "000000000000000"
retrieveNum = "1000000000"
blacklist = ["example.com"]
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename='./slurp.log',
filemode='a+')
#
# Gets and parses the feed
def getfeed(feedURL):
feed = feedparser.parse( feedURL )
return feed.entries
#
# Downloads the image from the URL in the feed
def downloadFromURL(URL, downloadName):
downloadDetails = urllib.urlretrieve(URL, _filedir + downloadName)
logging.info("Downloaded " + _filedir + downloadName + " from " + URL)
return downloadDetails
#
# main function
def main():
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
entries = getfeed("http://www.google.com/reader/public/atom/user/" + userid + "/state/com.google/starred?n=" + retrieveNum)
x = 0
print "Working…"
while x < len(entries):
safefilename = ""
fieldtosearch = ""
badtouch = False
extension = ""
# Find which field to search for images
if entries[x].has_key('content'):
fieldtosearch = entries[x].content[0].value
elif entries[x].has_key('summary'):
fieldtosearch = entries[x].summary
# Generate our filename
if entries[x].has_key('link'):
filename = entries[x].links[0].href
safefilename = ''.join(c for c in filename if c in valid_chars)
# Get images
if fieldtosearch != "":
m = re.search("(?<=img\ssrc\=[\x27\x22])[^\x27\x22]*(?=[\x27\x22])", fieldtosearch)
if m != None:
# Check blacklist
for domain in blacklist:
if m.group(0).count(domain) > 0:
logging.info(filename + " is on a blacklisted domain. Ignoring!")
badtouch = True
if badtouch == True:
x = x + 1
continue
# We only want the first image
extension = os.path.splitext(m.group(0))[1]
if safefilename == "":
filename = time.strftime("%H%M%S%d%m%Y")
downloadFromURL(m.group(0), filename +"_" + str(random.randint(1, 1000)) + extension)
else:
downloadFromURL(m.group(0), safefilename + extension)
# Write companion text file
if os.path.exists(_filedir+safefilename+extension):
ourfile = codecs.open(_filedir + safefilename+".txt", 'w', encoding="utf-8")
ourfile.write("## " + entries[x].links[0].href + '\n')
if entries[x].has_key('title'):
ourfile.write("## " + entries[x].title + '\n')
if fieldtosearch != "":
ourfile.write('\n' + strip_tags(fieldtosearch) + '\n')
ourfile.close()
x = x + 1
print "Done!"
#
# Main program body
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,011 |
13,572,096,656,653 |
efb8a1d8a1bbf762a6513acea4ffc1e924804c9b
|
0f6c37a56a36398ed9319ed30e335747f966ca94
|
/makeTools/parseTemplates.py
|
a0aabe371dda16b6dfd8f709bac19395190dc1ae
|
[
"AGPL-3.0-only"
] |
non_permissive
|
Polychart/builder
|
https://github.com/Polychart/builder
|
11fd618765ded27fd3fe2fa7d0225e33885d562a
|
a352ccd62a145c7379e954253c722e9704178f20
|
refs/heads/master
| 2020-05-20T02:24:15.921708 | 2014-07-01T16:51:44 | 2014-07-01T16:51:44 | 16,490,552 | 47 | 15 | null | false | 2016-02-05T17:25:07 | 2014-02-03T19:37:18 | 2016-02-04T15:02:33 | 2014-07-01T16:51:44 | 2,199 | 82 | 25 | 3 |
Python
| null | null |
#!/usr/bin/env python
import argparse
import glob
import json
import os
import re
def _parse_stream(stream):
from lxml import etree
parser = etree.HTMLParser()
# parse the <script> tags.
tree = etree.parse(stream, parser)
scripts = tree.xpath('//script')
for script in scripts:
if 'id' in script.attrib and script.attrib.get('type', None) == 'text/html':
value = script.text
value = value.strip()
# compress whitespace.
value = re.sub(r"([\t ]+)", " ", value)
value = re.sub(r"(\s*\n\s*)", "\n", value)
yield (script.attrib['id'], value)
def parse_comment(html_string):
import lxml.html
# tree = lxml.etree.parse(stream, parser)
tree = lxml.html.fragment_fromstring(html_string,create_parent=1)
# print etree.tostring(tree, pretty_print=1)
if len(tree.getchildren()) > 0:
children = tree.getchildren()
cmt = children[0]
if isinstance(cmt, lxml.html.HtmlComment):
text = cmt.text.strip()
if not text.startswith('ko'):
return text
return None
def parse_scripts(filenames):
result = {}
for html_file in filenames:
stream = open(html_file, 'rb')
for key, text in _parse_stream(stream):
if key in result:
assert False, 'template with duplicate id "%s".' % key
result[key] = {
'html':text,
'filename':html_file,
}
return result
def generate_template(html_files, output_file):
raw_result = parse_scripts(html_files)
result = {}
for (key, value) in raw_result.iteritems():
# only extract out the HTML part.
result[key] = value['html']
output = open(output_file, 'wb')
output.write("""require('poly/main/template').loadTemplateEngine(%s)""" % json.dumps(result))
output.close()
def list_all_tmpl_files(dirpath):
for dirname, subdirnames, filenames in os.walk(dirpath):
for f in filenames:
if f.lower().endswith('.tmpl'):
yield os.path.join(dirname, f)
def main():
parser = argparse.ArgumentParser(description='Turn ko templates into JavaScript.')
parser.add_argument('--source', dest='source', help="Path to source folder.")
parser.add_argument('--dest', dest='dest', help="Path to destination.")
parsed = parser.parse_args()
root_dir = os.getcwd()
source = list_all_tmpl_files(os.path.join(root_dir, parsed.source))
dest = os.path.join(root_dir, parsed.dest)
generate_template(source, dest)
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,014 |
13,511,967,136,883 |
d7935d42d3ba9188d587b0b838b8bb28d43abbac
|
055a0232b5cec1aa44297637273b07fd8d270259
|
/utils.py
|
c676789dbd84c1fcb297f94265f57952ea4151ca
|
[] |
no_license
|
gcross/MERA-experiments
|
https://github.com/gcross/MERA-experiments
|
f84950aa196b7b3998a1d2446915dda13e510890
|
d47d89c18471e8c5cd7ff88bbe9e1edeb44bd195
|
refs/heads/master
| 2016-09-02T05:24:15.362283 | 2011-07-07T20:26:42 | 2011-07-07T20:26:42 | 2,014,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#@+leo-ver=4-thin
#@+node:cog.20080723093036.34:@thin utils.py
from __future__ import division
import __builtin__
from numpy import tensordot, multiply
from numpy.random import rand
#@+others
#@+node:cog.20080723093036.13:n2l
n2l = map(chr,range(ord('A'),ord('Z')+1))
#@-node:cog.20080723093036.13:n2l
#@+node:cog.20080723093036.17:make_contractor_from_implicit_joins
def make_contractor_from_implicit_joins(tensor_index_labels,result_index_labels,name="f"):
tensor_index_labels = list(map(list,tensor_index_labels))
found_indices = {}
index_join_pairs = []
for i in xrange(len(tensor_index_labels)):
for index_position, index in enumerate(tensor_index_labels[i]):
if index in found_indices:
other_tensor = found_indices[index]
if other_tensor is None:
raise ValueError("index label %s found in more than two tensors" % index)
else:
# rename this instance of the index and add to the list of join pairs
tensor_index_labels[i][index_position] = (i,index)
index_join_pairs.append((index,(i,index)))
# mark that we have found two instances of this index for
# error-checking purposes
found_indices[index] = None
else:
found_indices[index] = i
return make_contractor(tensor_index_labels,index_join_pairs,result_index_labels,name)
#@nonl
#@-node:cog.20080723093036.17:make_contractor_from_implicit_joins
#@+node:cog.20080723093036.18:make_contractor
def make_contractor(tensor_index_labels,index_join_pairs,result_index_labels,name="f"): # pre-process parameters
tensor_index_labels = list(map(list,tensor_index_labels))
index_join_pairs = list(index_join_pairs)
result_index_labels = list([list(index_group) if hasattr(index_group,"__getitem__") else [index_group] for index_group in result_index_labels])
assert sum(len(index_group) for index_group in tensor_index_labels) == (sum(len(index_group) for index_group in result_index_labels)+2*len(index_join_pairs))
function_definition_statements = ["def %s(%s):" % (name,",".join(n2l[:len(tensor_index_labels)]))]
#@ << def build_statements >>
#@+node:cog.20080723093036.19:<< def build_statements >>
def build_statements(tensor_index_labels,index_join_pairs,result_index_labels):
#@+at
# This routine recursively builds a list of statements which performs the
# full tensor contraction.
#
# First, if there is only one tensor left, then transpose and reshape it
# to match the result_index_labels.
#@-at
#@@c
if len(tensor_index_labels) == 1:
if len(result_index_labels) == 0:
return ["return A"]
else:
final_index_labels = tensor_index_labels[0]
result_indices = [[final_index_labels.index(index) for index in index_group] for index_group in result_index_labels]
transposed_indices = __builtin__.sum(result_indices,[])
assert type(transposed_indices) == list
assert len(final_index_labels) == len(transposed_indices)
new_shape = ",".join(["(%s)" % "*".join(["shape[%i]"%index for index in index_group]) for index_group in result_indices])
return ["shape=A.shape","return A.transpose(%s).reshape(%s)" % (transposed_indices,new_shape)]
#@+at
# Second, if all joins have finished, then take outer products to combine
# all remaining tensors into one.
#@-at
#@@c
elif len(index_join_pairs) == 0:
if tensor_index_labels[-1] is None:
return build_statements(tensor_index_labels[:-1],index_join_pairs,result_index_labels)
elif len(tensor_index_labels[-1]) == 0:
v = n2l[len(tensor_index_labels)-1]
return ["A*=%s" % v, "del %s" % v] + build_statements(tensor_index_labels[:-1],index_join_pairs,result_index_labels)
else:
v = n2l[len(tensor_index_labels)-1]
tensor_index_labels[0] += tensor_index_labels[-1]
return ["A = multiply.outer(A,%s)" % v, "del %s" % v] + build_statements(tensor_index_labels[:-1],index_join_pairs,result_index_labels)
#@+at
# Otherwise, do the first join, walking through index_join_pairs to find
# any other pairs which connect the same two tensors.
#@-at
#@@c
else:
#@ << Search for all joins between these tensors >>
#@+node:cog.20080723093036.20:<< Search for all joins between these tensors >>
#@+at
# This function searches for the tensors which are joined, and
# reorders the indices in the join so that the index corresponding
# to the tensor appearing first in the list of tensors appears
# first in the join.
#@-at
#@@c
def find_tensor_ids(join):
reordered_join = [None,None]
tensor_ids = [0,0]
join = list(join)
while tensor_ids[0] < len(tensor_index_labels):
index_labels = tensor_index_labels[tensor_ids[0]]
if index_labels is None:
tensor_ids[0] += 1
elif join[0] in index_labels:
reordered_join[0] = index_labels.index(join[0])
del join[0]
break
elif join[1] in index_labels:
reordered_join[0] = index_labels.index(join[1])
del join[1]
break
else:
tensor_ids[0] += 1
assert len(join) == 1 # otherwise index was not found in any tensor
tensor_ids[1] = tensor_ids[0] + 1
while tensor_ids[1] < len(tensor_index_labels):
index_labels = tensor_index_labels[tensor_ids[1]]
if index_labels is None:
tensor_ids[1] += 1
elif join[0] in index_labels:
reordered_join[reordered_join.index(None)] = index_labels.index(join[0])
del join[0]
break
else:
tensor_ids[1] += 1
assert len(join) == 0 # otherwise index was not found in any tensor
return tensor_ids, reordered_join
join_indices = [0]
tensor_ids,reordered_join = find_tensor_ids(index_join_pairs[0])
indices = [[],[]]
for j in xrange(2):
indices[j].append(reordered_join[j])
# Search for other joins between these tensors
for i in xrange(1,len(index_join_pairs)):
tensor_ids_,reordered_join = find_tensor_ids(index_join_pairs[i])
if tensor_ids == tensor_ids_:
join_indices.append(i)
for j in xrange(2):
indices[j].append(reordered_join[j])
#@-node:cog.20080723093036.20:<< Search for all joins between these tensors >>
#@nl
#@ << Build tensor contraction statements >>
#@+node:cog.20080723093036.21:<< Build tensor contraction statements >>
tensor_vars = [n2l[id] for id in tensor_ids]
statements = [
"try:",
" %s = tensordot(%s,%s,%s)" % (tensor_vars[0],tensor_vars[0],tensor_vars[1],indices),
" del %s" % tensor_vars[1],
"except ValueError:",
" raise ValueError('indices %%s do not match for tensor %%i, shape %%s, and tensor %%i, shape %%s.' %% (%s,%i,%s.shape,%i,%s.shape))" % (indices,tensor_ids[0],tensor_vars[0],tensor_ids[1],tensor_vars[1])
]
#@-node:cog.20080723093036.21:<< Build tensor contraction statements >>
#@nl
#@ << Delete joins from list and update tensor specifications >>
#@+node:cog.20080723093036.22:<< Delete joins from list and update tensor specifications >>
join_indices.reverse()
for join_index in join_indices:
del index_join_pairs[join_index]
new_tensor_index_labels_0 = list(tensor_index_labels[tensor_ids[0]])
indices[0].sort(reverse=True)
for index in indices[0]:
del new_tensor_index_labels_0[index]
new_tensor_index_labels_1 = list(tensor_index_labels[tensor_ids[1]])
indices[1].sort(reverse=True)
for index in indices[1]:
del new_tensor_index_labels_1[index]
tensor_index_labels[tensor_ids[0]] = new_tensor_index_labels_0+new_tensor_index_labels_1
tensor_index_labels[tensor_ids[1]] = None
#@-node:cog.20080723093036.22:<< Delete joins from list and update tensor specifications >>
#@nl
return statements + build_statements(tensor_index_labels,index_join_pairs,result_index_labels)
#@-node:cog.20080723093036.19:<< def build_statements >>
#@nl
function_definition_statements += ["\t" + statement for statement in build_statements(tensor_index_labels,index_join_pairs,result_index_labels)]
function_definition = "\n".join(function_definition_statements)+"\n"
f_globals = {"tensordot":tensordot,"multiply":multiply}
f_locals = {}
exec function_definition in f_globals, f_locals
f = f_locals[name]
f.source = function_definition
return f
#@nonl
#@-node:cog.20080723093036.18:make_contractor
#@+node:cog.20080723093036.24:parse_arguments
def parse_arguments(parameters,minimum_required=None):
#@+at
# Parameters are read from the command line; if one or more are omitted,
# hard-coded defaults are used instead.
#
# If the user does not specify any parameters, then it might be because he or
# she does not know what the command-line
# arguments are. Display a help message just in case.
#@-at
#@@c
print
if len(sys.argv) == 1 or minimum_required and len(sys.argv)-1 < minimum_required:
print "Usage: %s %s" % (sys.argv[0],' '.join(map(lambda p: "[%s]"%p,zip(*parameters)[1])))
print
print "When one or more of these parameters is omitted, defaults are employed in their stead."
if minimum_required and len(sys.argv)-1 < minimum_required:
sys.exit()
else:
print
print "(Even though no parameters were specified, this program will continue to run using the defaults.)"
print
#@+at
# First parse whatever arguments are given by the user.
#@-at
#@@c
parameter_values = {}
i = 1
while len(sys.argv) > i and i <= len(parameters):
parameter_variable, parameter_name, parameter_type, default_value = parameters[i-1]
parameter_value = parameter_type(sys.argv[i])
print parameter_name,"=",parameter_value
parameter_values[parameter_variable] = parameter_value
i += 1
#@+at
# Now fill in the rest of the parameters with the defaults.
#@-at
#@@c
while i <= len(parameters):
parameter_variable, parameter_name, parameter_type, default_value = parameters[i-1]
print "Using default value",default_value,"for %s." % parameter_name
parameter_values[parameter_variable] = default_value
i += 1
#@+at
# Return parameter values to the caller.
#@-at
#@@c
return parameter_values
#@-node:cog.20080723093036.24:parse_arguments
#@+node:gcross.20080724123750.12:generate_orderings
def generate_orderings(*list):
if len(list) == 0:
yield ()
else:
for i, item in enumerate(list):
for suffix in generate_orderings(*(list[:i]+list[i+1:])):
yield (item,)+suffix
#@-node:gcross.20080724123750.12:generate_orderings
#@+node:cog.20080723093036.12:crand
def crand(*shape):
return rand(*shape)*2-1+rand(*shape)*2j-1j
#@-node:cog.20080723093036.12:crand
#@+node:cog.20080723093036.25:Unit Tests
if __name__ == '__main__':
import unittest
from Graph import make_graph, Subgraph
from numpy.random import randint
#@ @+others
#@+node:cog.20080723093036.26:make_contractor_tests
class make_contractor_tests(unittest.TestCase):
#@ @+others
#@+node:cog.20080723093036.27:testIdentity
def testIdentity(self):
arr = rand(3,4,5)
self.assertTrue(allclose(arr,make_contractor([[0,1,2]],[],[[0],[1],[2]])(arr),rtol=1e-10))
self.assertTrue(allclose(arr.ravel(),make_contractor([[0,1,2]],[],[[0,1,2]])(arr),rtol=1e-10))
self.assertTrue(allclose(arr.transpose(2,0,1).ravel(),make_contractor([[0,1,2]],[],[[2,0,1]])(arr),rtol=1e-10))
self.assertTrue(allclose(arr.transpose(2,0,1).reshape(15,4),make_contractor([[0,1,2]],[],[[2,0],[1]])(arr),rtol=1e-10))
#@nonl
#@-node:cog.20080723093036.27:testIdentity
#@+node:cog.20080723093036.28:testInnerProduct
def testInnerProduct(self):
A = rand(3,5)
B = rand(5,3)
MP = make_contractor([[0,1],[2,3]],[[1,2]],[0,3])
self.assertTrue(allclose(dot(A,B),MP(A,B),rtol=1e-10))
self.assertTrue(allclose(dot(B,A),MP(B,A),rtol=1e-10))
TP = make_contractor([[0,1],[2,3]],[[1,2],[3,0]],[])
self.assertTrue(allclose(inner(A.transpose().ravel(),B.ravel()),TP(A,B),rtol=1e-10))
#@nonl
#@-node:cog.20080723093036.28:testInnerProduct
#@+node:cog.20080723093036.29:testImplicitJoins
def testImplicitJoins(self):
arr = rand(3,4,5)
self.assertTrue(allclose(arr,make_contractor_from_implicit_joins([[0,1,2]],[[0],[1],[2]])(arr),rtol=1e-10))
self.assertTrue(allclose(arr.ravel(),make_contractor_from_implicit_joins([[0,1,2]],[[0,1,2]])(arr),rtol=1e-10))
self.assertTrue(allclose(arr.transpose(2,0,1).ravel(),make_contractor_from_implicit_joins([[0,1,2]],[[2,0,1]])(arr),rtol=1e-10))
self.assertTrue(allclose(arr.transpose(2,0,1).reshape(15,4),make_contractor_from_implicit_joins([[0,1,2]],[[2,0],[1]])(arr),rtol=1e-10))
A = rand(3,5)
B = rand(5,3)
MP = make_contractor_from_implicit_joins([[0,1],[1,3]],[[0],[3]])
self.assertTrue(allclose(dot(A,B),MP(A,B),rtol=1e-10))
self.assertTrue(allclose(dot(B,A),MP(B,A),rtol=1e-10))
TP = make_contractor_from_implicit_joins([[0,1],[1,0]],[])
self.assertTrue(allclose(inner(A.transpose().ravel(),B.ravel()),TP(A,B),rtol=1e-10))
arr = rand(3,4,5)
self.assertTrue(allclose(arr*5,make_contractor_from_implicit_joins([[0,1,2],[]],[[0],[1],[2]])(arr,5),rtol=1e-10))
self.assertTrue(allclose(arr*5*6,make_contractor_from_implicit_joins([[0,1,2],[],[]],[[0],[1],[2]])(arr,5,6),rtol=1e-10))
self.assertTrue(allclose(multiply.outer(arr,arr),make_contractor_from_implicit_joins([[0,1,2],[3,4,5]],[[i] for i in xrange(6)])(arr,arr),rtol=1e-10))
self.assertTrue(allclose(reduce(multiply.outer,[arr,]*3),make_contractor_from_implicit_joins([[0,1,2],[3,4,5],[6,7,8]],[[i] for i in xrange(9)])(arr,arr,arr),rtol=1e-10))
A = rand(3,4,5)
B = rand(3,4,5)
C = rand(3,4,5)
self.assertTrue(allclose(reduce(multiply.outer,[A,B,C]),make_contractor_from_implicit_joins([[0,1,2],[3,4,5],[6,7,8]],[[i] for i in xrange(9)])(A,B,C),rtol=1e-10))
#@nonl
#@-node:cog.20080723093036.29:testImplicitJoins
#@+node:cog.20080723093036.30:testOuterProduct
def testOuterProduct(self):
arr = rand(3,4,5)
self.assertTrue(allclose(arr*5,make_contractor([[0,1,2],[]],[],range(3))(arr,5),rtol=1e-10))
self.assertTrue(allclose(arr*5*6,make_contractor([[0,1,2],[],[]],[],range(3))(arr,5,6),rtol=1e-10))
self.assertTrue(allclose(multiply.outer(arr,arr),make_contractor([[0,1,2],[3,4,5]],[],range(6))(arr,arr),rtol=1e-10))
self.assertTrue(allclose(reduce(multiply.outer,[arr,]*3),make_contractor([[0,1,2],[3,4,5],[6,7,8]],[],range(9))(arr,arr,arr),rtol=1e-10))
A = rand(3,4,5)
B = rand(3,4,5)
C = rand(3,4,5)
self.assertTrue(allclose(reduce(multiply.outer,[A,B,C]),make_contractor([[0,1,2],[3,4,5],[6,7,8]],[],[[i] for i in xrange(9)])(A,B,C),rtol=1e-10))
#@nonl
#@-node:cog.20080723093036.30:testOuterProduct
#@+node:cog.20080723093036.31:testTensorNetwork
def testTensorNetwork(self):
A_indices = (2,3,4,6)
B_indices = (7,2,8)
C_indices = (9,8,3,10)
D_indices = (11,7,9,4)
E_indices = (6,10,11)
A = rand(2,5,3,7)
B = rand(4,2,6)
C = rand(6,6,5,8)
D = rand(4,4,6,3)
E = rand(7,8,4)
g = make_graph(
(A,A_indices),
(B,B_indices),
(C,C_indices),
(D,D_indices),
(E,E_indices),
)
self.assertTrue(allclose(
g.fully_contract()[0],
make_contractor_from_implicit_joins([A_indices,B_indices,C_indices,D_indices,E_indices],[])(A,B,C,D,E),
rtol=1e-10
))
tensors = (A,B,C,D,E)
specifications = (A_indices,B_indices,C_indices,D_indices,E_indices)
for selected in xrange(1,1<<5):
selected_tensors = [i for i in xrange(5) if ((selected >> i) % 2) == 1]
selected_specifications = [specifications[i] for i in selected_tensors]
excluded_tensors = [i for i in xrange(5) if ((selected >> i) % 2) == 0]
result_indices = []
connected_tensors = []
for i in excluded_tensors:
tensor_is_connected = True
for index in specifications[i]:
found = False
for j in selected_tensors:
if index in specifications[j]:
found = True
break
if found: # i.e., if this index is connected to the network
result_indices.append(index)
tensor_is_connected = True
if tensor_is_connected:
connected_tensors.append(i)
f_eval = make_contractor_from_implicit_joins(selected_specifications,result_indices)(*[tensors[i] for i in selected_tensors])
s = Subgraph(g)
for i in selected_tensors:
s.add_node(i)
s.merge_all()
g_eval = s.get_resulting_matrices(connected_tensors)[0]
self.assertTrue(allclose(f_eval,g_eval,rtol=1e-10))
#@nonl
#@-node:cog.20080723093036.31:testTensorNetwork
#@-others
#@nonl
#@-node:cog.20080723093036.26:make_contractor_tests
#@-others
unittest.main()
#@-node:cog.20080723093036.25:Unit Tests
#@-others
#@-node:cog.20080723093036.34:@thin utils.py
#@-leo
|
UTF-8
|
Python
| false | false | 2,011 |
16,260,746,201,603 |
6c1891cc933571752cd2c888276c444c0a5cd019
|
d5e250b222228fcfff06e3915f73a16f159bffe2
|
/Alpha/product/models.py
|
6a3fa7b14ca3d88a4c8096079d5ab6fd26a6d520
|
[] |
no_license
|
flynhigher/terry-play-ground
|
https://github.com/flynhigher/terry-play-ground
|
602be75e8161c1f1b4b57578986cbaca57b43eba
|
c57674b65f59db0bf2e3e97526153c1f91516671
|
refs/heads/master
| 2021-01-10T11:39:37.416843 | 2013-04-18T01:50:42 | 2013-04-18T01:50:42 | 44,543,863 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import operator
from datetime import datetime
from django.db import models
from django.db.models import signals
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.contrib.localflavor.us.models import USStateField
class Category(models.Model):
"""
a category is a product category
"""
slug = models.SlugField(_('slug'), max_length=200)
name = models.CharField(_('name'), max_length=200)
description = models.TextField(_('description'), null=True, blank=True)
parents = models.ManyToManyField('self', verbose_name=_('parents'), null=True, blank=True)
deleted = models.BooleanField(_('deleted'), default=False)
def __unicode__(self):
return self.name
class Product(models.Model):
"""
a product
"""
slug = models.SlugField(_('slug'), max_length=350)
code = models.CharField(_('code'), max_length=100, blank=True, null=True)
name = models.CharField(_('name'), max_length=350)
price = models.DecimalField(_('price'), default=0, decimal_places=2, max_digits=20)
creator = models.ForeignKey(User, related_name="created_products", verbose_name=_('creator'))
created = models.DateTimeField(_('created'), default=datetime.now)
updater = models.ForeignKey(User, related_name="updated_products", verbose_name=_('updater'), blank=True, null=True)
updated = models.DateTimeField(_('updated'), blank=True, null=True)
description = models.TextField(_('description'), blank=True, null=True)
discontinued = models.DateTimeField(_('discontinued'), blank=True, null=True)
categories = models.ManyToManyField(Category, verbose_name=_('categories'))
# prices = models.ManyToManyField(Price, verbose_name=_('prices'))
related_products = models.ManyToManyField('self', verbose_name=_('related_products'), blank=True, null=True)
image_url = models.URLField(_('image_url'), blank=True, null=True)
bought_by = models.ManyToManyField(User, related_name="bought_products", blank=True, null=True)
interested_by = models.ManyToManyField(User, related_name="interested_products", blank=True, null=True)
def __unicode__(self):
return self.name
class Schedule(models.Model):
"""
a schedule for a product
"""
slug = models.SlugField(_('slug'), max_length=350)
buycode = models.CharField(_('buycode'), max_length=45)
title = models.CharField(_('title'), max_length=500, blank=True, null=True) #auto-filled?
description = models.TextField(_('description'), blank=True, null=True)
venue = models.CharField(_('venue'), max_length=100)
address1 = models.CharField(_('address1'), max_length=300)
address2 = models.CharField(_('address2'), max_length=300, blank=True, null=True)
city = models.CharField(_('city'), max_length=50)
state = models.CharField(_('state'), max_length=50)
zipcode = models.CharField(_('zipcode'), max_length=15)
start = models.DateTimeField(_('start'), blank=True, null=True)
end = models.DateTimeField(_('end'), blank=True, null=True)
buyurl = models.URLField(_('buyurl'), max_length=200, blank=True, null=True)
price = models.DecimalField(_('price'), default=0, decimal_places=2, max_digits=20)
product = models.ForeignKey(Product)
creator = models.ForeignKey(User, related_name="created_prices", verbose_name=_('creator'))
created = models.DateTimeField(_('created'), default=datetime.now)
updater = models.ForeignKey(User, related_name="updated_prices", verbose_name=_('updater'), blank=True, null=True)
updated = models.DateTimeField(_('updated'), blank=True, null=True)
def __unicode__(self):
return self.title
class Signup(models.Model):
firstname = models.CharField(max_length=50)
middlename = models.CharField(max_length=50, blank=True, null=True)
lastname = models.CharField(max_length=50)
address1 = models.CharField(max_length=300, blank=True, null=True)
address2 = models.CharField(max_length=300, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
state = USStateField(blank=True, null=True)
zipcode = models.CharField(max_length=15, blank=True, null=True)
country = models.CharField(max_length=100, blank=True, null=True)
businessname = models.CharField(max_length=100, blank=True, null=True)
businesstype = models.CharField(max_length=100, blank=True, null=True)
position = models.CharField(max_length=100, blank=True, null=True)
numberofstudents = models.IntegerField(blank=True, null=True);
phone = models.CharField(max_length=50)
numberofemployees = models.IntegerField(blank=True, null=True);
email = models.EmailField(blank=True, null=True)
schedulecode = models.CharField(max_length=20)
comment = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.lastname + ', ' + self.firstname
class Meta:
verbose_name = 'Signup information'
verbose_name_plural = 'Signup information'
# Apply keyword searches.
def construct_search(field_name):
if field_name.startswith('^'):
return "%s__istartswith" % field_name[1:]
elif field_name.startswith('='):
return "%s__iexact" % field_name[1:]
elif field_name.startswith('@'):
return "%s__search" % field_name[1:]
else:
return "%s__icontains" % field_name
def get_queryset(initial_queryset, query, search_fields):
qs = initial_queryset
if search_fields and query:
for word in query.split():
or_queries = [models.Q(**{construct_search(str(field_name)): word}) for field_name in search_fields]
qs = qs.filter(reduce(operator.or_, or_queries))
for field_name in search_fields:
if '__' in field_name:
qs = qs.distinct()
break
return qs
|
UTF-8
|
Python
| false | false | 2,013 |
18,013,092,870,255 |
77692f0ebe784d2a2cf49f90798571caeeb9c4cb
|
978ebee6c02c4d7c1ebcf5e409670c8834576f9f
|
/wscript
|
d79612a232f1b31034104c1569b3cc24aa32e808
|
[] |
no_license
|
Cloudxtreme/py-ndns
|
https://github.com/Cloudxtreme/py-ndns
|
3e9c302a7cb7f4ca93f65eec37e631f8ff69412d
|
b099ea49cfafcd985dad3472765b217cd2cfdd83
|
refs/heads/master
| 2020-03-31T11:58:02.647210 | 2013-09-02T22:12:41 | 2013-09-02T22:12:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
VERSION='0.1'
APPNAME='ndns'
from waflib import TaskGen, Task, Utils, Logs
def options(opt):
opt.load('compiler_c python gnu_dirs')
def configure(conf):
conf.load("compiler_c python gnu_dirs")
conf.check_python_version ((2,7))
conf.check_python_headers ()
conf.check_python_module ('apscheduler')
conf.check_python_module ('sqlalchemy')
try:
conf.start_msg ("Check contrib/")
import subprocess
from waflib import Logs
p = subprocess.Popen("git submodule status", shell=True, stdout=subprocess.PIPE)
var = p.communicate ()[0]
up_to_date = True
for line in var.split ('\n'):
if line == "":
continue
up_to_date = (up_to_date and line[0] == ' ')
if up_to_date:
conf.end_msg ("up-to-date")
else:
conf.end_msg ("contrib/ has differences, consider `git submodule update` or `git submodule update --init`", 'YELLOW')
Logs.warn (var)
except:
raise
try:
conf.check_python_module ('setproctitle')
except:
Logs.warn ("py-setproctitle can be installed from contrib/ folder: (cd contrib/py-setproctitle && sudo python ./setup.py install)")
raise
try:
conf.check_python_module ('ndn')
except:
Logs.warn ("PyNDN can be installed from contrib/ folder: (cd contrib/py-ndn && ./waf configure && sudo ./waf install)")
raise
def build (bld):
bld (features = "py",
source = bld.path.ant_glob(['ndns/**/*.py']),
install_from = ".",
install_path = "${LIBDIR}/ndns")
bld (features = "py",
source = bld.path.ant_glob(['contrib/dnspython/dns/**/*.py']),
install_from = "contrib/dnspython",
install_path = "${LIBDIR}/ndns")
bld (features = "subst",
source = bld.path.ant_glob(['bin/**/*.in']),
target = [node.change_ext('', '.in') for node in bld.path.ant_glob(['bin/**/*.in'])],
install_path = "${BINDIR}",
chmod = 0755,
)
def docs (bld):
import subprocess
p = subprocess.Popen (['sphinx-build', '-b', 'html', './docs', './build/docs'], close_fds=False)
p.communicate ()
|
UTF-8
|
Python
| false | false | 2,013 |
14,396,730,420,101 |
fa3a8d440e24aebe5d329bb05ab2d61fe3b0136b
|
73d1b9a8878e55ce5a86662ff339680101e1ba48
|
/CheckBoolean.py
|
29e21f3b7814c32ef73fdab8510bac86121667e8
|
[] |
no_license
|
gkioumis/VariousPython
|
https://github.com/gkioumis/VariousPython
|
df7eaf929f3a1eb100c0189ce63e608acb52d091
|
64a9f3e18a27b0edd45e78e8ce3e60e4fed57c29
|
refs/heads/master
| 2015-07-23T04:49:37 | 2013-03-18T21:07:48 | 2013-03-18T21:07:48 | 8,684,297 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__ = "giorgos"
__date__ = "$15/02/2012$"
def hasNotEmpty(a):
for i in range(3):
for j in range(3):
if a[i][j] == " ":
return False
def hasEmpty(a):
Empty = True
for i in range(3):
for j in range(3):
Empty = Empty and a[i][j] == " "
return Empty
def hasEmpty2(a):
counter = 0
for i in range(9):
if a[i % 3][i / 3] == " ":
counter += 1
return counter == 9
def hasEmpty3(a):
counter = 0
i = 8
while (i >= 0 and a[i % 3][i / 3] == " "):
counter += 1
i -= 1
# if i < 0: break # allios xoris to (i>=0 and) sti sin8iki tou while
return counter == 9
# fun pythonista stuff #
def hasEmpty4(a):
return len([(i, j) for i in range(3)
for j in range(3) if a[i][j] == " "]) == 9
def hasEmpty5(a):
isFull = True
return [(isFull and a[i % 3][i / 3] == " ")
for i in range(9)].count(True) == 9
def hasEmpty6(a): # generator :)
for bool in (True and a[i % 3][i / 3] == " " for i in range(9)):
if not bool:
return bool
return True
if __name__ == "__main__":
# a=[['x','o','o'], ['o','x','x'],['x','o','x']]
a = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]
# a=[[" "]*3 for i in range(3)]
print hasEmpty(a)
print hasEmpty2(a)
print hasEmpty3(a)
print hasEmpty4(a)
print hasEmpty5(a)
print hasEmpty6(a)
|
UTF-8
|
Python
| false | false | 2,013 |
3,891,240,382,287 |
c460f2fc38038e3527b0c27a22101ea2065e36ce
|
e96b80b8bff5e8f54c62ed09815c844d121fe60c
|
/branches/notifier/ilenia-notifier/lib/details.py
|
3f8060ede7e542176a2615981b3c80d6f21d3c4b
|
[] |
no_license
|
BackupTheBerlios/ilenia-svn
|
https://github.com/BackupTheBerlios/ilenia-svn
|
814fae99bc56de98973655e8c52f84558be83528
|
6d35c85223a2d2deb052681acc6b846494ae3968
|
refs/heads/master
| 2021-01-23T19:43:18.899658 | 2008-11-15T18:01:02 | 2008-11-15T18:01:02 | 40,747,920 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
details.py
Sun Sep 18 15:52:02 2005
Copyright 2005 - 2006 Coviello Giuseppe
immigrant@email.it
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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
import gtk
class Details(gtk.Window):
def __init__(self):
gtk.Window.__init__(self)
self.set_title("Ilenia-notifier: details")
vbox = gtk.VBox(spacing=0)
self.w_label = gtk.Label()
self.w_label.set_padding(0, 18)
vbox.pack_start(self.w_label, 0, 0)
self.pc = PkginfoContainer()
vbox.pack_start(self.pc)
self.add(vbox)
self.resize(300, 200)
self.connect("delete_event", self.on_delete)
def set_list(self, list):
self.pc.clear()
for pkg in list:
self.pc.add(Pkginfo(pkg))
if len(list)==0:
self.w_label.set_markup("<b>The System is Up To Date!</b>")
else:
self.w_label.set_markup("<b>There are %s updates available:</b>" %
len(list))
def show(self):
self.show_all()
def hide(self):
self.hide_all()
def on_delete(self, w, data):
self.hide()
return True
class PkginfoContainer(gtk.ScrolledWindow):
def __init__(self):
gtk.ScrolledWindow.__init__(self)
self._vbox = gtk.VBox(spacing=24)
self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.set_border_width(2)
self.set_shadow_type(gtk.SHADOW_NONE)
gtk.ScrolledWindow.add_with_viewport(self, self._vbox)
def add(self, pkginfo):
self._vbox.pack_start(pkginfo, 0, 0)
self._vbox.pack_start(gtk.HSeparator(), 0, 0)
def clear(self):
for w in self._vbox.get_children():
self._vbox.remove(w)
class Pkginfo(gtk.Frame):
def __init__(self, pkg):
gtk.Frame.__init__(self)
label = gtk.Label()
label.set_markup("<b>%s</b>" % pkg["name"])
self.set_label_widget(label)
self.set_label_align(0.0, 0.5)
self.set_border_width(0)
self.set_shadow_type(gtk.SHADOW_NONE)
alignment = gtk.Alignment(0.5, 0.5, 1.0, 1.0)
gtk.Frame.add(self, alignment)
alignment.set_padding(0, 0, 12, 0)
vbox = gtk.VBox(spacing = 6)
label = gtk.Label()
label.set_markup("<b>Installed version</b>: %s" % pkg["l_version"])
vbox.pack_start(label, 0, 0)
label.set_alignment(0, 0.5)
label = gtk.Label()
label.set_markup("<b>Repository version</b>: %s" % pkg["r_version"])
vbox.pack_start(label, 0, 0)
label.set_alignment(0, 0.5)
label = gtk.Label()
label.set_markup("<b>Repository</b>: %s" % pkg["repo"])
vbox.pack_start(label, 0, 0)
label.set_alignment(0, 0.5)
alignment.add(vbox)
self.show_all()
if __name__ == "__main__":
Details([{"name":"ilenia-notifier","l_version":"0","r_version":"0",
"repo":"none"}])
gtk.main()
|
UTF-8
|
Python
| false | false | 2,008 |
7,722,351,221,663 |
ad580b923998bf304cf0093a0e8a9cc32ddd5ebd
|
fef146784283362fa37465bd212b65b13774d8c5
|
/bin/pyflakes
|
2f90c7823500748e8d8d07819244cd4125a76adb
|
[
"MIT"
] |
permissive
|
mattorb/pyflakes
|
https://github.com/mattorb/pyflakes
|
0cea57b402a837b52310c1172cd3e1b682a54033
|
0cb5c7fba21c27b4503fcead10bbebce2e368894
|
refs/heads/master
| 2021-01-02T09:01:42.882254 | 2009-11-02T00:31:50 | 2009-11-02T00:32:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
import compiler, sys
import os
from pyflakes import checker, messages
import optparse
import fnmatch
import linecache
class MessageFilters(object):
def __init__(self, filters=()):
self.filters = list(filters)
def add(self, class_name, arg, filename_pattern):
self.filters.append((class_name, arg, filename_pattern))
def show(self, message, filename):
for class_name, arg, filename_pattern in self.filters:
if filename_pattern:
if not fnmatch.fnmatch(filename, filename_pattern):
continue # this filter does not apply
if message.__class__.__name__ == class_name or class_name == '*':
if not arg or arg == '*':
return False
if (arg, ) == message.message_args[:1]:
return False
return True
class UnusedImportFilter(object):
"""Suppress UnusedImport warnings if the import line has a comment."""
def show(self, message, filename):
if isinstance(message, messages.UnusedImport):
source_line = linecache.getline(filename, message.lineno)
if '#' in source_line:
return False
return True
class CombinedFilter(object):
def __init__(self, filters=()):
self.filters = list(filters)
def add(self, filter):
self.filters.append(filter)
def show(self, message, filename):
for filter in self.filters:
if not filter.show(message, filename):
return False
return True
class FilenameFilters(object):
def __init__(self, patterns):
self.patterns = patterns
def allows(self, filename):
for pattern in self.patterns:
if fnmatch.fnmatch(filename, pattern):
return False
return True
def check(codeString, filename, filters):
try:
tree = compiler.parse(codeString)
except (SyntaxError, IndentationError), e:
msg = e.args[0]
value = sys.exc_info()[1]
try:
(lineno, offset, text) = value[1][1:]
except IndexError:
print >> sys.stderr, 'could not compile %r' % (filename,)
return 1
line = text.splitlines()[-1]
offset = offset - (len(text) - len(line))
print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg)
print >> sys.stderr, line
print >> sys.stderr, " " * (offset-1) + "^"
return 1
else:
try:
w = checker.Checker(tree, filename)
except:
print >> sys.stderr, "in %s:" % filename
raise
w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
for warning in w.messages:
if not filters.show(warning, filename):
w.messages.remove(warning) # it doesn't affect return code
else:
print warning
return len(w.messages)
def checkPath(filename, filters):
if os.path.exists(filename):
return check(file(filename, 'U').read(), filename, filters=filters)
print >> sys.stderr, '%s: not found' % filename
return 0
parser = optparse.OptionParser()
parser.add_option('-x', '--exclude', metavar='FILENAME_PATTERN',
help='skip files matching this pattern (* matches /)',
action='append', type='str', dest='exclude', default=[])
parser.add_option('-i', '--ignore', metavar='WARNING_CLASS[:NAME[:FILENAME_PATTERN]][,...]',
help='ignore warnings of a given class, or just names about a given name',
action='append', type='str', dest='ignore', default=[])
opts, args = parser.parse_args()
exclude = FilenameFilters(opts.exclude)
filters = MessageFilters()
for arg in opts.ignore:
if arg == 'help':
print "Warning classes:"
for name in sorted(dir(messages)):
obj = getattr(messages, name)
if isinstance(obj, type) and issubclass(obj, messages.Message) and obj is not messages.Message:
print ' ', obj.__name__.ljust(24), ' ', obj.message.replace('%r', 'X').replace('%s', 'X')
sys.exit(0)
for spec in arg.split(','):
bits = spec.split(':') + [None, None]
class_name, arg, filename_pattern = bits[:3]
filters.add(class_name, arg, filename_pattern)
filters = CombinedFilter([filters, UnusedImportFilter()])
warnings = 0
if args:
for arg in args:
if os.path.isdir(arg):
for dirpath, dirnames, filenames in os.walk(arg):
dirnames.sort()
for filename in sorted(filenames):
if filename.endswith('.py'):
filepath = os.path.join(dirpath, filename)
if exclude.allows(filepath):
thisWarningCount = checkPath(filepath,
filters=filters)
warnings += thisWarningCount
else:
if exclude.allows(arg):
thisWarningCount = checkPath(filepath,
filters=filters)
warnings += thisWarningCount
else:
warnings += check(sys.stdin.read(), '<stdin>', filters=filters)
raise SystemExit(warnings > 0)
|
UTF-8
|
Python
| false | false | 2,009 |
12,034,498,410,735 |
b9852818d3d7d95daaa091a11da6a152c95ea2fa
|
aa6bc79a1f9b41dfa4a1c70a4b6a6e52e75aefce
|
/kdyno/util.py
|
7e1b2c72a088723cb0c2682f4a051df3b441a97d
|
[] |
no_license
|
kzahel/kdyno
|
https://github.com/kzahel/kdyno
|
9b09d6f2b1f4c9f1211cc305adea20f59fc41829
|
dc0fd2a1397a34ac9bacb7e18a26f63f87d5b60d
|
refs/heads/master
| 2016-09-06T17:26:53.530662 | 2012-10-22T17:06:56 | 2012-10-22T17:06:56 | 3,287,372 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from email.utils import formatdate
from hashlib import sha256
class HmacKeys(object):
"""Key based Auth handler helper."""
def __init__(self, host, config, secret_key):
self.host = host
self.update_secret(secret_key)
def update_secret(self, secret_key):
self._hmac_256 = hmac.new(secret_key,
digestmod=sha256)
def algorithm(self):
return 'HmacSHA256'
def sign_string(self, string_to_sign):
if self._hmac_256:
hmac = self._hmac_256.copy()
else:
hmac = self._hmac.copy()
hmac.update(string_to_sign)
return base64.encodestring(hmac.digest()).strip()
#class HmacAuthV3HTTPHandler(AuthHandler, HmacKeys):
class HmacAuthV3HTTPHandler(HmacKeys):
"""
Implements the new Version 3 HMAC authorization used by DynamoDB.
"""
capability = ['hmac-v3-http']
def __init__(self, host, config, provider):
#AuthHandler.__init__(self, host, config, provider)
HmacKeys.__init__(self, host, config, provider)
def headers_to_sign(self, http_request):
"""
Select the headers from the request that need to be included
in the StringToSign.
"""
headers_to_sign = {}
headers_to_sign = {'Host' : self.host}
for name, value in http_request.headers.items():
lname = name.lower()
if lname.startswith('x-amz'):
headers_to_sign[name] = value
return headers_to_sign
def canonical_headers(self, headers_to_sign):
"""
Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines.
"""
l = ['%s:%s'%(n.lower().strip(),
headers_to_sign[n].strip()) for n in headers_to_sign]
l.sort()
return '\n'.join(l)
def string_to_sign(self, http_request):
"""
Return the canonical StringToSign as well as a dict
containing the original version of all headers that
were included in the StringToSign.
"""
headers_to_sign = self.headers_to_sign(http_request)
canonical_headers = self.canonical_headers(headers_to_sign)
string_to_sign = '\n'.join([http_request.method,
http_request.path,
'',
canonical_headers,
'',
http_request.body])
return string_to_sign, headers_to_sign
def add_auth(self, req, security_token=None, access_key=None):
"""
Add AWS3 authentication to a request.
:type req: :class`boto.connection.HTTPRequest`
:param req: The HTTPRequest object.
"""
# This could be a retry. Make sure the previous
# authorization header is removed first.
if 'X-Amzn-Authorization' in req.headers:
del req.headers['X-Amzn-Authorization']
req.headers['X-Amz-Date'] = formatdate(usegmt=True)
req.headers['X-Amz-Security-Token'] = security_token
string_to_sign, headers_to_sign = self.string_to_sign(req)
hash_value = sha256(string_to_sign).digest()
b64_hmac = self.sign_string(hash_value)
s = "AWS3 AWSAccessKeyId=%s," % access_key
s += "Algorithm=%s," % self.algorithm()
s += "SignedHeaders=%s," % ';'.join(headers_to_sign)
s += "Signature=%s" % b64_hmac
req.headers['X-Amzn-Authorization'] = s
import hmac
import hashlib
import base64
#sixapart signing stuff
class SignatureMethod(object):
def build_signature_base_string(self, request):
sig = '\n'.join( (
request.get_normalized_http_method(),
request.get_normalized_http_host(),
request.get_normalized_http_path(),
request.get_normalized_parameters(),
) )
return sig
class SignatureMethod_HMAC_SHA256(SignatureMethod):
name = 'HmacSHA256'
version = '2'
def build_signature(self, request, aws_secret):
base = self.build_signature_base_string(request)
hashed = hmac.new(aws_secret, base, hashlib.sha256)
return base64.b64encode(hashed.digest())
signer = SignatureMethod_HMAC_SHA256()
|
UTF-8
|
Python
| false | false | 2,012 |
5,162,550,724,635 |
afb11555ddb3b61a874cb7dd8f60a3d34855736d
|
94417e7b3b76297de5483f9dc972d52bcc9b33af
|
/storaged.py
|
1335a3884eec228719864f052abe1d71f61b95b7
|
[
"BSD-3-Clause"
] |
permissive
|
dwilliams/dpyfs
|
https://github.com/dwilliams/dpyfs
|
7ad03c3d3030025fd5f46aad6d3bc99b1d4756ca
|
6a2295d7e9706caa63d511f3384e2aa2b37bc172
|
refs/heads/master
| 2021-01-25T10:07:05.987054 | 2013-12-04T16:27:42 | 2013-12-04T16:27:42 | 14,308,245 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/local/bin/python
# storaged.py
# A python based simple storage daemon for the dpyfs project.
# Daniel Williams <dwilliams@port8080.net>
### IMPORTS ############################################################################################################
import logging
import argparse
import ConfigParser
import hashlib
import web
import os
import platform
import json
if platform.system() == 'Windows':
import ctypes
### GLOBALS ############################################################################################################
config = None
numChunks = 0
### FUNCTIONS ##########################################################################################################
# View function for the good ol' 404
def notFound():
return web.notfound("<html><body><h1>404 Not Found</h1>\n"
"<p>Somethin's amiss. Might want to check them URLs again.</p></body></html>")
# View function for a lovely little internal error
def internalError():
return web.internalerror("<html><body><h1>500 Internal Server Error</h1>\n"
"<p>I guess I've lost my tools in my hands again.</p></body></html>")
# Helper function to get free space and total space information (in megabytes)
def diskSpace(path):
freespace = 0
freespacenonsuper = 0
totalspace = 0
print "diskSpace(%s): platform = %s" % (path, platform.system())
# If we're on Windows
if platform.system() == 'Windows':
freespace = ctypes.c_ulonglong(0)
freespacenonsuper = ctypes.c_ulonglong(0)
totalspace = ctypes.c_ulonglong(0)
# NOTE: totalspace here is the total space available to the user, not total space on the disk.
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path),
ctypes.pointer(freespacenonsuper),
ctypes.pointer(totalspace),
ctypes.pointer(freespace))
else:
# We're on a decent system...
stat = os.statvfs(path)
freespace = st.f_bfree * st.f_frsize
freespacenonsuper = st.f_bavail * st.f_frsize
totalspace = st.f_blocks * f_frsize
# return a tuple of the yummy info
return (freespace.value / (1024 * 1024), freespacenonsuper.value / (1024 * 1024), totalspace.value / (1024 * 1024))
# Helper function to check the chunks in the storageDir and set the counters
def checkChunks(path):
chunkCounter = 0
for root, dir, files in os.walk(path):
logging.debug("checkChunks: root: %s" % (root))
logging.debug("checkChunks: dir: %s" % (str(dir)))
logging.debug("checkChunks: files: %s" % (str(files)))
for curfile in files:
isChunkGood = True
logging.debug("checkChunks: curfile: %s" % (curfile))
# Grab the chunk
chunk = open(os.path.abspath("%s/%s" % (root, curfile)), 'rb').read()
# check it's size
if len(chunk) != config.getBlockSize():
# The chunk is the wrong size.
logging.warning("Somebody's touched the file system again.")
isChunkGood = False
# hash it
mdfive = hashlib.md5(chunk).hexdigest()
shaone = hashlib.sha1(chunk).hexdigest()
# check the path
curpath = "%s/" % (config.getStorageDir())
for i in range(0, len(mdfive), 3):
curpath += "%s/" % (mdfive[i:i+3])
if(os.path.abspath(curpath) != os.path.abspath(root)):
# The chunk hashed badly.
logging.warning("Somebody's touched the file system again.")
logging.debug(" root: %s" % (os.path.abspath(root)))
logging.debug(" curpath: %s" % (os.path.abspath(curpath)))
isChunkGood = False
# check the filename
if(curfile != ("%s.obj" % (shaone))):
# The chunk hashed badly.
logging.warning("Somebody's touched the file system again.")
logging.debug(" curfile: %s" % (curfile))
logging.debug(" shaone: %s" % (shaone))
isChunkGood = False
# if it's good, increment counter
if(isChunkGood):
chunkCounter += 1
# if it's bad delete the chunk
else:
logging.warning("Cleaning up other's meddling")
os.remove("%s/%s" % (root, curfile))
# delete any empty directories (should have function in os module that does this)
try:
os.removedirs(path)
except OSError as ex:
logging.debug("Failed to remove a directory: %s" % (ex))
return chunkCounter
### CLASSES ############################################################################################################
# Controller class for redirecting the root to another place
class index:
def GET(self):
raise web.seeother('/info')
# Controller class for infomation display pages.
class info:
def GET(self, parameterString = None):
global config, numChunks
path = config.getStorageDir()
# If /info/integritycheck is called, run the integrity check function.
if(parameterString == 'integritycheck'):
numChunks = checkChunks(path)
info = {'numchunks': numChunks}
info['spacefree'], info['spacefreenonsuper'], info['spacetotal'] = diskSpace(path)
logging.debug("SF: %s\nSFNS: %s\nTS: %s" % (info['spacefree'], info['spacefreenonsuper'], info['spacetotal']))
try:
info['percentfreenonsuper'] = 100 * (float(info['spacefreenonsuper']) / info['spacetotal'])
except ZeroDivisionError:
info['percentfreenonsuper'] = 0
contentType = web.ctx.env.get('HTTP_ACCEPT')
logging.debug("/info GET Content-Type: %s" % (contentType))
if(contentType == 'application/json'):
web.header('Content-Type', 'application/json')
result = json.dumps(info)
else:
web.header('Content-Type', 'text/html')
result = "<html><body><h1>dpyfs Storage Daemon</h1>\n"
result += "<h3>Diskspace:</h3>\n"
result += "Total Space: %d MB<br />\n" % (info['spacetotal'])
result += "Free Space: %d MB<br />\n" % (info['spacefreenonsuper'])
result += "Percent Free: %d%%<br />\n" % (info['percentfreenonsuper'])
result += "Number of Chunks: %d<br />" % (info['numchunks'])
return result
# Controller class for accessing file chunks.
class data:
def GET(self, hashMD5, hashSHA1):
global config
# Build the path and read the file
path = "%s/" % (config.getStorageDir())
for i in range(0, len(hashMD5), 3):
path += "%s/" % (hashMD5[i:i+3])
path += "%s.obj" % (hashSHA1)
## Should try catch around this file read...
if not os.path.isfile(path):
logging.info("File not found: %s" % (path))
return web.notfound()
chunk = open(path, 'rb').read()
# Verify the sums
mdfive = hashlib.md5(chunk).hexdigest()
shaone = hashlib.sha1(chunk).hexdigest()
# Return the chunk
if mdfive == hashMD5 and shaone == hashSHA1:
web.header("Content-Type", "application/octet-stream")
return chunk
# Return an error here
logging.error("There's a skeleton in my closet! GET - %s" % (path))
return web.internalerror()
def PUT(self, hashMD5, hashSHA1):
global config, numChunks
# Make sure we're getting the right content-type
contentType = web.ctx.env.get('CONTENT-TYPE')
if(contentType != 'application/octet-stream'):
# Not an octet stream, log a warning. We'll still store the chunk if it passes everything else.
logging.warning("Somebody's giving me something I don't like.")
logging.debug("PUT Content-Type: %s" % (contentType))
# Grab the chunk and calc the sums
chunk = web.data()
if len(chunk) != config.getBlockSize():
# The chunk is wrong. Return a 400 bad request error. Log info about the remote in the future.
logging.warning("Somebody's passing around a bad brownie.")
logging.debug("actual chunk size: %d" % (len(chunk)))
logging.debug("config chunk size: %d" % (config.getBlockSize()))
return web.badrequest()
mdfive = hashlib.md5(chunk).hexdigest()
shaone = hashlib.sha1(chunk).hexdigest()
# Build the path and write the file
path = "%s/" % (config.getStorageDir())
for i in range(0, len(mdfive), 3):
path += "%s/" % (mdfive[i:i+3])
if not os.path.exists(path):
# I've read that this isn't the best way to do this, but I can
# always make it better later...
os.makedirs(path)
path += "%s.obj" % (shaone)
## At this point I should see if the file exists. If it does, verify
## checksums, otherwise write the file and then verify the checksums
if not os.path.isfile(path):
# Write the file
logging.debug("Adding new chunk at: %s" % (path))
writeResult = open(path, 'wb').write(chunk)
# Read the file back and verify the sums
verifyChunk = open(path, 'rb').read()
verifyMdfive = hashlib.md5(verifyChunk).hexdigest()
verifyShaone = hashlib.sha1(verifyChunk).hexdigest()
# If the sums match, return a 200 OK (return the sums for now)
# otherwise return a 500 error (we have a file that doesn't match)
if verifyMdfive == mdfive or verifyShaone == shaone:
numChunks += 1
return "Success"
# Return an error here
logging.error("There's a skeleton in my closet! PUT - %s" % (path))
return web.internalerror()
def DELETE(self, hashMD5, hashSHA1):
global config, numChunks
# Build the path and read the file
path = "%s/" % (config.getStorageDir())
for i in range(0, len(hashMD5), 3):
path += "%s/" % (hashMD5[i:i+3])
path += "%s.obj" % (hashSHA1)
## Should try catch around this file read...
if not os.path.isfile(path):
logging.info("File not found: %s" % (path))
return web.notfound()
chunk = open(path, 'rb').read()
# Verify the sums
mdfive = hashlib.md5(chunk).hexdigest()
shaone = hashlib.sha1(chunk).hexdigest()
# Delete the file. I'll leave deleting the directories for a cleanup
# task that'll be run by cron.
if mdfive == hashMD5 and shaone == hashSHA1:
os.remove(path)
numChunks -= 1
return "Success"
# Return an error here
logging.error("There's a skeleton in my closet! DELETE - %s" % (path))
return web.internalerror()
# Do I need to implement this ass an error, or just leave it out?
#def POST(self, hashMD5, hashSHA1):
# return "Not yet implemented. May not implement in the future."
# Config handling class. This should never be accessed by the clients directly.
class dpyfsConfig:
configFile = '/etc/dpyfs/storaged.conf'
configSection = 'storage'
# Config file entries always come back lower case.
ipaddr = '0.0.0.0'
port = '8080'
storagedir = '/var/dpyfs/data'
blocksize = '8'
# Initialize the configuration class
def __init__(self, conFile = None):
if conFile is not None:
self.configFile = conFile
# Load the config from the file
self.tmpConfig = ConfigParser.ConfigParser()
self.tmpConfig.read(self.configFile)
# Load the config from the proper section
def load(self, section = None):
if section is not None:
self.configSection = section
# Read the config options from the section. Need a try catch with better
# error handling here.
logging.debug("Read from config file:")
for key, value in self.tmpConfig.items(self.configSection):
setattr(self, key, value)
logging.debug(" %s = %s" % (key, value))
# Create an IP address for the webserver to use
def getIP(self):
return web.net.validip("%s:%s" % (self.ipaddr, self.port))
# Grab the blockSize and convert to bytes from kilobytes
def getBlockSize(self):
return int(self.blocksize) * 1024
# Grab the storage directory (make absolute path if needed)
def getStorageDir(self):
# FIXME: Make this convert to absolute path if necessary
return os.path.abspath(self.storagedir)
### MAIN ###############################################################################################################
def main():
global config, numChunks
# Turn on verbose logging. I'll make this config driven at a future date.
logging.basicConfig(level=logging.DEBUG)
# Parse the command line arguments.
argparser = argparse.ArgumentParser(description = "The storage daemon for the dpyfs project.")
argparser.add_argument('--configFile', help = "Configuration file to read from")
argparser.add_argument('--configSection', help = "Section in the configuration file to use")
args = argparser.parse_args()
logging.debug('Argument datastructure: \n %s' % (str(args)))
# Parse the config file.
if args.configFile is not None:
config = dpyfsConfig(args.configFile)
else:
config = dpyfsConfig()
if args.configSection is not None:
config.load(args.configSection)
else:
config.load()
# Setup the webserver for handling requests.
urls = ('/', 'index',
'/data/([0-9,a-f,A-F]+)/([0-9,a-f,A-F]+)', 'data',
'/info', 'info',
'/info/(.*)', 'info')
app = web.application(urls, globals())
app.notfound = notFound
app.internalerror = internalError
# Check chunks if there are any in the storage directory
numChunks = checkChunks(config.getStorageDir())
# Run the webserver
web.httpserver.runsimple(app.wsgifunc(), config.getIP())
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,013 |
18,889,266,176,917 |
c0fd7963fa6874337f2475eacf6a2cc352d2fa09
|
539b0aa0033a2fcafd1f657f33471ae414fec92a
|
/bot.py
|
92819b4dfc4c6d84ad3bf06b13ca95ea0de6d1f0
|
[] |
no_license
|
ShatterWorld/RedBot
|
https://github.com/ShatterWorld/RedBot
|
5156ac9ada30289df6265a913d95fb4f1d31834b
|
1d5bc4c2e8e3c2e62e994e219c29dc95fbad8176
|
refs/heads/master
| 2021-01-19T17:44:29.883522 | 2012-10-29T13:28:25 | 2012-10-29T13:28:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python3
from botlib import *
player = createPlayer()
#TODO: odlišit chování pro majoritní území (neútočit) a posledních cca 5 kol (útoky)
defenseReport = readFile(files['defenseReport'])
attackReport = readFile(files['attackReport'])
if getFoodTimeout() <= 1:
harvest()
elif attackReport and int(attackReport['zisk_ja_uzemi']) > 0 and player['soldiers'] > 2:
attack(attackReport['cil'])
elif defenseReport and (int(defenseReport['ztraty_ja_uzemi']) == 0 and player['soldiers'] > 3):
attack(defenseReport['utocnici'].split(',').pop().strip())
elif 2 * getAttackPower(player['soldiers'], player['armyLevel']) > getProduction() and getFoodTimeout() < 5:
increaseProduction()
else:
increaseArmyPower()
|
UTF-8
|
Python
| false | false | 2,012 |
10,574,209,521,284 |
b100182d4e7b8aee03d25c5071d9f784bf32028b
|
99e1a15d8f605be456f17608843c309dd8a3260f
|
/src/Screen/Console/Menu/ActionMenu/action_menu_view.py
|
4512e79f300f9054fcf5d22fc52ff3c9addeae13
|
[] |
no_license
|
sgtnourry/Pokemon-Project
|
https://github.com/sgtnourry/Pokemon-Project
|
e53604096dcba939efca358e4177374bffcf0b38
|
3931eee5fd04e18bb1738a0b27a4c6979dc4db01
|
refs/heads/master
| 2021-01-17T23:02:25.910738 | 2014-04-12T17:46:27 | 2014-04-12T17:46:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from Screen.Console.Menu.menu_entry_view import MenuEntryView
from kao_gui.console.console_widget import ConsoleWidget
class ActionMenuView(ConsoleWidget):
""" Action Menu View """
def __init__(self, menu):
""" """
self.menu = menu
self.entries = []
for entry in self.menu.entries:
self.entries.append(MenuEntryView(entry))
def draw(self):
""" Draw the window """
box = self.getMenuBox()
return self.drawMenuEntries(box)
def getMenuBox(self):
""" Draws the Menu Box """
lines = []
hdrLine ="-"*self.terminal.width
line = "|{0}|".format(" "*(self.terminal.width-2))
lines.append(hdrLine)
lines.append(line)
lines.append(line)
lines.append(hdrLine)
return lines
def drawMenuEntries(self, box):
""" Draws all Menu Entries """
menuText = []
cols = [.33, .66]
for entry in self.entries:
index = self.entries.index(entry)
col = cols[index%2]
rowIndex = (index > 1) + 1
length = entry.entry.getTextLength()
entryPosition = self.getEntryPosition(length, col, self.terminal.width)
box[rowIndex] = self.addEntryText(entry, int(entryPosition), box[rowIndex])
return box, (self.terminal.width, len(box))
def addEntryText(self, entry, position, line):
""" Adds the entry text to a line given and returns it """
newLine = line[:position]
newLine += entry.draw()
newLine += line[position+entry.entry.getTextLength():]
return newLine
def getEntryPosition(self, entryLength, xRatio, terminalWidth):
""" Gets the position of an entry """
centerLocation = xRatio*terminalWidth
centerLocation -= entryLength/2
return centerLocation
|
UTF-8
|
Python
| false | false | 2,014 |
13,056,700,586,012 |
bb2a9d1633dde3de5f2d846a2eca28a7923eccea
|
8feb00c0ed5f4ed8cecfb506d02b749986335bb4
|
/db/fakeflowdb/main.py
|
2df8acd441a8aeaf32716a5c75a7b08e264274c1
|
[] |
no_license
|
IsCaster/aboutfakeflow
|
https://github.com/IsCaster/aboutfakeflow
|
bd436e848b4168ff71512f680da29902ec8491df
|
3dbbbced2eb709a3b15d69dada146c2a0ad6e853
|
refs/heads/master
| 2016-09-06T07:01:52.345255 | 2014-05-13T09:07:47 | 2014-05-13T09:07:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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.
#
import cgi
import os
import urllib
import logging
import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
# Set the debug level
_DEBUG = True
class MissionInfo(db.Model):
shopkeeper = db.StringProperty();
message = db.StringProperty(required=False);#if it's True then MissionInfo.put() would fail,even if message is valued.
url = db.StringProperty();
site = db.StringProperty(required=False);
valid = db.BooleanProperty(default=True);
updateTime = db.DateTimeProperty(auto_now_add=True);
class BaseRequestHandler(webapp.RequestHandler):
"""Base request handler extends webapp.Request handler
It defines the generate method, which renders a Django template
in response to a web request
"""
def generate(self, template_name, template_values={}):
"""Generate takes renders and HTML template along with values
passed to that template
Args:
template_name: A string that represents the name of the HTML template
template_values: A dictionary that associates objects with a string
assigned to that object to call in the HTML template. The defualt
is an empty dictionary.
"""
# We check if there is a current user and generate a login or logout URL
user = users.get_current_user()
if user:
log_in_out_url = users.create_logout_url('/')
else:
log_in_out_url = users.create_login_url(self.request.path)
# We'll display the user name if available and the URL on all pages
values = {'user': user, 'log_in_out_url': log_in_out_url}
values.update(template_values)
# Construct the path to the template
directory = os.path.dirname(__file__)
path = os.path.join(directory, 'templates', template_name)
# Respond to the request by rendering the template
self.response.out.write(template.render(path, values, debug=_DEBUG))
class MainRequestHandler(BaseRequestHandler):
def get(self):
'''if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
template_values = {
'url': url,
'url_linktext': url_linktext,
}
'''
#for test
missionInfo=MissionInfo()
missionInfo.shopkeeper = "caster"
missionInfo.message = "fucking message"
missionInfo.url = "http://sfaasdf.taobao.com/asdf"
missionInfo.site = "hiwinwin"
missionInfo.put();
template_values={};
self.generate('default.html', template_values);
class QueryMissionInfoHandler(BaseRequestHandler):
# def get(self):
# self.getChats()
def post(self):
keyword = self.request.get('content')
query=db.GqlQuery("SELECT * FROM MissionInfo ");
missionInfos=query.fetch(20);
template_values={
'missionInfos' : missionInfos,
};
self.generate('missioninfo.html', template_values);
application = webapp.WSGIApplication(
[('/', MainRequestHandler),
('/missioninfo', QueryMissionInfoHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,014 |
17,480,516,917,291 |
61798ff4c4983626b89c3f2f6a8f23e467003449
|
adda496b84cdf17ff251f885fe0f9fc1d484139d
|
/src/mailserver/testapp/settings.py
|
0b3e0069c6d620ca1fe81d1063f051bfe448c7a1
|
[
"BSD-3-Clause"
] |
permissive
|
telenieko/django-mailserver
|
https://github.com/telenieko/django-mailserver
|
9b513fb1445178760ae6e78292b6c21d91beee3e
|
acc1888e0c225d7d45eace13406104d7bc08a6bf
|
refs/heads/master
| 2021-01-23T12:15:36.167409 | 2009-07-28T10:32:24 | 2009-07-28T10:32:24 | 199,888 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os
ADMINS = (
('John Smith', 'john@example.net'),
)
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = ':memory:'
TEST_DATABASE_NAME = ':memory:'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'mailserver', 'mailserver.testapp']
ROOT_URLCONF = 'mailserver.urls'
ROOT_MAILCONF = 'mailserver.testapp.mailbox'
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
|
UTF-8
|
Python
| false | false | 2,009 |
12,584,254,212,084 |
3bcfd02fb72fbe25479ab03957e845670d6ac3bc
|
151eec8b8d1a95b53f6af819497547aa9a8f5f20
|
/ordered_model/admin.py
|
a1887eb033a4bcdd63f18c5e8993edae9783a2da
|
[
"BSD-3-Clause"
] |
permissive
|
fusionbox/django-ordered-model
|
https://github.com/fusionbox/django-ordered-model
|
a930f49a86ec637f31ee15a57a5d252fa74283aa
|
20194add31af1de5d760cfff93e50a079bab5c74
|
refs/heads/master
| 2021-01-21T00:26:10.302055 | 2013-01-11T19:03:35 | 2013-01-11T19:03:35 | 7,565,121 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.contrib import admin
from django.contrib.admin.util import unquote
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
class OrderedModelAdmin(admin.ModelAdmin):
UP_LINK_FORMAT = '<a href="{url}"><img src="' + settings.STATIC_URL + 'ordered_model/arrow-up.gif" alt="Move up" /></a>'
DOWN_LINK_FORMAT = '<a href="{url}"><img src="' + settings.STATIC_URL + 'ordered_model/arrow-down.gif" alt="Move down" /></a>'
@property
def _model_info(self):
return '{0}_{1}_'.format(
self.model._meta.app_label,
self.model._meta.module_name,
)
def get_urls(self):
return patterns(
'',
url(r'^(.+)/move-up/$', self.admin_site.admin_view(self.move_up), name=self._model_info + 'move_up'),
url(r'^(.+)/move-down/$', self.admin_site.admin_view(self.move_down), name=self._model_info + 'move_down'),
) + super(OrderedModelAdmin, self).get_urls()
def move_up(self, request, object_id):
obj = get_object_or_404(self.model, pk=unquote(object_id))
obj.move_up()
return HttpResponseRedirect(reverse('admin:{0}changelist'.format(self._model_info)))
def move_down(self, request, object_id):
obj = get_object_or_404(self.model, pk=unquote(object_id))
obj.move_down()
return HttpResponseRedirect(reverse('admin:{0}changelist'.format(self._model_info)))
def move_up_down_links(self, obj):
up_url = reverse('admin:{0}move_up'.format(self._model_info), args=[obj.id])
down_url = reverse('admin:{0}move_down'.format(self._model_info), args=[obj.id])
return self.UP_LINK_FORMAT.format(url=up_url) + ' ' + self.DOWN_LINK_FORMAT.format(url=down_url)
move_up_down_links.allow_tags = True
move_up_down_links.short_description = _(u'Move')
|
UTF-8
|
Python
| false | false | 2,013 |
11,536,282,179,377 |
567607eb8f88edc8b6f7b21cb08ab653916b349b
|
0dba8ff8d218e2b5e23262f30a84d2e2011bc340
|
/notes/day3.py
|
452ed4486cf6bfdd4b62e0818b5a7e3a3aa55f67
|
[] |
no_license
|
pc2459/learnpy
|
https://github.com/pc2459/learnpy
|
1af14c5db3618b0bf4d163f4d300dbde635c3ac9
|
f0eb442bd201e9cf1ad98dbb1ca9f007a071b24b
|
refs/heads/master
| 2016-09-05T15:38:43.521081 | 2014-11-28T10:10:53 | 2014-11-28T10:10:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# CSV
import csv
import os
path = "/Users/Fo/Dropbox/LearnPython/repo"
# rb = "read binary", necessary in Python 2.x for CSV
# stick to r in P3
with open(os.path.join(path,"wonka.csv"),"rb") as file:
reader = csv.reader(file)
for row in reader:
print row
print "-----"
with open(os.path.join(path,"pastimes.csv"),"rb") as file,open(os.path.join(path,"categorized pastimes.csv"),"wb") as outfile:
reader = csv.reader(file)
writer = csv.writer(outfile)
next(reader) #skip the header
writer.writerow(["Name","Favourite Pastime","Type of Pastime"])
for row in reader:
if row[1].lower().find("fighting") != -1:
row.append("Combat")
else:
row.append("Other")
writer.writerow(row)
|
UTF-8
|
Python
| false | false | 2,014 |
2,388,001,867,595 |
efe8efa8e5dbe0c448aaeb165f12b5f2553fa127
|
67525a98af709f017285a825da712b718c12ed7f
|
/policy_enforcer/policy/alarm_quota.py
|
0357881c9c6583df7a585cd34962e1711c046811
|
[] |
no_license
|
HKervadec/Policy-Enforcer
|
https://github.com/HKervadec/Policy-Enforcer
|
2d0b3bcb4451a22819e86dc8cecda360c4c319b4
|
370f7f414bbd5e800b93a01be6ce999df73a6d37
|
refs/heads/master
| 2021-01-10T18:26:48.376640 | 2014-08-15T21:00:22 | 2014-08-15T21:00:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
from base_policy import BasePolicy
from common import extract_token, identify_create_alarm
class AlarmQuota(BasePolicy):
def __init__(self, max_alarm=2):
BasePolicy.__init__(self)
self.is_alarm = False
self.token_memory = {}
self.last_token = ""
self.max_alarm = max_alarm
def identify_request(self, a_request):
return identify_create_alarm(a_request)
def decide_fate(self, a_request):
"""
Reject if the token has already too much alarms.
"""
token = extract_token(a_request)
self.last_token = token
if not token in self.token_memory:
self.token_memory[token] = 0
return self.token_memory[token] < self.max_alarm
def gen_error_message(self):
return "Defined already too much alarms. Max: %d" % self.max_alarm
def test_response(self, response):
"""
Will test the response.
If the alarm creation was a success, it will increment
the counter for the last token used.
:param response: str The response
"""
if "HTTP/1.0 201 Created" in response:
self.token_memory[self.last_token] += 1
|
UTF-8
|
Python
| false | false | 2,014 |
13,460,427,520,605 |
46fca97c493c3133f9b5e2e5a3d3e59614afd161
|
43936cdb78496d39d641d51aa8e04b65ae6c8df9
|
/api/serializers.py
|
1a13d500bded2382e97b020a9f2e18d6ef9c55c1
|
[] |
no_license
|
frnhr/rsstest
|
https://github.com/frnhr/rsstest
|
258939f893250dd28eabfb17f1eb8a197c6112f0
|
41ded77510fbcc30fc3167b526066fa75b4c2e43
|
refs/heads/master
| 2020-05-16T15:58:31.539640 | 2014-08-25T10:22:16 | 2014-08-25T10:22:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from rest_framework import serializers
from rest_framework.fields import Field
from rest_framework.reverse import reverse
from api.models import Feed, Entry, Word, WordCount
class HyperlinkNestedSelf(Field):
"""
Use instead of default URL field on nested resources.
Because default URL field looks for url named "<resource>-detail", and url.reverse args are not compatible.
Note: a read-only field
"""
url = None
view_name = None
parents_lookup = None
self_field = None
obj_field = None
def __init__(self, view_name, parents_lookup=None, obj_field=None, self_field='pk', *args, **kwargs):
super(HyperlinkNestedSelf, self).__init__(*args, **kwargs)
self.view_name = view_name
self.parents_lookup = parents_lookup
self.self_field = self_field
self.obj_field = obj_field
def field_to_native(self, obj, field_name):
request = self.context.get('request', None)
parents_lookup = [[parent_lookup, 'pk'] if isinstance(parent_lookup, basestring) else parent_lookup
for parent_lookup in self.parents_lookup] # copy the list and make "pk" optional default
if self.obj_field is not None:
obj = getattr(obj, self.obj_field)
#@TODO this is a good point to unify with HyperlinkNestedViewField
def get_parent_data(parent_lookup, parent_data):
"""
Gather parent objects and field values
"""
if len(parent_lookup) < 1:
return parent_data
lookup = parent_lookup.pop()
parent_attr = lookup[0].split("__")[-1]
parent_field = lookup[1]
obj = parent_data[-1]['obj']
parent = getattr(obj, parent_attr)
parent_data.append({
'obj': parent,
'field': parent_field,
'value': getattr(parent, parent_field),
'lookup': lookup[0],
})
return get_parent_data(parent_lookup, parent_data)
parent_data = [{'obj': obj, 'field': self.self_field, 'value': getattr(obj, self.self_field) }, ]
parents_data = get_parent_data(parents_lookup, parent_data)
kwargs = {} # populate kwargs for URL reverse() call
for i, parent_data in enumerate(parents_data):
if i == 0:
kwargs[parent_data['field']] = parent_data['value']
else:
kwargs['parent_lookup_%s' % parent_data['lookup']] = parent_data['value']
return reverse(self.view_name, kwargs=kwargs, request=request)
#@TODO DRY it out, it's quite similar to HyperlinkNestedSelf
class HyperlinkNestedViewField(Field):
"""
Use to link to arbitrary url that has relationship with current resource.
Note: a read-only field
"""
url = None
view_name = None
parents_lookup = None
nested_field = None
def __init__(self, view_name, parents_lookup=None, nested_field=None, *args, **kwargs):
super(HyperlinkNestedViewField, self).__init__(*args, **kwargs)
self.view_name = view_name
self.parents_lookup = parents_lookup
self.nested_field = nested_field
def field_to_native(self, obj, field_name):
request = self.context.get('request', None)
parents_lookup = [[parent_lookup, 'pk'] if isinstance(parent_lookup, basestring) else parent_lookup
for parent_lookup in self.parents_lookup] # copy the list and make "pk" optional default
def get_parent_data(parent_lookup, parent_data):
"""
Gather parent objects and field values
"""
if len(parent_lookup) < 1:
return parent_data
lookup = parent_lookup.pop()
parent_attr = lookup[0].split("__")[-1]
parent_field = lookup[1]
obj = parent_data[-1]['obj']
parent = getattr(obj, parent_attr)
parent_data.append({
'obj': parent,
'field': parent_field,
'value': getattr(parent, parent_field),
'lookup': lookup[0],
})
return get_parent_data(parent_lookup, parent_data)
nested_obj = getattr(obj, self.nested_field).model() #@TODO not a nice trick, creating a dummy nested object
setattr(nested_obj, parents_lookup[-1][0], obj)
parent_data = [{'obj': nested_obj, 'field': 'pk', 'value': getattr(nested_obj, 'pk') }, ]
parents_data = get_parent_data(parents_lookup, parent_data)
kwargs = {} # populate kwargs for URL reverse() call
for i, parent_data in enumerate(parents_data):
if i == 0:
pass
else:
kwargs['parent_lookup_%s' % parent_data['lookup']] = parent_data['value']
return reverse(self.view_name, kwargs=kwargs, request=request)
# list serializers
class FeedListSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Feed
fields = ('_url', 'url', 'is_active', )
class EntryListSerializer(serializers.HyperlinkedModelSerializer):
_url = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ])
class Meta:
model = Entry
fields = ('_url', 'title', )
class WordField(serializers.CharField):
def field_to_native(self, obj, field_name):
"""
Given and object and a field name, returns the value that should be
serialized for that field.
"""
#return obj.word.word if obj else ''
return obj.word.word
class WordCountListSerializer(serializers.HyperlinkedModelSerializer):
_url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ])
word = WordField()
class Meta:
model = WordCount
fields = ('_url', 'word', 'count', )
class WordListSerializer(serializers.HyperlinkedModelSerializer):
class WordCountWordListSerializer(serializers.HyperlinkedModelSerializer):
_url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ])
entry = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ], obj_field='entry')
class Meta:
model = WordCount
fields = ('_url', 'entry', 'count', )
wordcounts = WordCountWordListSerializer()
class Meta:
model = Word
fields = ('_url', 'word', 'wordcounts', )
# detail serializers
class WordCountRootSerializer(serializers.HyperlinkedModelSerializer):
class FeedURLField(Field):
def field_to_native(self, obj, field_name):
return obj.entry.feed.url
class EntryTitleField(Field):
def field_to_native(self, obj, field_name):
return obj.entry.title
_url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ])
word = WordField()
entry = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ], obj_field='entry')
entry_title = EntryTitleField()
feed_url = FeedURLField()
class Meta:
model = WordCount
fields = ('_url', 'word', 'count', 'entry', 'entry_title', 'feed_url' )
class WordCountTopSerializer(serializers.Serializer):
class WordWordField(serializers.CharField):
def field_to_native(self, obj, field_name):
"""
Given and object and a field name, returns the value that should be
serialized for that field.
"""
#return obj.word.word if obj else ''
return obj['word__word']
word = WordWordField()
count = serializers.Field()
class WordCountSerializer(serializers.HyperlinkedModelSerializer):
_url = HyperlinkNestedSelf(view_name="feeds-entries-wordcount-detail", parents_lookup=['entry__feed', 'entry', ])
entry = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ], obj_field='entry')
word = WordField()
class Meta:
model = WordCount
fields = ('_url', 'entry', 'word', 'count', )
class EntrySerializer(serializers.HyperlinkedModelSerializer):
_url = HyperlinkNestedSelf(view_name="feeds-entry-detail", parents_lookup=['feed', ])
_wordcounts = HyperlinkNestedViewField(view_name='feeds-entries-wordcount-list', parents_lookup=['entry__feed', 'entry', ], nested_field="wordcounts")
class Meta:
model = Entry
fields = ('_url', '_wordcounts', 'feed', 'title', 'url', 'timestamp', 'text', )
class FeedSerializer(serializers.HyperlinkedModelSerializer):
_entries = HyperlinkNestedViewField(view_name='feeds-entry-list', parents_lookup=['feed', ], nested_field="entries")
class Meta:
model = Feed
fields = ('_url', '_entries', 'url', 'is_active', )
read_only_fields = ('url', )
|
UTF-8
|
Python
| false | false | 2,014 |
1,786,706,400,654 |
390429e22e1e00f7c1ec0146a9da7b420f47c3b0
|
d9765e7043065c553fa617289b40cd6dc353e75f
|
/topicalizer_original_version/makeprofiles.py
|
f483d51e3365c463fc8a52adde91a663d768c397
|
[
"MIT"
] |
permissive
|
mathewsbabu/Topicalizer
|
https://github.com/mathewsbabu/Topicalizer
|
7b8da349da6f4a927ca08c4ba6b8577b120237b3
|
f7b1fac5ee8378da2d87620f5b43c64922ae3d0a
|
refs/heads/master
| 2021-01-24T14:28:04.615777 | 2012-04-28T13:34:05 | 2012-04-28T13:34:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import re, os, codecs
from operator import itemgetter
from nltk_lite import tokenize
# n-gram structure function
def getNGramStructure(sourceFile):
# initialise n-gram dictionary
ngrams = {}
# read file
corpus = sourceFile.read()
# get tokens separated by whitespaces
tokenizedCorpus = tokenize.whitespace(corpus)
# go through each token
for token in tokenizedCorpus:
# split token in single characters
characters = list(token)
# copy character list
charactersBuffer = list(characters)
# initialise buffer
buffer1 = ''
# go through character list
for char1 in characters:
# write each n-gram to list
buffer1 += char1
ngrams[buffer1] = ngrams.get(buffer1, 0) + 1
# shift from character list copy
charactersBuffer.pop(0)
# initialise buffer
buffer2 = ''
# go through copy of character list
for char2 in charactersBuffer:
buffer2 += char2
ngrams[buffer2] = ngrams.get(buffer2, 0) + 1
# return n-grams
return ngrams
# get directory listing
listOfSourceFiles = os.listdir('languageprofiles/sourcefiles/')
# compile regular expression for files starting with '.'
dotAtBeginning = re.compile('^\.')
# go through each file
for sourceFileName in listOfSourceFiles:
# process, if no '.' at beginning of source file name
if dotAtBeginning.findall(sourceFileName):
pass
else:
# open source and profile file
sourceFile = codecs.open('languageprofiles/sourcefiles/' + sourceFileName, 'r', 'iso-8859-1')
profileFile = codecs.open('languageprofiles/' + sourceFileName, 'w', 'iso-8859-1')
# get n-grams from source file
ngrams = getNGramStructure(sourceFile)
# sort n-grams and go through each n-gram and write it to profile
for ngram, ngramValue in sorted(ngrams.iteritems(), key = itemgetter(1), reverse = True):
profileFile.write(ngram + '\n')
|
UTF-8
|
Python
| false | false | 2,012 |
15,144,054,702,595 |
455219adb328e33f221c314b8f30692f74494621
|
ca0d33992a5657c32484fd49ab30f4e0e8e72cba
|
/chapter3/antihtml.py
|
2c200eaf4bdf5c02a71a8dd30baba3f9c1b05f93
|
[] |
no_license
|
Haseebvp/Anand-python
|
https://github.com/Haseebvp/Anand-python
|
406ba01d89d0849be9a83ecb342454448267c552
|
d17c692d0aba29e96a3f55177a943c65ab0ec7a6
|
refs/heads/master
| 2020-04-07T13:37:46.590801 | 2013-10-21T07:03:27 | 2013-10-21T07:03:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import urllib
import sys
import re
def antihtml(url):
urllib.urlretrieve(sys.argv[1],'web')
a=re.findall(r'>[^<]+<',open('web').read())
for i in a:
print i[1:-1]
antihtml(sys.argv[1])
|
UTF-8
|
Python
| false | false | 2,013 |
10,496,900,076,304 |
01b481512545f0d7637a13411704eacb72d6bb16
|
e826643a05312aa8d63aa063fb9975a30e92841a
|
/teammaia_fbhack/facecards/facebook_client.py
|
a61446ccbd41a808bf2ea40f98e7d5e10e6ad4d8
|
[] |
no_license
|
gabrielhpugliese/teammaia_fbhack
|
https://github.com/gabrielhpugliese/teammaia_fbhack
|
e8fa20d895e08b145f714836cccd506b3f25cf23
|
7ffeb80a63cb563d73e7180bd74118c18e3b5092
|
refs/heads/master
| 2020-05-30T14:40:30.317906 | 2012-05-19T17:10:24 | 2012-05-19T17:10:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django_fukinbook.graph_api import GraphAPI
import random
class FacebookClient(GraphAPI):
def get_my_friends(self):
fql = '''SELECT uid FROM user WHERE
uid IN (SELECT uid2 FROM friend WHERE uid1 = me())'''
my_friends = self.get(path='fql', fql=fql)
return my_friends
def get_my_deck(self, limit=20):
fql = '''SELECT uid, name, friend_count, likes_count, pic_square
FROM user WHERE uid
IN (SELECT uid2 FROM friend WHERE uid1 = me())'''
my_friends = self.get(path='fql', fql=fql)
my_deck = []
random.shuffle(my_friends)
for friend in my_friends:
if limit > 0 and friend.get('friend_count') and friend.get('likes_count'):
my_deck.append(friend)
limit -= 1
return my_deck
|
UTF-8
|
Python
| false | false | 2,012 |
9,345,848,886,056 |
8933497dd98f2f77b35112b980ca368ef3e07c5f
|
9bef44307cf379a005f695ca65fd4cef2f6d2dda
|
/pymol-depricated/bsasa_centers_rot.py
|
33db7c61fd5ae2f5988639f0c0b0d5f0a4c10d19
|
[] |
no_license
|
willsheffler/lib
|
https://github.com/willsheffler/lib
|
a2e691cd1bccfc89989b161820616b57f9097c4d
|
b3e2781468a8fc25528a9f03c31e45af1cddd75a
|
refs/heads/master
| 2020-03-30T04:11:51.663557 | 2013-05-26T03:53:40 | 2013-05-26T03:53:40 | 1,439,853 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import pymol
from pymol import cmd
import sys,os,random,re
from pymol.cgo import *
import random
POCKET1 = """
@subgroup { Pocket1} dominant off
@vectorlist {Pck1} color=green
{ ca arg 7 } P 2.803, 8.648, 4.367 { ca arg 7 } L 2.803, 8.648, 4.367
{ cd1 leu 10 } L 1.867, 7.291, 9.151
{ cb lys 48 } P -6.083, 8.509, 14.663 { cb lys 48 } L -6.083, 8.509, 14.663
{ cg leu 49 } L -1.484, 10.094, 15.959
{ o asp 45 } P -4.102, 11.719, 14.877 { o asp 45 } L -4.102, 11.719, 14.877
{ cg leu 49 } L -1.484, 10.094, 15.959
{ o asp 45 } P -4.102, 11.719, 14.877 { o asp 45 } L -4.102, 11.719, 14.877
{ cb lys 48 } L -6.083, 8.509, 14.663
{ cg leu 49 } P -1.484, 10.094, 15.959 { cg leu 49 } L -1.484, 10.094, 15.959
{ cd1 leu 49 } L -0.561, 11.234, 15.551
{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899
{ cd1 leu 49 } L -0.561, 11.234, 15.551
{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899
{ cg leu 49 } L -1.484, 10.094, 15.959
{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742
{ cg leu 49 } L -1.484, 10.094, 15.959
{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742
{ cb asp 45 } L -3.836, 13.216, 11.899
{ od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086
{ od2 asp 45 } L -3.344, 13.600, 9.633
{ ce2 phe 37 } P -3.372, 14.257, 5.145 { ce2 phe 37 } L -3.372, 14.257, 5.145
{ od2 asp 45 } L -3.344, 13.600, 9.633
{ ce2 phe 37 } P -3.372, 14.257, 5.145 { ce2 phe 37 } L -3.372, 14.257, 5.145
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151
{ cd2 leu 10 } L 1.728, 8.986, 10.991
{ cg2 val 9 } P 0.064, 14.243, 6.530 { cg2 val 9 } L 0.064, 14.243, 6.530
{ ce2 phe 37 } L -3.372, 14.257, 5.145
{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283
{ ce2 phe 37 } L -3.372, 14.257, 5.145
{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283
{ cg2 val 9 } L 0.064, 14.243, 6.530
{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523
{ cd1 leu 10 } L 1.867, 7.291, 9.151
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ cd1 leu 10 } L 1.867, 7.291, 9.151
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ cg leu 10 } L 2.055, 8.756, 9.523
{ cg asp 45 } P -3.833, 12.831, 10.426 { cg asp 45 } L -3.833, 12.831, 10.426
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955
{ cg asp 45 } L -3.833, 12.831, 10.426
{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
{ cg asp 45 } L -3.833, 12.831, 10.426
{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
{ cg1 val 9 } L 0.536, 13.866, 8.955
{ cg2 val 9 } P 0.064, 14.243, 6.530 { cg2 val 9 } L 0.064, 14.243, 6.530
{ od2 asp 45 } L -3.344, 13.600, 9.633
{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
{ od2 asp 45 } L -3.344, 13.600, 9.633
{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
{ ce2 phe 37 } L -3.372, 14.257, 5.145
{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
{ cg2 val 9 } L 0.064, 14.243, 6.530
{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691
{ cd2 leu 49 } L -0.765, 8.757, 15.863
{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936
{ cd2 leu 49 } L -0.765, 8.757, 15.863
{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936
{ ce lys 48 } L -4.977, 5.372, 12.691
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ cd2 leu 49 } L -0.765, 8.757, 15.863
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ ce lys 48 } L -4.977, 5.372, 12.691
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ cd lys 48 } L -5.427, 6.804, 12.936
{ cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863
{ ce2 tyr 74 } L 3.275, 7.836, 14.253
{ cd1 leu 52 } P -3.221, 4.984, 16.696 { cd1 leu 52 } L -3.221, 4.984, 16.696
{ ce2 phe 73 } L 1.133, 3.773, 14.096
{ cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863
{ ce2 phe 73 } L 1.133, 3.773, 14.096
{ cd2 leu 49 } P -0.765, 8.757, 15.863 { cd2 leu 49 } L -0.765, 8.757, 15.863
{ cd1 leu 52 } L -3.221, 4.984, 16.696
{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691
{ ce2 phe 73 } L 1.133, 3.773, 14.096
{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691
{ cd1 leu 52 } L -3.221, 4.984, 16.696
{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955
{ cd1 ile 13 } L 2.644, 12.675, 12.899
{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988
{ cd1 leu 10 } L 1.867, 7.291, 9.151
{ c gln 6 } P 0.580, 9.529, 4.825 { c gln 6 } L 0.580, 9.529, 4.825
{ cd1 leu 10 } L 1.867, 7.291, 9.151
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ o gln 6 } L 0.873, 9.804, 5.988
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ c gln 6 } L 0.580, 9.529, 4.825
{ cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076
{ cd gln 6 } L -3.929, 7.466, 4.075
{ cd1 ile 13 } P 2.644, 12.675, 12.899 { cd1 ile 13 } L 2.644, 12.675, 12.899
{ cb asp 45 } L -3.836, 13.216, 11.899
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ oe1 gln 6 } L -3.369, 6.382, 4.261
{ cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222
{ oe1 gln 6 } L -3.369, 6.382, 4.261
{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283
{ cg gln 6 } L -3.140, 8.762, 4.076
{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523
{ cd2 leu 10 } L 1.728, 8.986, 10.991
{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151
{ nz lys 48 } L -4.743, 5.101, 11.247
{ oe1 gln 6 } P -3.369, 6.382, 4.261 { oe1 gln 6 } L -3.369, 6.382, 4.261
{ nz lys 48 } L -4.743, 5.101, 11.247
{ oe1 gln 6 } P -3.369, 6.382, 4.261 { oe1 gln 6 } L -3.369, 6.382, 4.261
{ cd1 leu 10 } L 1.867, 7.291, 9.151
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ nz lys 48 } L -4.743, 5.101, 11.247
{ od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086
{ cd lys 48 } L -5.427, 6.804, 12.936
{ cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075
{ nz lys 48 } L -4.743, 5.101, 11.247
{ cd gln 6 } P -3.929, 7.466, 4.075 { cd gln 6 } L -3.929, 7.466, 4.075
{ oe1 gln 6 } L -3.369, 6.382, 4.261
{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076
{ ce2 phe 37 } L -3.372, 14.257, 5.145
{ c gln 6 } P 0.580, 9.529, 4.825 { c gln 6 } L 0.580, 9.529, 4.825
{ ca arg 7 } L 2.803, 8.648, 4.367
{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027
{ ca arg 7 } L 2.803, 8.648, 4.367
{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027
{ c gln 6 } L 0.580, 9.529, 4.825
{ cd1 leu 49 } P -0.561, 11.234, 15.551 { cd1 leu 49 } L -0.561, 11.234, 15.551
{ cd2 leu 49 } L -0.765, 8.757, 15.863
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ ce2 tyr 74 } L 3.275, 7.836, 14.253
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ cd1 leu 49 } L -0.561, 11.234, 15.551
{ nz lys 48 } P -4.743, 5.101, 11.247 { nz lys 48 } L -4.743, 5.101, 11.247
{ ce2 phe 73 } L 1.133, 3.773, 14.096
{ ce lys 48 } P -4.977, 5.372, 12.691 { ce lys 48 } L -4.977, 5.372, 12.691
{ nz lys 48 } L -4.743, 5.101, 11.247
{ cd1 leu 10 } P 1.867, 7.291, 9.151 { cd1 leu 10 } L 1.867, 7.291, 9.151
{ ce lys 48 } L -4.977, 5.372, 12.691
{ cg gln 6 } P -3.140, 8.762, 4.076 { cg gln 6 } L -3.140, 8.762, 4.076
{ nz lys 48 } L -4.743, 5.101, 11.247
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ cd gln 6 } L -3.929, 7.466, 4.075
{ cb gln 6 } P -1.660, 8.539, 4.337 { cb gln 6 } L -1.660, 8.539, 4.337
{ cg gln 6 } L -3.140, 8.762, 4.076
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ cg leu 49 } L -1.484, 10.094, 15.959
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ cb asp 45 } L -3.836, 13.216, 11.899
{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955
{ od2 asp 45 } L -3.344, 13.600, 9.633
{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955
{ cb asp 45 } L -3.836, 13.216, 11.899
{ cb lys 48 } P -6.083, 8.509, 14.663 { cb lys 48 } L -6.083, 8.509, 14.663
{ cd lys 48 } L -5.427, 6.804, 12.936
{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988
{ cb val 9 } L 0.829, 13.398, 7.537
{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cg leu 10 } P 2.055, 8.756, 9.523 { cg leu 10 } L 2.055, 8.756, 9.523
{ cg asp 45 } L -3.833, 12.831, 10.426
{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955
{ cg leu 10 } L 2.055, 8.756, 9.523
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ cd1 ile 13 } L 2.644, 12.675, 12.899
{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936
{ cg leu 49 } L -1.484, 10.094, 15.959
{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899
{ cd lys 48 } L -5.427, 6.804, 12.936
{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742
{ cd lys 48 } L -5.427, 6.804, 12.936
{ cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
{ cg leu 10 } L 2.055, 8.756, 9.523
{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027
{ nz lys 48 } L -4.743, 5.101, 11.247
{ cg leu 49 } P -1.484, 10.094, 15.959 { cg leu 49 } L -1.484, 10.094, 15.959
{ cd2 leu 49 } L -0.765, 8.757, 15.863
{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742
{ cb lys 48 } L -6.083, 8.509, 14.663
{ cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222
{ nz lys 48 } L -4.743, 5.101, 11.247
{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027
{ cd2 leu 2 } L -1.227, 2.531, 4.222
{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283
{ cb gln 6 } L -1.660, 8.539, 4.337
{ ce2 phe 73 } P 1.133, 3.773, 14.096 { ce2 phe 73 } L 1.133, 3.773, 14.096
{ ce2 tyr 74 } L 3.275, 7.836, 14.253
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ ce2 phe 73 } L 1.133, 3.773, 14.096
{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ o gln 6 } P 0.873, 9.804, 5.988 { o gln 6 } L 0.873, 9.804, 5.988
{ cg leu 10 } L 2.055, 8.756, 9.523
{ cg asp 45 } P -3.833, 12.831, 10.426 { cg asp 45 } L -3.833, 12.831, 10.426
{ od2 asp 45 } L -3.344, 13.600, 9.633
{ ca asp 45 } P -4.884, 12.484, 12.742 { ca asp 45 } L -4.884, 12.484, 12.742
{ o asp 45 } L -4.102, 11.719, 14.877
{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ od1 asp 45 } P -4.455, 11.853, 10.086 { od1 asp 45 } L -4.455, 11.853, 10.086
{ nz lys 48 } L -4.743, 5.101, 11.247
{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283
{ o gln 6 } L 0.873, 9.804, 5.988
{ cd lys 48 } P -5.427, 6.804, 12.936 { cd lys 48 } L -5.427, 6.804, 12.936
{ nz lys 48 } L -4.743, 5.101, 11.247
{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899
{ od1 asp 45 } L -4.455, 11.853, 10.086
{ cb asp 45 } P -3.836, 13.216, 11.899 { cb asp 45 } L -3.836, 13.216, 11.899
{ cg asp 45 } L -3.833, 12.831, 10.426
{ ca gln 6 } P -0.815, 9.814, 4.283 { ca gln 6 } L -0.815, 9.814, 4.283
{ cb val 9 } L 0.829, 13.398, 7.537
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ cg asp 45 } L -3.833, 12.831, 10.426
{ cg1 val 9 } P 0.536, 13.866, 8.955 { cg1 val 9 } L 0.536, 13.866, 8.955
{ cd2 leu 10 } L 1.728, 8.986, 10.991
{ cd2 leu 2 } P -1.227, 2.531, 4.222 { cd2 leu 2 } L -1.227, 2.531, 4.222
{ cd1 leu 10 } L 1.867, 7.291, 9.151
{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027
{ oe1 gln 6 } L -3.369, 6.382, 4.261
{ cd1 leu 2 } P 1.057, 3.170, 5.027 { cd1 leu 2 } L 1.057, 3.170, 5.027
{ cb gln 6 } L -1.660, 8.539, 4.337
{ cd2 leu 10 } P 1.728, 8.986, 10.991 { cd2 leu 10 } L 1.728, 8.986, 10.991
{ od1 asp 45 } L -4.455, 11.853, 10.086
1.867, 7.291, 9.151
"""
def loadcenters(file,nickname=None):
if nickname is None:
nickname = file.split('/')[-1][:4]
print nickname
cmd.load(file,nickname)
cmd.do("useRosettaRadii")
csel = nickname+"centers"
psel = nickname+"rot"
print nickname+" & resi 500-999"
cmd.select(csel,nickname+" & resi 500-999")
cmd.select(psel,nickname+" & resi 0-500")
cmd.do("useOccRadii "+csel)
cmd.hide('ev',nickname)
cmd.show('sph',csel)
cmd.show('cart',psel)
cmd.show('line',psel)
cmd.color('white',psel)
def loadpair(file):
id = file.split('/')[-1][:4]
loadcenters(file,id+'nat')
loadcenters(file[:-17]+'_decoy_sasa_centers.pdb',id+'decoy')
d = id+'decoy'
n = id+'nat'
cmd.align(n,d)
class LRvolume:
def __init__(self,line): # doesn't handle arbitrary order!
rex = "^.*<volume"
for tag in ("color","name","sa","v"):
rex += "\s+%s=(\S+)"%tag
rex += ".*>"
print rex
self.color,self.name,self.sa,self.vol = re.match(rex,line).groups()
class LRarc:
def __init__(self,line):
rex = "^.*<arc"
names = ("radius","theta_hi","theta_lo","x","y","z")
for tag in names:
rex += "\s+%s=(\S+)"%tag
rex += "\s*>"
print rex
vals = re.match(rex,line).groups()
for i in range(len(names)):
setattr(self,names[i],vals[i])
def __repr__(self):
return ",".join((self.radius,self.theta_hi,self.theta_lo,self.x,self.y,self.z))
s = "<volume color=white name=0 sa=4470.66 v=17019.7>"
a = "<arc radius=1.98063 theta_hi=180 theta_lo=0 x=-4.075 y=15.097 z=-6.52939> </arc>"
v = LRvolume(s)
r = LRarc(a)
print r
# { cb val 9 } P 0.829, 13.398, 7.537 { cb val 9 } L 0.829, 13.398, 7.537
# { cg1 val 9 } L 0.536, 13.866, 8.955
def parsekin(s):
for l in s.split():
pass
#parsekin(POCKET1)
#cmd.set("cgo_line_width",5)
#obj = [
# BEGIN, LINES,
# LINEWIDTH, 50,#
#
# VERTEX, 2.803, 8.648, 4.367,
# VERTEX, 1.867, 7.291, 9.151,#
#
# END
# ]
#
#cmd.load_cgo(obj,'cgo'+`random.random()`)
def noclip():
print "noclip!"
cmd.clip("near",100)
cmd.clip("far",-100)
cmd.extend("loadcenters",loadcenters)
cmd.extend("noclup",noclip)
|
UTF-8
|
Python
| false | false | 2,013 |
9,955,734,194,334 |
ce10f3748074891a168f49f5cf9944e44e356d6c
|
15212dbdf5d8cae2babb884180b90c28087cd18e
|
/deprecated/run.py
|
616e4b6d0b0da37213cb2114f9bdbff02d307220
|
[
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"GPL-2.0-or-later"
] |
non_permissive
|
lbybee/newsbefore
|
https://github.com/lbybee/newsbefore
|
05e30e529145bc7f71d69c3f870d9b9acfa71bda
|
b6e77839cea2004035c05247cf8a8b2bd74245a3
|
refs/heads/master
| 2018-12-28T12:19:23.710838 | 2014-01-12T18:49:40 | 2014-01-12T18:49:40 | 11,436,051 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import ConfigParser
import reddit_scraper
import twitter_scraper
Config = ConfigParser.ConfigParser()
Config.read("newsbefore.config")
#user data for twitter, reddit and MySQL db
t_consumer_key = Config.get("Twitter", "consumer_key")
t_consumer_secret = Config.get("Twitter", "consumer_secret")
t_access_token = Config.get("Twitter", "access_token")
t_access_token_secret = Config.get("Twitter", "access_token_secret")
r_username = Config.get("reddit", "username")
r_password = Config.get("reddit", "password")
r_subreddits = Config.get("reddit", "subreddits").split(",")
#twitter
t_api = twitter_scraper.authorize(t_consumer_key, t_consumer_secret,
t_access_token, t_access_token_secret)
trends = twitter_scraper.getTrends(t_api)
twitter_dict = twitter_scraper.getTrendTweets(trends, t_api)
#reddit
r_api = reddit_scraper.authorize(r_username, r_password)
reddit_dict = reddit_scraper.getAllStories(r_api, r_subreddits)
|
UTF-8
|
Python
| false | false | 2,014 |
15,925,738,759,358 |
25a485891226f616d6f5c2b3451e7aa0bdbc9799
|
76f2df1e54d187be31740cd97f0201544b7a518f
|
/GDUT/SuperPy/src/SuperPy.py
|
d9c275e0a12bca4d0891d273991d2c0b9fa0f48e
|
[] |
no_license
|
donwoc/icancode
|
https://github.com/donwoc/icancode
|
3ac3c067ebddad5b446e0b2f4d8d87a79c521878
|
45174cf95382154d26983b9781b598b2fb634871
|
refs/heads/master
| 2021-01-01T17:09:58.123909 | 2010-12-13T14:24:56 | 2010-12-13T14:24:56 | 39,470,347 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import wx
from math import *
class TestPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
self.inputFrom = wx.TextCtrl(self, 100, pos = wx.Point(27, 58), size = wx.Size(500,20), style = wx.NO_BORDER)
bmpBt = wx.Bitmap("compute.png")
mask = wx.Mask(bmpBt, wx.BLUE)
bmpBt.SetMask(mask)
self.computeBtn = wx.BitmapButton(self, 101, bmpBt, pos = wx.Point(530, 56), size = wx.Size(20,20) )
wx.EVT_BUTTON(self, 101, self.compute)
self.outputFrom = wx.TextCtrl(self, 102, pos = wx.Point(18, 126), size = wx.Size(545,183), style = wx.TE_MULTILINE|wx.TE_PROCESS_ENTER|wx.NO_BORDER)
image_file = 'UI.png'
bmp = wx.Bitmap(image_file)
wx.StaticBitmap(self, -1, bmp, (0, 0))
self.Show(True)
def compute(self, event):
tmp = str(self.inputFrom.GetValue())
if ( len(tmp) != 0 ):
exp = tmp
self.outputFrom.write( tmp + '\n' + '=' + str(eval(exp)) + '\n\n' )
app = wx.App( redirect = False )
frame = wx.Frame(None, -1, title = "SuperPy Alpha", size = (590, 355))
imp = TestPanel(frame, -1)
frame.Show(True)
app.MainLoop()
|
UTF-8
|
Python
| false | false | 2,010 |
4,818,953,315,853 |
b6df555ebe490b92004dcaa6cfb62772ba639243
|
e90f51435798f7ca806b4513cfe09c5462fac9cd
|
/publishconf.py
|
c81734f493ba85d94824a8f0731c084636ab2f19
|
[] |
no_license
|
offlinehacker/blog-xtruder-net
|
https://github.com/offlinehacker/blog-xtruder-net
|
23a633fb3b0f078689e8400fa36466abfa5699dc
|
103a492930d82d318d2c59454a4f5067b7e93c37
|
refs/heads/master
| 2021-01-18T18:25:17.802920 | 2014-09-22T10:01:02 | 2014-09-22T10:01:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Jaka Hudoklin'
AUTHOR_EMAIL = u'jakahudoklin@gmail.com'
SITENAME = u'Jaka Hudoklin'
SITEURL = 'http://www.jakahudoklin.com'
TIMEZONE = 'Europe/Ljubljana'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = "feeds/all.atom.xml"
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('Python.org', 'http://python.org/'),
('Jinja2', 'http://jinja.pocoo.org/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (
('', 'http://www.github.com/offlinehacker'),
('', 'http://www.facebook.com/offlinehacker'),
('', 'http://www.twitter.com/offlinehacker')
)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True
PLUGIN_PATHS = ['plugins']
PLUGINS = ['sitemap']
SITEMAP = {
'format': 'xml',
'priorities': {
'articles': 0.5,
'indexes': 0.5,
'pages': 0.5
},
'changefreqs': {
'articles': 'monthly',
'indexes': 'daily',
'pages': 'monthly'
}
}
THEME = "theme/"
GRV_URL = "https://sl.gravatar.com/avatar/07de32bbf131a9bd6f9678105b05f84a?s=300"
WHAT_DO_I_THINK = "Just working on some awesome projects...<br></br>Want to know more? ping me!"
GOOGLE_ANALYTICS = "UA-44181448-1"
DISQUS_SITENAME = "blogxtrudernet"
TWITTER_USERNAME = "offlinehacker"
|
UTF-8
|
Python
| false | false | 2,014 |
19,533,511,273,683 |
c46037b593219f92ec89f433a23d4ceec0478d45
|
bbb2dd42388eb2bf3520aacebf443fd1884a2086
|
/convert_data_in.py
|
75742510dd556acda6c2bcd01e10395f4feab534
|
[] |
no_license
|
peterhm/dismod-mr_rate_validation
|
https://github.com/peterhm/dismod-mr_rate_validation
|
d318a533ee95eecd3c0f0cadc11561197cc3e1a6
|
f394feec1e9bac6c1df19503b7ae1eb90e884d12
|
refs/heads/master
| 2016-09-05T12:55:14.563338 | 2013-06-03T16:57:23 | 2013-06-03T16:57:23 | 7,414,397 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''This module creates data_in.csv for dismod_spline'''
import sys
sys.path += ['.', '..', '/homes/peterhm/gbd/', '/homes/peterhm/gbd/book']
import pylab as pl
import os
import pandas
import dismod3
reload(dismod3)
import model_utilities as mu
reload(mu)
def convert_data_type(data_type):
integrand = {'p': 'prevalence',
'i': 'incidence',
'r': 'remission',
'f': 'r_excess',
'pf': 'r_prevalence',
'csmr': 'r_specific',
'm_all': 'r_all',
'm_with': 'r_with',
'm': 'r_other',
'smr': 'r_standard',
'rr': 'relative_risk',
'X': 'duration'}
return integrand[data_type]
def empty_data_in(ix):
return pandas.DataFrame(index=ix, columns=['integrand', 'meas_value', 'meas_stdev', 'sex', 'age_lower', 'age_upper', 'time_lower', 'time_upper', 'm_sub', 'm_region', 'm_super', 'x_sex'], dtype=object)
def build_data_in(dm3, data_type, model_num):
# find standard error and use it for standard deviation
dm3 = mu.create_uncertainty(dm3, 'log_normal')
# create data file
data_in = empty_data_in(dm3.input_data.index)
# add covariates
cov = dm3.input_data.filter(like='x_')
data_in = data_in.join(pandas.DataFrame(cov,columns=['']))
cov_z = dm3.input_data.filter(like='z_')
if len(cov_z.columns) != 0:
data_in = data_in.join(pandas.DataFrame(cov_z,columns=['']))
# add data
data_in['integrand'] = convert_data_type(data_type)
data_in['meas_value'] = dm3.input_data['value']
data_in['meas_stdev'] = dm3.input_data['standard_error']
data_in['sex'] = dm3.input_data['sex']
data_in['age_lower'] = dm3.input_data['age_start']
data_in['age_upper'] = dm3.input_data['age_end'] + 1.0
data_in['time_lower'] = dm3.input_data['year_start']
data_in['time_upper'] = dm3.input_data['year_end'] + 1.0
data_in['x_sex'] = dm3.input_data['sex'].map(dict(male=.5, female=-.5, total=0))
# create data hierarchy
model = mu.load_new_model(model_num, 'all', data_type)
superregion = set(model.hierarchy.neighbors('all'))
region = set(pl.flatten([model.hierarchy.neighbors(sr) for sr in model.hierarchy.neighbors('all')]))
country = set(pl.flatten([[model.hierarchy.neighbors(r) for r in model.hierarchy.neighbors(sr)] for sr in model.hierarchy.neighbors('all')]))
# create data area levels
for i in dm3.input_data.index:
if dm3.input_data.ix[i,'area'] in country:
data_in.ix[i,'m_sub'] = dm3.input_data.ix[i,'area']
data_in.ix[i,'m_region'] = model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0]
data_in.ix[i,'m_super'] = model.hierarchy.in_edges(model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0])[0][0]
elif dm3.input_data.ix[i,'area'] in region:
data_in.ix[i,'m_region'] = dm3.input_data.ix[i,'area']
data_in.ix[i,'m_super'] = model.hierarchy.in_edges(dm3.input_data.ix[i,'area'])[0][0]
elif dm3.input_data.ix[i,'area'] in superregion:
data_in.ix[i,'m_super'] = dm3.input_data.ix[i,'area']
return data_in
|
UTF-8
|
Python
| false | false | 2,013 |
9,646,496,575,924 |
286e3411e999837c22cb10f7941c8564258f6cfa
|
0a7d4bb8d6b27076419fca2544bffff09ed921bc
|
/dota/scripts/json2hdf5.py
|
a1b42504e4cf681a5abed7813118c329d882b6ff
|
[
"MIT"
] |
permissive
|
darklordabc/dota
|
https://github.com/darklordabc/dota
|
dbed47a24308cd98a9b396ef24e7a3e45229ef17
|
38f4021370bb41a94d3edfd8e844e0ed43f4c9a8
|
refs/heads/master
| 2021-01-24T15:34:18.715496 | 2014-05-12T20:24:32 | 2014-05-12T20:24:32 | 66,687,376 | 1 | 0 | null | true | 2016-08-27T00:34:08 | 2016-08-27T00:34:07 | 2015-12-24T01:15:41 | 2014-06-05T02:46:21 | 3,600 | 0 | 0 | 0 | null | null | null |
# -*- coding: utf-8 -*-
"""
Given a data directory, convert all details responses to HDF5Store.
"""
import os
import json
from pathlib import Path
import argparse
import numpy as np
import pandas as pd
from dota import api
from dota.helpers import cached_games
parser = argparse.ArgumentParser("Convert JSON DetailsResponses to HDF5.")
parser.add_argument("--data_dir", type=str, help="Path to data direcotry.",
default='~/sandbox/dota/data/pro/')
parser.add_argument("--hdf_store", type=str, help="Path to the HDF Store",
default='~/sandbox/dota/data/pro/pro.h5')
def add_by_side(df, dr, item, side):
"""
Modifies df in place.
"""
vals = getattr(dr, item)
if callable(vals):
vals = vals()
if isinstance(vals, dict):
vals = vals.get(side, np.nan)
df.loc[(df.team == side), item] = vals
def append_to_store(store, dfs, key='drs'):
if dfs == []:
return None
dfs = pd.concat(dfs, ignore_index=True)
# will be float if any NaN. Some won't have
# NaNs so need to recast
cols = ['radiant_team_id', 'dire_team_id', 'account_id']
dfs[cols] = dfs[cols].astype(np.float64)
dfs.to_hdf(str(store), key=key, append=True)
def format_df(dr):
mr = dr.match_report().reset_index()
# avoid all objects
mr['team'] = mr.team.map({'Radiant': 0, 'Dire': 1})
mr['hero'] = mr.hero.map(api._hero_names_to_id)
for item in ['barracks_status', 'tower_status']:
for side in [0, 1]:
add_by_side(mr, dr, item, side)
for item in ['dire_team_id', 'radiant_team_id']:
mr[item] = getattr(dr, item, np.nan)
mr['duration'] = dr.duration
mr['game_mod'] = dr.game_mode
mr['start_time'] = pd.to_datetime(dr.start_time.isoformat())
return mr
def main():
args = parser.parse_args()
store = os.path.expanduser(args.hdf_store)
data_dir = Path(os.path.expanduser(args.data_dir))
cached = cached_games(data_dir)
# first time. Generate the store
if not os.path.isfile(store):
pd.HDFStore(store)
with pd.get_store(store) as s:
try:
stored = s.select('drs')['match_id'].unique()
except KeyError:
stored = []
new_games = filter(lambda x: int(x.stem) not in stored, cached)
dfs = []
i = 0 # if no new games
for i, game in enumerate(new_games, 1):
dr = api.DetailsResponse.from_json(str(game))
dfs.append(format_df(dr))
else:
append_to_store(store, dfs)
print("Added {} games.".format(i))
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,014 |
8,126,078,174,928 |
5442bb5499353dd3d5667af679270d0dd9d9e7af
|
355f4a4c9013c0e79dd2935463888bd4b17ff8fd
|
/src/LuxFire/Renderer/Client.py
|
553f155dba158139fc7f1d896095995065a05e4e
|
[] |
no_license
|
LuxRender/LuxFire
|
https://github.com/LuxRender/LuxFire
|
d8fdb834af0ab3649c5c4befc4fc23b9f98b05f8
|
60a7788dbaf9cf68c0a5252fcde7fba84c3693d4
|
refs/heads/master
| 2021-01-03T13:59:33.488920 | 2011-01-05T16:46:28 | 2011-01-05T16:46:28 | 240,095,221 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf8 -*-
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# --------------------------------------------------------------------------
# LuxFire Distributed Rendering System
# --------------------------------------------------------------------------
#
# Authors:
# Doug Hammond
#
# 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, see <http://www.gnu.org/licenses/>.
#
# ***** END GPL LICENCE BLOCK *****
#
"""
Renderer.Client is a local proxy for a remote Renderer.Server context. We have
to create a local Client proxy because of the binary (non-picklable) nature of
the LuxRender Context which is being served.
"""
# Pyro Imports
import Pyro
from ..Client import ListLuxFireGroup, ServerLocator, ClientException
class RemoteCallable(object):
'''
Function proxy for remote pylux.Context
'''
# Remote RenderServer object to call
RemoteRenderer = None
# Name of the Context method to call
remote_method = None
def __init__(self, RemoteRenderer, remote_method):
'''
Initialise callable with a RemoteRenderer and a method name
'''
self.RemoteRenderer = RemoteRenderer
self.remote_method = remote_method
def __call__(self, *a, **k):
'''
Proxy calling this object to the remote Context
'''
try:
return self.RemoteRenderer.luxcall(self.remote_method, *a, **k)
except Exception as err:
# Get meaningful output from remote exception;
# Boost.Python exceptions cannot be pickled
print(''.join( Pyro.util.getPyroTraceback(err) ))
class RendererClient(object):
'''
Client proxy for a remote RendererServer object
'''
# Remote RenderServer object
RemoteRenderer = None
# List of methods and attributes in the remote Context object
RemoteContextMethods = []
def __init__(self, RemoteRenderer):
'''
Initialise client object with the server object, and ask the
server which methods and attributes the remote Context has
'''
self.RemoteRenderer = RemoteRenderer
self.RemoteContextMethods = RemoteRenderer.get_context_methods()
def __getattr__(self, m):
'''
When asking this client for an attribute or method, first check
to see if we should call the remote Context, if not then try
to find the attribute or method in the RendererServer
'''
if m in self.RemoteContextMethods and m != 'name':
return RemoteCallable(self.RemoteRenderer, m)
elif not m.startswith('_'):
return getattr(self.RemoteRenderer, m)
else:
raise AttributeError('Cannot access remote private members')
def RendererGroup():
LuxSlavesNames = ListLuxFireGroup('Renderer')
if len(LuxSlavesNames) > 0:
slaves = {}
for LN in LuxSlavesNames:
try:
RS = ServerLocator.Instance().get_by_name(LN)
LS = RendererClient(RS)
slaves[LN] = (LS, RS)
except Exception as err:
raise ClientException('Error with remote renderer %s: %s' % (LN, err))
return slaves
else:
raise ClientException('No Renderers found')
if __name__ == '__main__':
try:
slaves = RendererGroup()
print(slaves)
except ClientException as err:
print('%s'%err)
|
UTF-8
|
Python
| false | false | 2,011 |
17,428,977,309,518 |
25ceb40c8b3145a9f3071fafb383c08dd7817783
|
d407f3bdbcdf70920bb8f0790c401dfb023af5de
|
/sound/sound.gypi
|
9a20d55d0b502dfbcf6e022162b7e3518c88f6c2
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
non_permissive
|
mathall/nanaka
|
https://github.com/mathall/nanaka
|
3f02ffb4f2e19af3446d43af61226c122b18498c
|
0304f444702318a83d221645d4e5f3622082c456
|
refs/heads/master
| 2016-09-11T04:01:22.986788 | 2014-04-16T20:31:46 | 2014-04-26T12:56:01 | 11,401,646 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
{
'sources': [
'../sound/OggDecoder.cpp',
'../sound/OggDecoder.h',
'../sound/Sound.cpp',
'../sound/Sound.h',
'../sound/SoundDecoder.h',
'../sound/SoundLoader.cpp',
'../sound/SoundLoader.h',
'../sound/SoundResource.h',
],
}
|
UTF-8
|
Python
| false | false | 2,014 |
1,417,339,210,951 |
e48f5e8f53c75bcea3e55b97396f39c9ab269c0f
|
a1d819a14eb57e81b3c7a03a35329c54e51a7769
|
/pi.py
|
e5585dfe5822037b7fef2b7c006f3337958a5aa7
|
[
"GPL-2.0-only"
] |
non_permissive
|
talonsensei/abmining
|
https://github.com/talonsensei/abmining
|
2347852263259cfdb671c6b0ad511e44962f399a
|
8ce80b6c434e2815ed7c6939b71eb8f8e56bc79e
|
refs/heads/master
| 2021-01-18T07:43:21.439302 | 2014-02-14T21:27:48 | 2014-02-14T21:27:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
__author__ = 'csaba'
__email__ = 'csakis[at]lanl[dot]gov'
import sys
import os
from collections import defaultdict
"""This script calculates the mean pI of CDR3s. It uses the unique CDR3 file (bins_*.cdr3) output as the input file.
The calculation is based on
Bjellqvist, B.,Hughes, G.J., Pasquali, Ch., Paquet, N., Ravier, F.,
Sanchez, J.-Ch., Frutiger, S. & Hochstrasser, D.F. The focusing
positions of polypeptides in immobilized pH gradients can be predicted
from their amino acid sequences. Electrophoresis 1993, 14, 1023-1031.
MEDLINE: 8125050 """
# Building the pI library
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
if not os.path.isfile(os.path.join(__location__, 'pi.csv')):
print 'You need to download the pi.csv file from the ionpython website!'
print 'http://sourceforge.net/projects/ionpython/'
sys.exit(
'Please run the program after you copied the hydro.csv file into the directory where all the other python scripts are located!')
pi_file = open(os.path.join(__location__, 'pi.csv')) # the csv file containing the translation table
pi_dict = {}
for line in pi_file.readlines():
line = line[:-1] # removing \n
pi_list = line.split(',')
pi_dict[pi_list[0]] = [float(pi_list[1]), float(pi_list[2]), float(pi_list[3])]
# the pI library is done.
if len(sys.argv) < 2:
file_in= 'test.txt'
# file_in = raw_input('Please enter the name of the file containing the CDR3s: ')
else:
file_in = sys.argv[1]
sample_name = file_in.split('.')[0][5:]
file_out_name = sample_name + '.pi'
f_in = open(file_in, 'rU')
f_out = open(file_out_name,'w')
cdr3_counter = 0
for line in f_in.readlines(): # read CDR3s line by line
cdr3_counter +=1
if cdr3_counter % 10000 == 0:
print 'So far %d CDR3s have been checked.' % cdr3_counter
line = line[:-1] # remove \n character from lines
line = line.split(',')
cdr3_seq = line[0] # The particular CDR3
cdr3_count = line[1] # The count of the particular CDR3
nterm = cdr3_seq[0]
cterm = cdr3_seq[-1]
aa_count_dict = defaultdict(int) # this dictionary holds the number occurrences of each aa in the CDR3
for aa in cdr3_seq[1:-1]:
aa_count_dict[aa] += 1
# pI calculation begins here
pHmin = 0.0 # the lowest pH
pHmax = 14.0 # the highest pH
maxiteration = 2000 # max iteration value
epsi = 0.0001 # desired precision
i = 0 # the iteration counter
charge = 1
while (i < maxiteration and (pHmax - pHmin > epsi)):
pHmid = pHmin + (pHmax - pHmin) / float(2)
pHmid_exp = 10**(-pHmid)
cter = 10**(-pi_dict[cterm][0]) / (10**(-pi_dict[cterm][0]) + pHmid_exp)
nter = pHmid_exp / (10**(-pi_dict[nterm][1]) + pHmid_exp)
carg = chis = clys = casp = cglu = ccys = ctyr = 0
if aa_count_dict['R']>0:
carg = aa_count_dict['R'] * pHmid_exp / (10**(-pi_dict['R'][2]) + pHmid_exp)
if aa_count_dict['H']>0:
chis = aa_count_dict['H'] * pHmid_exp / (10**(-pi_dict['H'][2]) + pHmid_exp)
if aa_count_dict['K']>0:
clys = aa_count_dict['K'] * pHmid_exp / (10**(-pi_dict['K'][2]) + pHmid_exp)
if aa_count_dict['D']>0:
casp = aa_count_dict['D'] * 10**(-pi_dict['D'][2]) / (10**(-pi_dict['D'][2]) + pHmid_exp)
if aa_count_dict['E']>0:
cglu = aa_count_dict['E'] * 10**(-pi_dict['E'][2]) / (10**(-pi_dict['E'][2]) + pHmid_exp)
if aa_count_dict['C']>0:
ccys = aa_count_dict['C'] * 10**(-pi_dict['C'][2]) / (10**(-pi_dict['C'][2]) + pHmid_exp)
if aa_count_dict['Y']>0:
ctyr = aa_count_dict['Y'] * 10**(-pi_dict['Y'][2]) / (10**(-pi_dict['Y'][2]) + pHmid_exp)
charge = carg + clys + chis + nter - (casp + cglu + ctyr + ccys + cter) # charge at pHmid
if charge > 0:
pHmin = pHmid
else:
pHmax = pHmid
i += 1
f_out.write('%s, %s, %.3f\n' % (line[0], line[1], pHmid))
f_in.close()
f_out.close()
print 'The %s file has been created successfully.' % file_out_name
|
UTF-8
|
Python
| false | false | 2,014 |
3,470,333,606,360 |
565ad2ac8e48eb8c6bf756a33d0d504c15d03c43
|
85530dd16c72bef65115a5951053cf11a1b32add
|
/Rosalind/consensus.py
|
d996d218b455b4a40bd1fc3863de87268c8e48c2
|
[] |
no_license
|
Alexander-N/coding-challenges
|
https://github.com/Alexander-N/coding-challenges
|
a9cbe6cc7076d21d19460db053e4dbfe892208a5
|
1a87aaa075af67af9c6ac3f620e06c0e1807c59c
|
refs/heads/master
| 2016-09-08T15:21:50.013800 | 2014-12-15T18:43:18 | 2014-12-15T18:43:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import fileinput
import numpy as np
nukleotides = ['A','C','G','T']
def get_profile_matrix(dna_strings):
profile_matrix = []
for i in range(len(dna_strings[0])):
pos_string = ''
for j in range(len(dna_strings)):
pos_string += dna_strings[j][i]
for nukl in nukleotides:
profile_matrix.append(pos_string.count(nukl))
profile_matrix = np.reshape(profile_matrix, [4,-1], order='F')
return profile_matrix
def get_consensus(profile_matrix):
consensus_string = ''
for i in range(profile_matrix.shape[-1]):
consensus_string += nukleotides[np.argmax(profile_matrix[:,i])]
return consensus_string
def read_fasta(f):
ids = []
dna_strings = []
lines = [line.strip() for line in f]
i = -1
for line in lines:
if line[0] == '>':
ids.append(line[1:])
i += 1
dna_strings.append('')
else:
dna_strings[i] += line
f.close()
return ids, dna_strings
ids, dna_strings = read_fasta(fileinput.input())
profile_matrix = get_profile_matrix(dna_strings)
consensus_string = get_consensus(profile_matrix)
print(consensus_string)
for i, nukl in enumerate(nukleotides):
print(nukl+':'),
for count in profile_matrix[i]:
print(str(count)),
print('')
|
UTF-8
|
Python
| false | false | 2,014 |
6,640,019,488,944 |
47f5682723ea6a8f32f5f3bfa0a5f6ba6baa9964
|
367fb7a7b36db3b8cb5c05e02fdd80adc831fa66
|
/OpenKVK/examples/baseclient.py
|
2ceb412259b250af4a437e0b251a8c866dfe2c43
|
[
"MIT"
] |
permissive
|
Amsterdam/OpenKVK
|
https://github.com/Amsterdam/OpenKVK
|
6bef53e79b1e14cd0f075867a8bc5bf5ba05978a
|
210f18dfa7bf5a940065f368021c830bc2b38ae0
|
refs/heads/master
| 2021-03-30T21:07:48.219412 | 2014-09-08T08:27:40 | 2014-09-08T08:27:40 | 124,552,260 | 0 | 0 | null | true | 2018-03-09T14:40:17 | 2018-03-09T14:40:17 | 2015-04-07T07:49:30 | 2014-09-08T08:27:40 | 324 | 0 | 0 | 0 | null | false | null |
from __future__ import print_function
from OpenKVK import BaseClient
client = BaseClient()
client.setResponseFormat('py')
print(client.query("SELECT * FROM kvk WHERE kvks = 27312152;"))
|
UTF-8
|
Python
| false | false | 2,014 |
11,536,282,203,515 |
8fae0f14cef6b78190fa0fed5aae007dcc845d02
|
82b931c103a6b403c4ddbf1e1fd5d93a990ae241
|
/acrylamid/filters/relative.py
|
7e9c6834f7b51dc19e5f263ef109e359105f6bd3
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
greatghoul/acrylamid
|
https://github.com/greatghoul/acrylamid
|
fda235cd1263eefd88ded91d9fe675e32f12050e
|
21e0fd8690d5cfee8b8d92d39283b08ab7267b85
|
refs/heads/master
| 2021-01-18T02:04:31.638517 | 2014-11-05T13:25:25 | 2014-11-05T13:25:25 | 26,484,943 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- encoding: utf-8 -*-
#
# Copyright 2012 Martin Zimmermann <info@posativ.org>. All rights reserved.
# License: BSD Style, 2 clauses -- see LICENSE.
from acrylamid import log
from acrylamid.filters import Filter
from acrylamid.helpers import joinurl
from acrylamid.lib.html import HTMLParser, HTMLParseError
class Href(HTMLParser):
def __init__(self, html, func=lambda part: part):
self.func = func
super(Href, self).__init__(html)
def apply(self, attrs):
for i, (key, value) in enumerate(attrs):
if key in ('href', 'src'):
attrs[i] = (key, self.func(value))
return attrs
def handle_starttag(self, tag, attrs):
if tag == 'a':
attrs = self.apply(attrs)
super(Href, self).handle_starttag(tag, attrs)
def handle_startendtag(self, tag, attrs):
if tag == 'img':
attrs = self.apply(attrs)
super(Href, self).handle_startendtag(tag, attrs)
class Relative(Filter):
match = ['relative']
version = 1
priority = 15.0
def transform(self, text, entry, *args):
def relatively(part):
if part.startswith('/') or part.find('://') == part.find('/') - 1:
return part
return joinurl(entry.permalink, part)
try:
return ''.join(Href(text, relatively).result)
except HTMLParseError as e:
log.warn('%s: %s in %s' % (e.__class__.__name__, e.msg, entry.filename))
return text
class Absolute(Filter):
match = ['absolute']
version = 2
priority = 15.0
@property
def uses(self):
return self.conf.www_root
def transform(self, text, entry, *args):
def absolutify(part):
if part.startswith('/'):
return self.conf.www_root + part
if part.find('://') == part.find('/') - 1:
return part
return self.conf.www_root + joinurl(entry.permalink, part)
try:
return ''.join(Href(text, absolutify).result)
except HTMLParseError as e:
log.warn('%s: %s in %s' % (e.__class__.__name__, e.msg, entry.filename))
return text
|
UTF-8
|
Python
| false | false | 2,014 |
4,389,456,597,421 |
50950d4b7ee17c3893416f1649cc09c1212cde30
|
42a63b49d66c89098574b216d4bafb592db70486
|
/astra/simulation.py
|
91fb2242f78615bedb50fdc6948a2d048f80383c
|
[
"GPL-3.0-only",
"GPL-1.0-or-later"
] |
non_permissive
|
remidomingues/ASTra
|
https://github.com/remidomingues/ASTra
|
e1aa102f7eeb9e061f16cefa2d428b3492a0ccfd
|
bd7a6b0b3af9df411ec8ae32bb4708844d09a329
|
refs/heads/master
| 2020-05-19T09:53:33.104945 | 2014-02-04T12:08:29 | 2014-02-04T12:08:29 | 12,138,810 | 9 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
"""
@file Simulation.py
@author Remi Domingues
@date 07/06/2013
Script algorithm:
While 1:
Running a SUMO simulation step of X seconds
Sending a vehicles position(1) message to the remote client by an output socket
Sending the vehicles ID of each arrived vehicle (2) by an output socket
Changing the traffic lights phases if required for cleaning the road for priority vehicles
Sleeping Y seconds
The regular messages below are sent on the port 18009 and can be disabled.
(1) Vehicles position message: COO vehicleId1 lon1 lat1 vehicleId2 lon2 lat2 ... vehicleIdN lonN latN
(2) Vehicles deletion message: DEL vehicleId1 vehicleId2 ... vehicleIdN
"""
import sys
import time
import constants
import traci
from trafficLights import updateTllForPriorityVehicles
from trafficLights import getTrafficLightsDictionary
from vehicle import sendArrivedVehicles
from vehicle import sendVehiclesCoordinates
from vehicle import getRegularVehicles
from logger import Logger
def runSimulationStep(mtraci):
"""
Runs one SUMO simulation step
"""
mtraci.acquire()
traci.simulationStep()
mtraci.release()
def removeArrivedVehicles(arrivedVehicles, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles):
"""
Removes every arrived vehicles from the priority vehicles shared list
"""
for vehicleId in arrivedVehicles:
if not constants.IGNORED_VEHICLES_REGEXP.match(vehicleId):
vehicles.remove(vehicleId)
mPriorityVehicles.acquire()
if vehicleId in priorityVehicles:
priorityVehicles.remove(vehicleId)
mPriorityVehicles.release()
for key in managedTllDict.keys():
if managedTllDict[key][0] == vehicleId:
del managedTllDict[key]
def notifyAndUpdateArrivedVehicles(mtraci, outputSocket, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles):
"""
Sends an arrived vehicles message (2) to the remote client and Remove every arrived vehicles from the priority vehicles shared list
"""
mtraci.acquire()
arrivedVehicles = traci.simulation.getArrivedIDList()
mtraci.release()
arrivedVehicles = getRegularVehicles(arrivedVehicles)
if constants.SEND_ARRIVED_VEHICLES and (constants.SEND_MSG_EVEN_IF_EMPTY or (not constants.SEND_MSG_EVEN_IF_EMPTY and arrivedVehicles)):
sendArrivedVehicles(arrivedVehicles, mtraci, outputSocket)
removeArrivedVehicles(arrivedVehicles, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles)
def run(mtraci, outputSocket, mRelaunch, eShutdown, eSimulationReady, priorityVehicles, mPriorityVehicles, eManagerReady, vehicles, mVehicles):
"""
See file description
"""
yellowTllDict = dict()
managedTllDict = dict()
tllDict = getTrafficLightsDictionary(mtraci)
mRelaunch.acquire()
eSimulationReady.set()
while not eManagerReady.is_set():
time.sleep(constants.SLEEP_SYNCHRONISATION)
while not eShutdown.is_set():
startTime = time.clock()
try:
mVehicles.acquire()
runSimulationStep(mtraci)
notifyAndUpdateArrivedVehicles(mtraci, outputSocket, priorityVehicles, mPriorityVehicles, managedTllDict, vehicles)
mVehicles.release()
if constants.SEND_VEHICLES_COORDS and (constants.SEND_MSG_EVEN_IF_EMPTY or (not constants.SEND_MSG_EVEN_IF_EMPTY and vehicles)):
sendVehiclesCoordinates(vehicles, mtraci, outputSocket, mVehicles)
updateTllForPriorityVehicles(mtraci, priorityVehicles, mPriorityVehicles, tllDict, yellowTllDict, managedTllDict)
except Exception as e:
if e.__class__.__name__ == constants.TRACI_EXCEPTION or e.__class__.__name__ == constants.CLOSED_SOCKET_EXCEPTION:
Logger.exception(e)
mRelaunch.release()
Logger.info("{}Shutting down current thread".format(constants.PRINT_PREFIX_SIMULATOR))
sys.exit()
else:
Logger.error("{}A {} exception occurred:".format(constants.PRINT_PREFIX_SIMULATOR, e.__class__.__name__))
Logger.exception(e)
endTime = time.clock()
duration = endTime - startTime
sleepTime = constants.SIMULATOR_SLEEP - duration
# Logger.info("{}Sleep time: {}".format(constants.PRINT_PREFIX_SIMULATOR, sleepTime))
if sleepTime > 0:
time.sleep(sleepTime)
|
UTF-8
|
Python
| false | false | 2,014 |
14,748,917,715,700 |
f385aeed5c07316600c3700061a76f8fde7c70d6
|
85dacb6b7d3c13fe3d8c84cbdf983faa0113b9a8
|
/metrics/workers/logger.py
|
cec338564297f614c539037ee1156d9d35bc5a34
|
[] |
no_license
|
jjcorrea/kanban-metrics
|
https://github.com/jjcorrea/kanban-metrics
|
b6a95b2e21e71bdd4b9b60d75bdfbaef7adf4d09
|
1f3de7ce947522f2681f2166bbfb0da605a69531
|
refs/heads/master
| 2020-06-06T10:28:16.216758 | 2014-01-17T19:57:16 | 2014-01-17T19:57:16 | 10,921,918 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
'''
A duummy Snapshot worker (for now)
'''
from time import mktime
from datetime import datetime
import time
import config
import re
import sys
from logging import *
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#The background is set with 40 plus the number of the color, and the foreground with 30
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
def formatter_message(message, use_color = True):
if use_color:
message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
else:
message = message.replace("$RESET", "").replace("$BOLD", "")
return message
COLORS = {
'WARNING': YELLOW,
'INFO': WHITE,
'DEBUG': BLUE,
'CRITICAL': YELLOW,
'ERROR': RED
}
class Logger(object):
def __enter__(self):
basicConfig(level=INFO)
self.logger = getLogger(__name__)
return self.logger
def __exit__(self, type, value, traceback):
''' '''
|
UTF-8
|
Python
| false | false | 2,014 |
7,292,854,470,997 |
efcc773acea18db8b6a7782393c28d7614fda8bd
|
11f4f7d789cf1bb45a02c6f6174b382abae2db85
|
/Mouth.py
|
5c185bbdcae13a95294b2f4c5b98c389a8fb45ce
|
[] |
no_license
|
rEtSaMfF/zenshiro
|
https://github.com/rEtSaMfF/zenshiro
|
855c48eea42372132f67e91d1c7d95f9b8e7c02a
|
fb03157919ad135559809f266456ec57e993d736
|
refs/heads/master
| 2021-01-01T06:26:30.158622 | 2013-04-22T21:35:58 | 2013-04-22T21:35:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import pygame
import random
import math
from EnemyBullet import *
from PlayerBullet import *
from PlayerSword import *
class Mouth(pygame.sprite.Sprite):
def __init__(self,x,y,bosss,creator):
pygame.sprite.Sprite.__init__(self)
self.game=creator
self.boss=bosss
self.rect=pygame.Rect(x,y,64,64)
self.hspd=0
self.vspd=1
self.emergetime=164
self.hpmax=400
self.hp=self.hpmax
self.bulletspeed=8
self.shootalarm=30
self.shootalarmmax=30
self.fireballalarm=30
self.fireballalarmmax=30
self.volleytimer=0
self.aimdir=0
self.currentweakspot=-1
self.eyesdead=0
self.imageind=0.0
def update(self):
if self.eyesdead>=2:
self.goBerserk()
#moving
new_rect=self.rect.move(self.hspd,self.vspd)
self.emergetime-=1
if self.emergetime<=0:
self.vspd=0
self.rect.move_ip(self.hspd,self.vspd)
if self.hp<=0:
self.game.removeBoss(self)
#self.game.resumeScrolling()
self.game.player.kills+=1
self.game.player.score+=self.hpmax*10
self.game.explode.play(loops=0, maxtime=0)
self.game.addExplosion(self.rect.left,self.rect.top)
if self.currentweakspot>=0:
#shooting
if self.currentweakspot==0:
self.shootalarm-=2
elif self.currentweakspot!=0:
self.shootalarm-=1
if self.shootalarm<=0:
shottype=random.randint(0,3)
self.shootalarm=self.shootalarmmax
self.shoot(shottype)
#fireballs
self.fireballalarm-=1
if self.fireballalarm<=0:
self.fireballalarm=self.fireballalarmmax
self.fire()
addind=0.0
addind+=1
addind+=abs(self.hspd/4)
self.imageind+=(addind/10)
def draw(self,screen):
drect=pygame.Rect((math.floor(self.imageind)%2)*64,0,64,64)
screen.blit(self.game.spr_BossMouth,self.rect,drect)
def collision(self,other):
if self.currentweakspot>=0:
if isinstance(other,PlayerBullet):
self.hp-=other.damage
self.boss.reduceHealth(other.damage)
self.game.removePlayerBullet(other)
if isinstance(other,PlayerSword):
self.hp-=other.damage
self.boss.reduceHealth(other.damage)
if other.player.shoottimer>8:
other.player.shoottimer=8
if isinstance(other,PlayerBomb):
self.hp-=other.damage
self.boss.reduceHealth(other.damage)
def shoot(self,type):
if type==0:
self.game.addEnemyBullet(self.rect.centerx,self.rect.bottom,0,8)
self.game.addEnemyBullet(self.rect.centerx-10,self.rect.bottom,-1,8)
self.game.addEnemyBullet(self.rect.centerx+10,self.rect.bottom,1,8)
elif type==1:
self.game.addEnemyBullet(self.rect.centerx, self.rect.bottom, 0, 4)
self.game.addEnemyBullet(self.rect.centerx-10,self.rect.bottom,-1,4)
self.game.addEnemyBullet(self.rect.centerx+10,self.rect.bottom,1,4)
elif type==2:
tox=self.game.player.rect.centerx
toy=self.game.player.rect.centery
self.aim(tox,toy)
thspd=math.cos(self.aimdir)*self.bulletspeed
tvspd=math.sin(self.aimdir)*self.bulletspeed
self.game.addEnemyBullet(self.rect.centerx,self.rect.centery,tvspd,thspd)
self.game.addEnemyBullet(self.rect.centerx-10,self.rect.centery-10,tvspd,thspd)
self.game.addEnemyBullet(self.rect.centerx+10,self.rect.centery-10,tvspd,thspd)
elif type==3:
self.game.addHomingMissile(self.rect.centerx,self.rect.centery,0,8)
self.game.addHomingMissile(self.rect.centerx-30,self.rect.centery-30,0,8)
self.game.addHomingMissile(self.rect.centerx+30, self.rect.centery-30,0,8)
def fire(self):
if self.volleytimer!=3:
self.game.addFireball(self.rect.centerx, self.rect.bottom,0,8)
self.volleytimer+=1
elif self.volleytimer==3:
self.game.addFireball(self.rect.centerx-10, self.rect.bottom,-2,8)
self.game.addFireball(self.rect.centerx-20, self.rect.bottom,-4,8)
self.game.addFireball(self.rect.centerx+10, self.rect.bottom,2,8)
self.game.addFireball(self.rect.centerx+20, self.rect.bottom,4,8)
self.game.addFireball(self.rect.centerx, self.rect.bottom,0,8)
self.volleytimer+=1
if self.volleytimer==5:
self.game.addFireball(self.rect.centerx,self.rect.bottom,0,8)
self.game.addFireball(self.rect.centerx-12,self.rect.bottom,0,8)
self.game.addFireball(self.rect.centerx-12,self.rect.bottom-24,0,8)
self.game.addFireball(self.rect.centerx+12,self.rect.bottom,0,8)
self.game.addFireball(self.rect.centerx+12,self.rect.bottom-24,0,8)
self.game.addFireball(self.rect.centerx-12,self.rect.bottom-12,0,8)
self.game.addFireball(self.rect.centerx-24,self.rect.bottom-12,0,8)
self.game.addFireball(self.rect.centerx+12,self.rect.bottom-12,0,8)
self.game.addFireball(self.rect.centerx+24,self.rect.bottom-12,0,8)
self.game.addFireball(self.rect.centerx,self.rect.bottom-12,0,8)
self.game.addFireball(self.rect.centerx,self.rect.bottom-24,0,8)
self.game.addFireball(self.rect.centerx,self.rect.bottom-36,0,8)
self.game.addFireball(self.rect.centerx,self.rect.bottom+12,0,8)
self.volleytimer=0
def aim(self,x,y):
self.aimdir=math.atan2(self.rect.centerx-x,self.rect.centery-y)+math.pi
def changeVuln(self):
self.currentweakspot=-self.currentweakspot
def goBerserk(self):
self.currentweakspot=0
def eyeDeath(self):
self.eyesdead+=1
|
UTF-8
|
Python
| false | false | 2,013 |
19,370,302,521,330 |
40e22b0b642b8ef17d902aeca0222c7cedd360ff
|
d3c5fc2a0464f8280862366334efa327305786c3
|
/mac/fanctl.py
|
a879400dec1c925a7bfeddeea61cfdb552098866
|
[] |
no_license
|
pgonee/setting_files
|
https://github.com/pgonee/setting_files
|
13ae7b27d234e0e32e88e36704c87f701693c4f7
|
37f1741b3d0de55aad4fb977ded4c4d721109974
|
refs/heads/master
| 2016-09-10T19:08:55.774562 | 2013-11-23T03:33:58 | 2013-11-23T03:33:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import commands
def get_temp():
rst = commands.getoutput('cat /sys/devices/platform/coretemp.0/temp1_input')
return int(rst)
def get_max_rpm():
rst = commands.getoutput('cat /sys/devices/platform/applesmc.768/fan1_max')
return int(rst)
def get_rpm():
a, b = commands.getstatusoutput('cat /sys/devices/platform/applesmc.768/fan1_min')
return int(b)
def set_rpm(rpm_speed):
a, b = commands.getstatusoutput('echo %d > /sys/devices/platform/applesmc.768/fan1_min' % (rpm_speed))
def main():
min_temp = 30
max_temp = 80
min_rpm = 1500
max_rpm = get_max_rpm() - 201
current_temp = get_temp() / 1000
#print "current : %d" % (current_temp)
if get_rpm() > max_rpm:
return
if current_temp <= min_temp:
set_rpm(min_rpm)
# print "min!"
elif current_temp >= max_temp:
set_rpm(max_rpm)
# print "max!"
else:
index = (max_rpm - min_rpm) / (max_temp - min_temp)
rpm = 1500 + (current_temp - min_temp) * index
set_rpm(rpm)
# print "hah : %d" % (rpm)
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,013 |
7,799,660,647,021 |
1e9e89c27eda975898d7d43f39393865d6544ad2
|
a475692e93d85aece84da0158d9317d2be1e8fbe
|
/jds_image_proc/mlabraw_image_processing.py
|
9fbfb7c7c8ece16f21e4bcdf9a5fa676406f945d
|
[] |
no_license
|
warriorarmentaix/lfd
|
https://github.com/warriorarmentaix/lfd
|
f83e20cd9b91a0ac719645669a1eb98f19fa9007
|
ff07d53d8c7ed5a092ec05a03f57620d15bb98a0
|
refs/heads/master
| 2016-09-06T05:31:24.262555 | 2013-06-03T07:13:45 | 2013-06-03T07:13:45 | 10,400,184 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import mlabraw
MATLAB = None
def initialize():
global MATLAB
if MATLAB is None:
print "starting matlab..."
MATLAB = mlabraw.open("matlab -nodisplay -nosplash -nojvm -nodesktop")
print "done"
def put(name,array):
mlabraw.put(MATLAB, name, array)
def get(name):
return mlabraw.get(MATLAB, name)
def evaluate(string):
mlabraw.eval(MATLAB, string)
def remove_holes(labels,min_size):
initialize()
mlabraw.put(MATLAB, "L",labels)
mlabraw.put(MATLAB, "min_size",min_size)
mlabraw.eval(MATLAB, """
max_label = max(L(:));
good_pix = L==0;
for label = 1:max_label
good_pix = good_pix | bwareaopen(L==label,min_size,4);
end
bad_pix = ~logical(good_pix);
[~,I] = bwdist(good_pix,'Chessboard');
NewL = L;
NewL(bad_pix) = L(I(bad_pix));
NewL_d = double(NewL);
""")
NewL_d = mlabraw.get(MATLAB, "NewL_d")
return NewL_d.astype('uint8')
def branch_points(bw):
initialize()
mlabraw.put(MATLAB, "bw",bw)
mlabraw.eval(MATLAB, """
bp = bwmorph(bw,'branchpoints')
bp_d = double(bp);
""")
bp_d = mlabraw.get(MATLAB, "bp_d")
bp = bp_d.astype('uint8')
return bp
def remove_branch_points(bw):
return bw - branch_points(bw)
def skeletonize(bw):
initialize()
put("bw",bw.astype('uint8'))
evaluate("""
bw_thin = bwmorph(bw,'thin',Inf);
bw_thin_d = double(bw_thin);
""")
bw_thin_d = get('bw_thin_d')
return bw_thin_d.astype('uint8')
|
UTF-8
|
Python
| false | false | 2,013 |
2,748,779,103,222 |
ea16d3705951498517f7013a10c4a698af5a5ea2
|
ffb3c84cb06ef9646d2d16995737293e027a8245
|
/modules/help.py
|
193fdd9b913af937135b6ed2804fca121a428b4a
|
[] |
no_license
|
radioanonymous/Talho
|
https://github.com/radioanonymous/Talho
|
737ceed350987287ab6ceadf5778809e3ad97734
|
26d4b50f656ce08d14a4a951cba1f27b64aa9edd
|
refs/heads/master
| 2021-01-16T21:28:10.514767 | 2013-05-08T15:32:34 | 2013-05-08T15:32:50 | 3,165,311 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def main(bot, args):
'''help\nHelp.'''
if not args:
return 'Type %lsmod to show available modules.\nSources: https://github.com/eurekafag/Talho'
def info(bot):
return (("help",), 10, main)
|
UTF-8
|
Python
| false | false | 2,013 |
4,844,723,157,882 |
5f1b9dfabd86acb0b1054960213435d5229ec188
|
276b789971bc3e2a9dda69be75c87794faed9c98
|
/servidor/henry/wsgi.py
|
7032e715a751b6a86076abb61d6966e9a5ae87f9
|
[] |
no_license
|
qihqi/henryFACT
|
https://github.com/qihqi/henryFACT
|
fc0c62e4dbbfa886d68bbb0669decde6a9caa9a0
|
f1bb94a3c320319ec379bc583c2d89143074e0aa
|
refs/heads/master
| 2016-09-05T22:30:54.890928 | 2014-12-30T20:36:37 | 2014-12-30T20:36:37 | 4,302,067 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
sys.path.append('/var/servidor/henry')
import os
os.environ["HOME"] = "/home/servidor/"
# This application object is used by the development server
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
# as well as any WSGI server configured to use this file.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
UTF-8
|
Python
| false | false | 2,014 |
13,932,873,935,469 |
2cd605a5fca4b8bd73d312175b68866a8b33be69
|
7b5ad5733126b902b27472c7f25bd7f192513d34
|
/setup.py
|
b6719926d2e5eaa83a3238d7d0cbaf2a2f82b547
|
[] |
no_license
|
rodrigoaguilera/spotify-websocket-api
|
https://github.com/rodrigoaguilera/spotify-websocket-api
|
d0977eb2f66fac652ea9c720055a0b56681b959c
|
2cb4bc075d7e1e928b9a6d371912651d229e63c1
|
refs/heads/master
| 2021-01-16T23:00:39.382942 | 2013-01-16T21:30:04 | 2013-01-16T21:30:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
from distutils.core import setup
import os
setup(name = 'SpotifyWebsocketAPI',
version = '0.2',
author='Liam McLoughlin',
author_email='hexxeh@hexxeh.net',
packages=['spotify_web', 'spotify_web.proto'],
)
|
UTF-8
|
Python
| false | false | 2,013 |
8,778,913,180,163 |
65986e73be525f3e4370d9fb6ac5af99c7369a40
|
f26b4d6fc9bfeac52cdd4ac815394bf1dc8198e8
|
/py2exe_setup.py
|
645c2ed546ecb5e790de28dc0bd93a66a2f95ed3
|
[
"GPL-3.0-only"
] |
non_permissive
|
babus/asianet-auto-login-python
|
https://github.com/babus/asianet-auto-login-python
|
d580cf5788c240ec1373ebdb4aaad4aa2b132d7a
|
801a84bd648c758c5d195bc321b7c2bae4922d34
|
refs/heads/master
| 2021-01-10T21:06:58.453751 | 2013-07-02T08:16:26 | 2013-07-02T08:16:26 | 10,886,366 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from distutils.core import setup
import py2exe
import os
setup(console=[os.path.join('src', 'asianet_login.py')])
|
UTF-8
|
Python
| false | false | 2,013 |
17,583,596,121,803 |
050ea0b2413da5031476b90e3a74fd20b67283b5
|
7b05f4bbdd973852410350a9635790ac0f973cf1
|
/src/edwin/edwin/models/tests/test_trash.py
|
ffcdd5154808b26c7aaad949fd1ec2e17b08fbb0
|
[] |
no_license
|
chrisrossi/edwin
|
https://github.com/chrisrossi/edwin
|
172bf0c803b2bea23a1aeb22b7918cd391a619f0
|
a1869d7bfef4c968447a33565dc1ea2e5f06dc7a
|
refs/heads/master
| 2021-01-21T19:28:42.496005 | 2012-12-14T15:08:12 | 2012-12-14T15:08:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import unittest
class TestTrash(unittest.TestCase):
def setUp(self):
import os
import shutil
import sys
import tempfile
from edwin.models.album import Album
from edwin.models.photo import Photo
self.path = path = tempfile.mkdtemp('_test', 'edwin_')
here = os.path.dirname(sys.modules[__name__].__file__)
test_jpg = os.path.join(here, 'test.jpg')
dst = os.path.join(path, 'test.jpg')
os.symlink(test_jpg, dst)
photo = Photo(dst)
photo.title = 'Test Foo'
self.album = Album(path)
def tearDown(self):
import shutil
shutil.rmtree(self.path)
def _make_one(self):
from edwin.models.trash import Trash
trash = Trash()
trash.__parent__ = self.album
return trash
def test_trash_unknown_type(self):
trash = self._make_one()
self.assertRaises(ValueError, trash.trash, object())
def test_trash_photo(self):
self.failUnless('test.jpg' in self.album)
self.assertEqual(self.album['test.jpg'].title, 'Test Foo')
album = self.album
trash = self._make_one()
trash_id = trash.trash(album['test.jpg'])
self.failIf('test.jpg' in album)
self.assertEqual(trash.restore(trash_id).title, 'Test Foo')
self.failUnless('test.jpg' in album)
self.assertEqual(album['test.jpg'].title, 'Test Foo')
def test_trash_transformed_photo(self):
self.failUnless('test.jpg' in self.album)
self.assertEqual(self.album['test.jpg'].title, 'Test Foo')
self.album['test.jpg'].rotate(90)
self.assertEqual(self.album['test.jpg'].size, (2304, 3072))
album = self.album
trash = self._make_one()
trash_id = trash.trash(album['test.jpg'])
self.failIf('test.jpg' in album)
self.assertEqual(trash.restore(trash_id).title, 'Test Foo')
self.failUnless('test.jpg' in album)
self.assertEqual(album['test.jpg'].title, 'Test Foo')
self.assertEqual(self.album['test.jpg'].size, (2304, 3072))
|
UTF-8
|
Python
| false | false | 2,012 |
4,191,888,115,040 |
201bd9fb69f7728b1da429b46e5d2e90d8ffc8e6
|
76e463661aa190971a59105d5c91ae9c965cbac8
|
/tests/system/tools/findUnusedObjects.py
|
dfa8d283331834b4e8f7f5c7654a79e271244741
|
[
"LGPL-2.1-only",
"Qt-LGPL-exception-1.1",
"MIT",
"LicenseRef-scancode-mit-old-style",
"BSD-2-Clause",
"BSD-3-Clause"
] |
non_permissive
|
XMrBear/qtcreator
|
https://github.com/XMrBear/qtcreator
|
a1cf9aa1e5b5c4c7167e2a90273e03aa34342787
|
4537b8e5d6410f949a135a63e304870f2a66a93f
|
refs/heads/2.6
| 2021-01-17T20:24:20.809439 | 2013-01-31T09:00:47 | 2013-02-02T10:30:01 | 84,143,927 | 2 | 0 | null | true | 2017-03-07T02:17:45 | 2017-03-07T02:17:45 | 2017-03-07T02:17:43 | 2016-10-20T11:02:36 | 245,128 | 0 | 0 | 0 | null | null | null |
#!/usr/bin/env python
import os
import sys
import tokenize
from optparse import OptionParser
from toolfunctions import checkDirectory
from toolfunctions import getFileContent
objMap = None
def parseCommandLine():
global directory, onlyRemovable, fileType
scriptChoice = ('Python', 'JavaScript', 'Perl', 'Tcl', 'Ruby')
parser = OptionParser("\n%prog [OPTIONS] [DIRECTORY]")
parser.add_option("-o", "--only-removable", dest="onlyRemovable",
action="store_true", default=False,
help="list removable objects only")
parser.add_option("-t", "--type", dest='fileType', type="choice",
choices=scriptChoice,
default='Python', nargs=1, metavar='LANG',
help="script language of the Squish tests (" +
", ".join(scriptChoice) + "; default: %default)")
(options, args) = parser.parse_args()
if len(args) == 0:
directory = os.path.abspath(".")
elif len(args) == 1:
directory = os.path.abspath(args[0])
else:
print "\nERROR: Too many arguments\n"
parser.print_help()
sys.exit(1)
onlyRemovable = options.onlyRemovable
fileType = options.fileType
def collectObjects():
global objMap
data = getFileContent(objMap)
return map(lambda x: x.strip().split("\t", 1)[0], data.strip().splitlines())
def getFileSuffix():
global fileType
fileSuffixes = {'Python':'.py', 'JavaScript':'.js', 'Perl':'.pl',
'Tcl':'.tcl', 'Ruby':'.rb'}
return fileSuffixes.get(fileType, None)
def handle_token(tokenType, token, (startRow, startCol), (endRow, endCol), line):
global useCounts
if tokenize.tok_name[tokenType] == 'STRING':
for obj in useCounts:
useCounts[obj] += str(token).count("'%s'" % obj)
useCounts[obj] += str(token).count('"%s"' % obj)
def findUsages():
global directory, objMap
suffix = getFileSuffix()
for root, dirnames, filenames in os.walk(directory):
for filename in filter(lambda x: x.endswith(suffix), filenames):
currentFile = open(os.path.join(root, filename))
tokenize.tokenize(currentFile.readline, handle_token)
currentFile.close()
currentFile = open(objMap)
tokenize.tokenize(currentFile.readline, handle_token)
currentFile.close()
def printResult():
global useCounts, onlyRemovable
print
if onlyRemovable:
if min(useCounts.values()) > 0:
print "All objects are used once at least.\n"
return False
print "Unused objects:\n"
for obj in filter(lambda x: useCounts[x] == 0, useCounts):
print "%s" % obj
return True
else:
length = max(map(len, useCounts.keys()))
outFormat = "%%%ds %%3d" % length
for obj,useCount in useCounts.iteritems():
print outFormat % (obj, useCount)
print
return None
def main():
global useCounts, objMap
objMap = checkDirectory(directory)
useCounts = dict.fromkeys(collectObjects(), 0)
findUsages()
atLeastOneRemovable = printResult()
if atLeastOneRemovable:
print "\nAfter removing the listed objects you should re-run this tool"
print "to find objects that might have been used only by these objects.\n"
return 0
if __name__ == '__main__':
parseCommandLine()
sys.exit(main())
|
UTF-8
|
Python
| false | false | 2,013 |
4,733,053,977,507 |
3af9db443cb29fd5134d30f46bdc12611b455a89
|
5629b4722d9650e8ca01e2a401edb279ab8e69e9
|
/gusPyCode/!simpleScripts/interrogatePickles.py
|
f7c0538433795fb22ef59427c7927763cb67930b
|
[] |
no_license
|
xguse/gusPyProj
|
https://github.com/xguse/gusPyProj
|
193c5872cbe03550436668035c79c47f0ae4f312
|
e2d2119c208ad383c92708f4fad3142de95d224f
|
refs/heads/master
| 2021-01-19T14:29:42.053306 | 2011-07-23T15:50:23 | 2011-07-23T15:50:23 | 345,724 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import cPickle
pklPath = '/Users/biggus/Documents/James/Data/ReClustering/PrelimData_Grant_Feb09/Clus2_247genes.6-8mers.gGEMS.pkl'
pickle = cPickle.load(open(pklPath,'rU'))
None
|
UTF-8
|
Python
| false | false | 2,011 |
5,059,471,513,741 |
0e7287c7703e4308cf83395c2729e00a63e8c82a
|
a8b0266fabd86ff4c1bc86d99a7b91856634f0ba
|
/wallhackctl.py
|
c4fe17d4588597c934386700a7e2725b8ef0512c
|
[] |
no_license
|
c3pb/wallhackctl
|
https://github.com/c3pb/wallhackctl
|
5a704bc66a035898ed7d490ad6596257fffdc1e8
|
86e9ce09b32149566e50d7d1a880e6a7a86e4616
|
refs/heads/master
| 2016-09-06T14:57:31.967997 | 2011-02-16T18:54:36 | 2011-02-16T18:54:36 | 1,375,028 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------------
# "THE CLUB-MATE LICENSE" (Revision 23.5):
# Some guys from the c3pb.de wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If you meet one of us some day, and you think
# this stuff is worth it, you can buy them a club-mate in return.
# ----------------------------------------------------------------------------
#
import os
import cherrypy
import ConfigParser
import subprocess
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('wallhackctl', 'templates'))
links=[]
class Root(object):
@cherrypy.expose
def index(self, s=None):
if s:
try:
x = int(s)
if x in range (0,5):
print "show: %s" % (s)
showScreen (s)
except:
# 'source' does not represent an integer
print "incorrect value for s"
pass
template = env.get_template('index.html')
return template.render(title='CTL', links=links)
def showScreen(x):
screen = "XK_%s" % (x)
subprocess.check_call(["/home/chaos/wallhackctl/xfk", "+XK_Meta_L", screen, "-XK_Meta_L"])
def main():
# Some global configuration; note that this could be moved into a
# configuration file
cherrypy.config.update({
'server.socket_port' : 80,
'server.socket_host' : "0.0.0.0",
'tools.encode.on': True, 'tools.encode.encoding': 'utf-8',
'tools.decode.on': True,
'tools.trailing_slash.on': True,
'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)),
})
rootconf = {
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'static'
}
}
links.append('<a href="?s=1">Clock</a>')
links.append('<a href="?s=2">Slideshow</a>')
links.append('<a href="?s=3">3</a>')
cherrypy.tree.mount(Root(),"/",rootconf)
cherrypy.engine.start()
cherrypy.engine.block()
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,011 |
5,497,558,140,515 |
441e339db90d4d8141609a0ed4d926f6819212e9
|
673fb2ea6c020acf80419c32605316e02147680c
|
/QMcalculator.py
|
85b06d0628a8ae84a7f1b76218c30ef25ba70b88
|
[
"GPL-3.0-only",
"GPL-3.0-or-later",
"GPL-1.0-or-later"
] |
non_permissive
|
gacohoon/Quantum-Mechanics-Calculator
|
https://github.com/gacohoon/Quantum-Mechanics-Calculator
|
97f1878a9790856ddef0100aff501012ba47f681
|
c963e9ac9e2fa41484e782d1c3036ac76a78faf8
|
refs/heads/master
| 2016-09-08T00:35:33.397340 | 2010-11-20T20:56:36 | 2010-11-20T20:56:36 | 1,098,280 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""Quantum mechanics calculator
Run using:
python QMcalculator.py
"""
import QMTypes
import classify
import iostream
class CommandLinePrompt(object):
"""Current interface to the quantum mechanics calculator."""
def __init__(self, program):
self.history = []
self.main = program
def run(self):
"""Begin the command line program"""
print """
# Quantum Mechanics Calculator
#
# Copyright (C) 2010 Jeffrey M. Brown, Kyle T. Taylor
#
# Type 'exit' to quit.
"""
while 1:
line = raw_input('> ') # get a line from the prompt
self.history.append(line) # keep track of commands
if line == 'exit': break
try:
self.main(line)
except iostream.InputError, classify.ClassificationError:
print "Invalid input"
def main(line):
c = classify.Classifier(QMTypes.inputDict, QMTypes.outputDict)
inputTokenList = iostream.parse(line) # parse input
classList = []
for token in inputTokenList:
qmClass = c.toClass(token) # convert input into classes
classList.append(qmClass)
print classList # display all classes that were identified
outputTokenList = []
for qmClass in classList:
token = c.toToken(qmClass) # create token for each class
outputTokenList.append(token)
outputString = iostream.assemble(outputTokenList)
print outputString, '\n'
if __name__ == '__main__':
CLP = CommandLinePrompt(main)
CLP.run()
|
UTF-8
|
Python
| false | false | 2,010 |
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 |
8,804,682,980,275 |
ea4027fc433c5c45f49e5efa50d2c28bb56185a3
|
29e03d8816228d2d5259d2e01ed97661e253c0bb
|
/vagabond/memory.py
|
fdc79afc05f0a08a92b86c137c8d99333eef9807
|
[
"MIT"
] |
permissive
|
hiway/vagabond
|
https://github.com/hiway/vagabond
|
b8d9fcc885e2c6cf3206a3851160ffc11829432c
|
b61284f76393e0fa14375f14249178b8339bb95e
|
refs/heads/master
| 2016-05-24T02:17:00.256278 | 2013-12-28T23:31:30 | 2013-12-28T23:31:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Memory(object):
cells = {}
def _location_check(self, location):
location = int(location)
if not 0 < location < 100:
raise NameError("Unable to access location {location}".format(location=location))
return location
def store(self, location, value):
location = self._location_check(location)
if not -10000 < value < 10000:
raise ValueError("Value {value} is too large. (Limit: -10k to 10k)".format(value=value))
self.cells[location] = value
def read(self, location):
location = self._location_check(location)
return self.cells.get(location)
def reset(self):
self.cells = {}
|
UTF-8
|
Python
| false | false | 2,013 |
1,786,706,441,793 |
7afc05e0fe1008e08d79fcbedf2aac86eb2813c8
|
55fed1d154a51d17fc763f7572bb86b6c93edf27
|
/generate_classes.py
|
530e9a0715db6f879e5d28b4b5be44b5cdecb1e2
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
non_permissive
|
msscully/BAW_Nipype
|
https://github.com/msscully/BAW_Nipype
|
10b36aaee66b9a7e0a59523f9b43e94d4e699dc8
|
195922decb6b09d2b7fde0f75c15a634271334bc
|
refs/heads/master
| 2016-09-06T15:13:22.830755 | 2011-12-30T22:17:58 | 2011-12-30T22:17:58 | 2,667,750 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import xml.dom.minidom
import subprocess
import os
import warnings
from nipype.interfaces.base import (CommandLineInputSpec, CommandLine, traits,
TraitedSpec, File, StdOutCommandLine,
StdOutCommandLineInputSpec, isdefined)
def generate_all_classes(modules_list = [], launcher=[]):
""" modules_list contains all the SEM compliant tools that should have wrappers created for them.
launcher containtains the command line prefix wrapper arugments needed to prepare
a proper environment for each of the modules.
"""
init_imports = ""
for module in modules_list:
module_python_filename="%s.py"%module
print("="*80)
print("Generating Definition for module {0} in {1}".format(module,module_python_filename))
print("^"*80)
code = generate_class(module,launcher)
f = open(module_python_filename, "w")
f.write(code)
f.close()
init_imports += "from %s import %s\n"%(module,module)
f = open("__init__.py", "w")
f.write(init_imports)
f.close()
def generate_class(module,launcher):
dom = _grab_xml(module,launcher)
inputTraits = []
outputTraits = []
outputs_filenames = {}
#self._outputs_nodes = []
for paramGroup in dom.getElementsByTagName("parameters"):
for param in paramGroup.childNodes:
if param.nodeName in ['label', 'description', '#text', '#comment']:
continue
traitsParams = {}
name = param.getElementsByTagName('name')[0].firstChild.nodeValue
name = name.lstrip().rstrip()
longFlagNode = param.getElementsByTagName('longflag')
if longFlagNode:
## Prefer to use longFlag as name if it is given, rather than the parameter name
longFlagName = longFlagNode[0].firstChild.nodeValue
## SEM automatically strips prefixed "--" or "-" from from xml before processing
## we need to replicate that behavior here The following
## two nodes in xml have the same behavior in the program
## <longflag>--test</longflag>
## <longflag>test</longflag>
longFlagName = longFlagName.lstrip(" -").rstrip(" ")
traitsParams["argstr"] = "--" + longFlagName + " "
else:
traitsParams["argstr"] = "--" + name + " "
argsDict = {'directory': '%s', 'file': '%s', 'integer': "%d", 'double': "%f", 'float': "%f", 'image': "%s", 'transform': "%s", 'boolean': '', 'string-enumeration': '%s', 'string': "%s", 'integer-enumeration' : '%s'}
if param.nodeName.endswith('-vector'):
traitsParams["argstr"] += "%s"
else:
traitsParams["argstr"] += argsDict[param.nodeName]
index = param.getElementsByTagName('index')
if index:
traitsParams["position"] = index[0].firstChild.nodeValue
desc = param.getElementsByTagName('description')
if index:
traitsParams["desc"] = desc[0].firstChild.nodeValue
name = param.getElementsByTagName('name')[0].firstChild.nodeValue
typesDict = {'integer': "traits.Int", 'double': "traits.Float",
'float': "traits.Float", 'image': "File",
'transform': "File", 'boolean': "traits.Bool",
'string': "traits.Str", 'file':"File",
'directory': "Directory"}
if param.nodeName.endswith('-enumeration'):
type = "traits.Enum"
values = ['"%s"'%el.firstChild.nodeValue for el in param.getElementsByTagName('element')]
elif param.nodeName.endswith('-vector'):
type = "InputMultiPath"
if param.nodeName in ['file', 'directory', 'image', 'transform']:
values = ["%s(exists=True)"%typesDict[param.nodeName.replace('-vector','')]]
else:
values = [typesDict[param.nodeName.replace('-vector','')]]
traitsParams["sep"] = ','
elif param.getAttribute('multiple') == "true":
type = "InputMultiPath"
if param.nodeName in ['file', 'directory', 'image', 'transform']:
values = ["%s(exists=True)"%typesDict[param.nodeName]]
else:
values = [typesDict[param.nodeName]]
traitsParams["argstr"] += "..."
else:
values = []
type = typesDict[param.nodeName]
if param.nodeName in ['file', 'directory', 'image', 'transform'] and param.getElementsByTagName('channel')[0].firstChild.nodeValue == 'output':
traitsParams["hash_files"] = False
inputTraits.append("%s = traits.Either(traits.Bool, %s(%s), %s)"%(name,
type,
_parse_values(values).replace("exists=True",""),
_parse_params(traitsParams)))
traitsParams["exists"] = True
traitsParams.pop("argstr")
traitsParams.pop("hash_files")
outputTraits.append("%s = %s(%s %s)"%(name, type.replace("Input", "Output"), _parse_values(values), _parse_params(traitsParams)))
outputs_filenames[name] = gen_filename_from_param(param)
else:
if param.nodeName in ['file', 'directory', 'image', 'transform'] and type not in ["InputMultiPath", "traits.List"]:
traitsParams["exists"] = True
inputTraits.append("%s = %s(%s %s)"%(name, type, _parse_values(values), _parse_params(traitsParams)))
input_spec_code = "class " + module + "InputSpec(CommandLineInputSpec):\n"
for trait in inputTraits:
input_spec_code += " " + trait + "\n"
output_spec_code = "class " + module + "OutputSpec(TraitedSpec):\n"
if len(outputTraits) > 0:
for trait in outputTraits:
output_spec_code += " " + trait + "\n"
else:
output_spec_code += " pass\n"
output_filenames_code = "_outputs_filenames = {"
output_filenames_code += ",".join(["'%s':'%s'"%(key,value) for key,value in outputs_filenames.iteritems()])
output_filenames_code += "}"
input_spec_code += "\n\n"
output_spec_code += "\n\n"
imports = """from nipype.interfaces.base import CommandLine, CommandLineInputSpec, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath
import os\n\n"""
template = """class %name%(CommandLine):
input_spec = %name%InputSpec
output_spec = %name%OutputSpec
_cmd = "%launcher% %name% "
%output_filenames_code%
def _list_outputs(self):
outputs = self.output_spec().get()
for name in outputs.keys():
coresponding_input = getattr(self.inputs, name)
if isdefined(coresponding_input):
if isinstance(coresponding_input, bool) and coresponding_input == True:
outputs[name] = os.path.abspath(self._outputs_filenames[name])
else:
if isinstance(coresponding_input, list):
outputs[name] = [os.path.abspath(inp) for inp in coresponding_input]
else:
outputs[name] = os.path.abspath(coresponding_input)
return outputs
def _format_arg(self, name, spec, value):
if name in self._outputs_filenames.keys():
if isinstance(value, bool):
if value == True:
value = os.path.abspath(self._outputs_filenames[name])
else:
return ""
return super(%name%, self)._format_arg(name, spec, value)\n\n"""
main_class = template.replace("%name%", module).replace("%output_filenames_code%", output_filenames_code).replace("%launcher%"," ".join(launcher))
return imports + input_spec_code + output_spec_code + main_class
def _grab_xml(module,launcher):
# cmd = CommandLine(command = "Slicer3", args="--launch %s --xml"%module)
# ret = cmd.run()
command_list=launcher[:] ## force copy to preserve original
command_list.extend([module, "--xml"])
final_command=" ".join(command_list)
xmlReturnValue = subprocess.Popen(final_command, stdout=subprocess.PIPE, shell=True).communicate()[0]
return xml.dom.minidom.parseString(xmlReturnValue)
# if ret.runtime.returncode == 0:
# return xml.dom.minidom.parseString(ret.runtime.stdout)
# else:
# raise Exception(cmd.cmdline + " failed:\n%s"%ret.runtime.stderr)
def _parse_params(params):
list = []
for key, value in params.iteritems():
if isinstance(value, str) or isinstance(value, unicode):
list.append('%s = "%s"'%(key, value))
else:
list.append('%s = %s'%(key, value))
return ",".join(list)
def _parse_values(values):
values = ['%s'%value for value in values]
if len(values) > 0:
retstr = ",".join(values) + ","
else:
retstr = ""
return retstr
def gen_filename_from_param(param):
base = param.getElementsByTagName('name')[0].firstChild.nodeValue
fileExtensions = param.getAttribute("fileExtensions")
if fileExtensions:
## It is possible that multiple file extensions can be specified in a
## comma separated list, This will extract just the first extension
firstFileExtension=fileExtensions.split(',')[0]
ext = firstFileExtension
else:
ext = {'image': '.nii', 'transform': '.mat', 'file': '', 'directory': ''}[param.nodeName]
return base + ext
if __name__ == "__main__":
## NOTE: For now either the launcher needs to be found on the default path, or
## every tool in the modules list must be found on the default path
## AND calling the module with --xml must be supported and compliant.
modules_list = ['BRAINSFit', 'BRAINSResample', 'BRAINSDemonWarp', 'BRAINSROIAuto']
## SlicerExecutionModel compliant tools that are usually statically built, and don't need the Slicer3 --launcher
#generate_all_classes(modules_list=modules_list,launcher=[])
## Tools compliant with SlicerExecutionModel called from the Slicer environment (for shared lib compatibility)
launcher=['Slicer3','--launch']
generate_all_classes(modules_list=modules_list, launcher=launcher )
#generate_all_classes(modules_list=['BRAINSABC'], launcher=[] )
|
UTF-8
|
Python
| false | false | 2,011 |
9,655,086,529,317 |
6347135921cd1ca12ec0134fb635780ad20bad89
|
a848e685813f3a4c5ace142a33e8dda1d56b2dd1
|
/stunat/helpdesk/forms.py
|
8182c3d3ed7b50b11ef0de8aa1aef8b39f5cf5d0
|
[] |
no_license
|
f0l1v31r4/stunat
|
https://github.com/f0l1v31r4/stunat
|
1387f5b555bfd46126dc83f9a817bd2477329439
|
a05749cf1c93d42a88af49bb5de92d3c4965003f
|
refs/heads/master
| 2016-08-04T05:53:42.148462 | 2012-05-02T17:29:15 | 2012-05-02T17:29:15 | 33,569,559 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from django import forms
from django.forms.util import ErrorList
from helpdesk.models import Ocorrencia, Tecnico, Categoria, OcorrenciaStatus
from djtools.formfields import BrDataField
from djtools.formwidgets import BrDataWidget
from comum.models import Pessoa
from datetime import datetime
#from rh.models import Servidor
#from djtools.formwidgets import AutocompleteWidget
##############
# OCORRENCIA #
##############
from django.core.mail import EmailMessage
def enviar_email(instance, email):
assunto = u'[HelpDesk] Notificação de Atividade - %s' % instance.status
mensagem = u'[%s] Atividade de %s \n\n Setor: %s \n Problema: %s \n\nNão responda este e-mail' % (instance.status, instance.categoria, instance.setor.sigla, instance.problema)
sendemail = EmailMessage(assunto, mensagem, to=[email.decode()])
sendemail.send()
class OcorrenciaForm(forms.ModelForm):
class Meta:
model = Ocorrencia
def save(self, commit=True, force_insert=False, force_update=False):
if 'enviar' in self.data:
email = self.instance.tecnico.email
enviar_email(self.instance, email)
return super(OcorrenciaForm, self).save(commit)
usuario = forms.ModelChoiceField(label=u'Usuário', queryset=Pessoa.objects.all(), required=False)
tecnico = forms.ModelChoiceField(label=u'Atribuido a', queryset=Tecnico.objects.all())
categoria = forms.ModelChoiceField(label=u'Categoria', queryset=Categoria.objects.all())
ocorretor = forms.CharField(label=u'Realizado por', max_length=120, widget=forms.TextInput(attrs={'size':'70'}), required=False)
# prestador = forms.ModelChoiceField(queryset=Servidor.objects.all(), widget=AutocompleteWidget(extraParams={'force_generic_search': '1'}, minChars=5))
status = forms.ModelChoiceField(label=u'Status', queryset=OcorrenciaStatus.objects.all())
data_chegada = BrDataField(label=u'Data de Chegada', widget=BrDataWidget(), initial=datetime.now())
data_saida = BrDataField(label=u'Data de Saída', widget=BrDataWidget(), required=False)
numero_patrimonio = forms.IntegerField(label=u'Número do Patrimônio', widget=forms.TextInput(attrs={'size':'14'}), initial=1180, required=False)
problema = forms.CharField(label=u'Problema', widget=forms.Textarea(attrs={'cols':'80', 'rows':'10'}))
observacao = forms.CharField(label=u'Observação', widget=forms.Textarea(attrs={'cols':'80', 'rows':'10'}), required=False)
enviar = forms.BooleanField(label=u'Enviar Email', required=False)
def clean_data_saida(self):
if self.cleaned_data['status'] == u'Resolvido' or self.cleaned_data['status'] == u'Impedido':
if not self.cleaned_data['data_saida']:
self._errors['data_saida'] = ErrorList([u'Este campo é obrigatório.'])
return self.cleaned_data['data_saida']
def clean_tecnico(self):
if self.cleaned_data['status'] == u'Resolvido':
if not self.cleaned_data['tecnico']:
self._errors['tecnico'] = ErrorList([u'Este campo é obrigatório.'])
return self.cleaned_data['tecnico']
class HistoricoOcorrenciaForm(forms.Form):
numero_patrimonio = forms.CharField(label=u'Número do Patrimônio', required=False, widget=forms.TextInput(attrs={'size':'50'}))
METHOD = 'GET'
TITLE = 'Historico de Ocorrência'
|
UTF-8
|
Python
| false | false | 2,012 |
9,079,560,908,915 |
8b0b2255df280046907ab03dd8f0e3b5b101727e
|
6e3e0d6471f28ad50a867db321494dfa7578f5bc
|
/errors.py
|
4fe1cce1d17cbb5d0a253af2c510c9268dc2d9c7
|
[
"ISC"
] |
permissive
|
gvx/deja
|
https://github.com/gvx/deja
|
65ed662c4a1b029aadf8243084530455fb92c68a
|
0cbf11c9b4c70ffa6cd34a068287c25692bae7f9
|
refs/heads/master
| 2021-01-20T02:47:43.434680 | 2014-08-12T10:50:58 | 2014-08-12T10:50:58 | 1,447,877 | 16 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class DejaSyntaxError(Exception):
def __init__(self, error, context=None, index=None):
self.error = error
self.context = context
self.index = index
def __str__(self):
if self.context:
return "Syntax error:\n %s:%d: %s\n %s\n %s" % (self.context.filename, self.context.linenr, self.error, self.context.origtext, '\t' * self.context.indent + ' ' * self.index + '^')
else:
return "Syntax error:\n %s\n" % (self.error,)
|
UTF-8
|
Python
| false | false | 2,014 |
4,741,643,941,489 |
900ce5a0bcf40f5db49b1d2639558d2a0acbfc59
|
42b82c2015a85e9e4e80f40988d588cb7fdc3098
|
/addons/zondaggio/questionnaire.py
|
dced7b8c0cc346c1d1fbb6baff2bf6fb1a92c5bc
|
[] |
no_license
|
eric-lemesre/openerp-survey
|
https://github.com/eric-lemesre/openerp-survey
|
64fe9dc266f6d9216cec445c80826c97b8d9171c
|
c30668969fa883f290aa8daa88cacd8103f5ef60
|
refs/heads/master
| 2020-03-19T13:51:39.996523 | 2013-10-24T10:41:59 | 2013-10-24T10:41:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
##############################################################################
#
# Survey Methodology
# Copyright (C) 2013 Coop. Trab. Moldeo Interactive Ltda.
# No email
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import re
import netsvc
from osv import osv, fields
from lxml import etree
from openerp.tools import SKIPPED_ELEMENT_TYPES
from openerp.tools.translate import _
import tools
import time
from datetime import datetime
import logging
import os.path
from wizard.questionnaire_export import dump_inputs
from openerp.osv.orm import setup_modifiers
_logger = logging.getLogger(__name__)
# ---- Codigo de orm.py : AQUI EMPIEZA. Permite generar vista por herencia. ----
def encode(s):
if isinstance(s, unicode):
return s.encode('utf8')
return s
def raise_view_error(error_msg, child_view_id):
view, child_view = self.pool.get('ir.ui.view').browse(cr, uid, [view_id, child_view_id], context)
error_msg = error_msg % {'parent_xml_id': view.xml_id}
raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
% (child_view.xml_id, self._name, error_msg))
def locate(source, spec):
""" Locate a node in a source (parent) architecture.
Given a complete source (parent) architecture (i.e. the field
`arch` in a view), and a 'spec' node (a node in an inheriting
view that specifies the location in the source view of what
should be changed), return (if it exists) the node in the
source view matching the specification.
:param source: a parent architecture to modify
:param spec: a modifying node in an inheriting view
:return: a node in the source matching the spec
"""
if spec.tag == 'xpath':
nodes = source.xpath(spec.get('expr'))
return nodes[0] if nodes else None
elif spec.tag == 'field':
# Only compare the field name: a field can be only once in a given view
# at a given level (and for multilevel expressions, we should use xpath
# inheritance spec anyway).
for node in source.getiterator('field'):
if node.get('name') == spec.get('name'):
return node
return None
for node in source.getiterator(spec.tag):
if isinstance(node, SKIPPED_ELEMENT_TYPES):
continue
if all(node.get(attr) == spec.get(attr) \
for attr in spec.attrib
if attr not in ('position','version')):
# Version spec should match parent's root element's version
if spec.get('version') and spec.get('version') != source.get('version'):
return None
return node
return None
def intercalate(a, L):
"""
Intercalate a beetween elements of L
"""
if len(L)>0:
for j in L[:-1]:
yield j
yield a
yield L[-1]
def apply_inheritance_specs(source, specs_arch, inherit_id=None):
""" Apply an inheriting view.
Apply to a source architecture all the spec nodes (i.e. nodes
describing where and what changes to apply to some parent
architecture) given by an inheriting view.
:param source: a parent architecture to modify
:param specs_arch: a modifying architecture in an inheriting view
:param inherit_id: the database id of the inheriting view
:return: a modified source where the specs are applied
"""
specs_tree = etree.fromstring(encode(specs_arch))
# Queue of specification nodes (i.e. nodes describing where and
# changes to apply to some parent architecture).
specs = [specs_tree]
while len(specs):
spec = specs.pop(0)
if isinstance(spec, SKIPPED_ELEMENT_TYPES):
continue
if spec.tag == 'data':
specs += [ c for c in specs_tree ]
continue
node = locate(source, spec)
if node is not None:
pos = spec.get('position', 'inside')
if pos == 'replace':
if node.getparent() is None:
source = copy.deepcopy(spec[0])
else:
for child in spec:
node.addprevious(child)
node.getparent().remove(node)
elif pos == 'attributes':
for child in spec.getiterator('attribute'):
attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)
if attribute[1]:
node.set(attribute[0], attribute[1])
else:
del(node.attrib[attribute[0]])
else:
sib = node.getnext()
for child in spec:
if pos == 'inside':
node.append(child)
elif pos == 'after':
if sib is None:
node.addnext(child)
node = child
else:
sib.addprevious(child)
elif pos == 'before':
node.addprevious(child)
else:
raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
else:
attrs = ''.join([
' %s="%s"' % (attr, spec.get(attr))
for attr in spec.attrib
if attr != 'position'
])
tag = "<%s%s>" % (spec.tag, attrs)
if spec.get('version') and spec.get('version') != source.get('version'):
raise_view_error("Mismatching view API version for element '%s': %r vs %r in parent view '%%(parent_xml_id)s'" % \
(tag, spec.get('version'), source.get('version')), inherit_id)
raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
return source
# ---- Codigo de orm.py : AQUI TERMINA ----
class JavaScript:
def __init__(self, script):
self.script = script
def __repr__(self):
return self.script
# Codigo JavaScript que permite Cambiar de <input/> con la tecla Enter.
_enter_js = """
<html>
<script type="text/javascript">
function sleep(ms)
{
var dt = new Date();
dt.setTime(dt.getTime() + ms);
while (Math.max(new Date().getTime(), dt.getTime()) == dt.getTime());
};
$(document).ready(function(){
(function(){
var char_keyup_orig = openerp.instances.instance0.web.form.FieldChar.prototype.events.keyup;
openerp.instances.instance0.web.form.FieldChar.prototype.events.keyup = function(e) {
if (e.which === $.ui.keyCode.ENTER) {
setTimeout(function() {
textboxes = $("input:visible:enabled");
currentBoxNumber = textboxes.index(e.target);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1];
nextBox.focus();
nextBox.select();
e.preventDefault();
return false;
}
}, 500);
}
}
})();
});
</script>
</html>
"""
_enter_js = """
<html>
<script type="text/javascript">
$(document).ready(function(){
debugger;
sheets = $('.oe_form_sheetbg');
main_sheet = sheets[sheets.length-1];
main_sheet.className = 'oe_form_sheetbg survey_full';
});
</script>
</html>"""
_enter_css_ = """
element.style {
display: block;
position: absolute;
width: 100%;
height: 100%;
background-color: white;
z-index: 10000;
left: 0px;
top: 0px;
}
"""
class questionnaire(osv.osv):
"""
Este objeto presenta las preguntas de un cuestionario para un encuestado.
"""
_name = 'sondaggio.questionnaire'
_inherit = [ _name ]
def get_parameters(self, cr, uid, ids, field_name, arg, context=None):
if field_name[:4] != 'par_':
return {}
param_obj = self.pool.get('sondaggio.parameters')
res = {}
for q in self.browse(cr, uid, ids, context=context):
p_l = [ par.value for par in q.parameter_ids if par.name == field_name[4:] ]
res[q.id] = p_l[0] if p_l else False
return res
def search_parameters(self, cr, uid, obj, name, args, context):
param_obj = self.pool.get('sondaggio.parameter')
args = [ item for sublist in [[('name','=',p[4:]), ('value', o, v)] for p,o,v in args ] for item in sublist ]
p_ids = param_obj.search(cr, uid, args, context=context)
p_reads = param_obj.read(cr, uid, p_ids, ['questionnaire_id'])
p_ids = [ p['questionnaire_id'][0] for p in p_reads ]
return [ ('id', 'in', p_ids) ]
def get_url(self, cr, uid, ids, field_name, arg, context=None):
user_obj = self.pool.get('res.users')
user_id = context.get('user_id', uid)
user = user_obj.browse(cr, uid, user_id, context=context)
login = user.login
password = user.password
r = {}
base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url', default='', context=context)
for questionnaire in self.browse(cr, uid, ids, context=context):
r[questionnaire.id] = '%s/login?db=%s&login=%s&key=%s#action=questionnaire.ui&active_id=%s&active_code=%s'%(base_url, cr.dbname,login,password,questionnaire.id,questionnaire.code)
return r
def get_communication_date(self, cr, uid, ids, field_name, arg, context=None):
r = {}
for questionnaire in self.browse(cr, uid, ids, context=context):
r[questionnaire.id] = max([ c.send_date for c in questionnaire.communication_batch_ids ]) if questionnaire.communication_batch_ids else False
return r
def get_num_communications(self, cr, uid, ids, field_name, arg, context=None):
r = {}
for questionnaire in self.browse(cr, uid, ids, context=context):
r[questionnaire.id] = len(questionnaire.communication_batch_ids) if questionnaire.communication_batch_ids else False
return r
def get_date(self, cr, uid, ids, field_name, arg, context=None):
if field_name[:5] != 'date_':
return {}
r = {}
for questionnaire in self.browse(cr, uid, ids, context=context):
messages = [ (m.date, m.body) for m in questionnaire.message_ids if field_name[5:] in m.body.lower() ]
r[questionnaire.id] = messages[0][0] if messages else False
return r
_columns = {
'actual_page': fields.integer('Actual Page', readonly=True),
'url': fields.function(get_url, method=True, string='URL', readonly=True, type='char'),
'fecha_ver': fields.char('Questionnaire group', size=16),
'par_razon_social': fields.function(get_parameters, method=True, string='Razón social',
readonly=True, type='text', fnct_search=search_parameters, store=True),
'par_razon_social_ver': fields.function(get_parameters, method=True, string='Razón social verificada',
readonly=True, type='text', fnct_search=search_parameters, store=True),
'par_estrato_f': fields.function(get_parameters, method=True, string='Estrato',
readonly=True, type='text', fnct_search=search_parameters, store=True),
'par_muesorig': fields.function(get_parameters, method=True, string='Muestra Orig',
readonly=True, type='text', fnct_search=search_parameters, store=True),
'par_fecha_ver': fields.function(get_parameters, method=True, string='Fecha verificación',
readonly=True, type='text', fnct_search=search_parameters, store=True),
'par_fecha_env': fields.function(get_parameters, method=True, string='Fecha envío',
readonly=True, type='text', fnct_search=search_parameters, store=True),
'par_encuestador': fields.function(get_parameters, method=True, string='Encuestador',
readonly=True, type='text', fnct_search=search_parameters, store=True),
'last_communication_date': fields.function(get_communication_date, method=True, string='Fecha de comunicación',
readonly=True, type='date', store=True),
'num_communications': fields.function(get_num_communications, method=True, string='Number of communications',
readonly=True, type='integer', store=False),
'date_draft': fields.function(get_date, method=True, string='Date in Draft',
readonly=True, type='datetime', store=False),
'date_in_process': fields.function(get_date, method=True, string='Date in Process',
readonly=True, type='datetime', store=False),
'date_waiting': fields.function(get_date, method=True, string='Date in Waiting',
readonly=True, type='datetime', store=False),
'date_rejected': fields.function(get_date, method=True, string='Date Rejected',
readonly=True, type='datetime', store=False),
'date_complete': fields.function(get_date, method=True, string='Date Complete',
readonly=True, type='datetime', store=False),
'date_validated': fields.function(get_date, method=True, string='Date Validated',
readonly=True, type='datetime', store=False),
'date_in_coding': fields.function(get_date, method=True, string='Date in Coding',
readonly=True, type='datetime', store=False),
'date_cancelled': fields.function(get_date, method=True, string='Date Cancelled',
readonly=True, type='datetime', store=False),
'mail_state': fields.related('sent_mail_id', 'state', type='selection',
string="Last mail state",
selection=[
('outgoing', 'Outgoing'),
('sent', 'Sent'),
('received', 'Received'),
('exception', 'Delivery Failed'),
('cancel', 'Cancelled'),
]),
}
_order = 'name asc, par_estrato_f asc'
_defaults = {
'actual_page': 1,
}
def onchange_input(self, cr, uid, ids, input_text, fields, context=None):
"""
Esta función toma el cambio que ocurre en una celda input y
actualiza el estado del próximo campo según lo que indique las
condiciones del "next_enable" o próximo campo a habilitar.
También verifica que mensaje tiene que enviarse al dataentry.
"""
context = context or None
value={}
complete_place = False
answer_obj = self.pool.get('sondaggio.answer')
question_obj = self.pool.get('sondaggio.node')
question_ids = question_obj.search(cr, uid, [('variable_name','=',fields)])
#answer_id = answer_obj.search(cr, uid, [('complete_place','=',fields),('questionnaire_id','=',ids)])
# Iterate over all hierarchical branch questions.
#child_ids = question_ids
#parent_ids = question_obj.search(cr, uid, [('child_ids', 'in', child_ids)])
#while len(parent_ids)>0:
# child_ids = child_ids + parent_ids
# parent_ids = question_obj.search(cr, uid, [('child_ids', 'in', parent_ids)])
#question_ids = child_ids
for question in question_obj.browse(cr, uid, question_ids):
# Habilitación o deshabilitación de preguntas.
if question.next_enable == False:
_logger.warning('Question %s no enable any other question' % question.complete_name)
else:
_logger.debug('Next enable: %s' % (question.next_enable))
for lines in question.next_enable.split('\n'):
if lines.strip():
parsed = re.search(r'(?P<condition>[^:]*):(?P<to_enable>[^:]*)(:(?P<to_disable>.*))?', lines).groupdict()
if parsed['condition'] and eval(parsed['condition'], tools.local_dict(input_text, question)):
to_enable = filter(lambda i: i!='', (parsed['to_enable'] or '').split(','))
to_disable = filter(lambda i: i!='', (parsed['to_disable'] or '').split(','))
to_enable = [ to if ' / ' in to else to.replace('_', ' / ') for to in to_enable ]
to_disable = [ to if ' / ' in to else to.replace('_', ' / ') for to in to_disable ]
_logger.debug('Searching to enable: %s' % (','.join(to_enable)))
_logger.debug('Searching to disable: %s' % (','.join(to_disable)))
next_dict = dict(
[ (qid, 'enabled') for qid in question_obj.search(cr, uid, [
('survey_id','=',question.survey_id.id),
('complete_name', 'in', to_enable)
]) ] +
[ (qid, 'disabled') for qid in question_obj.search(cr, uid, [
('survey_id','=',question.survey_id.id),
('complete_name', 'in', to_disable)
]) ])
_logger.debug('Found: %s' % (next_dict))
next_field_code = question_obj.read(cr, uid, next_dict.keys(), ['complete_place', 'complete_name'])
for item in next_field_code:
variable_name = item['variable_name']
value['sta_%s' % variable_name] = next_dict[item['id']]
it_ids = answer_obj.search(cr, uid, [('name','=',variable_name)])
if it_ids == []:
q_ids = question_obj.search(cr, uid, [('survey_id','=',question.survey_id.id),('variable_name','=',variable_name)])
for nq in question_obj.browse(cr, uid, q_ids):
v = {
'name': nq.variable_name,
'input': False,
'formated': False,
'message': False,
'valid': False,
'questionnaire_id': ids[0],
'question_id': nq.id,
}
it_ids.append(answer_obj.create(cr, uid, v))
if it_ids == []:
raise osv.except_osv("Inestable Questionary", "Not answer associated to the next field. Communicate with the administrator.")
answer_obj.write(cr, uid, it_ids, {'state': next_dict[item['id']]})
_logger.debug('Change %s(%s) to %s' % (variable_name, it_ids, next_dict[item['id']]))
# Evaluamos el formato
format_obj = question.format_id
format_res = format_obj.evaluate(input_text, question)[format_obj.id]
# Mensajes según pregunta.
value['msg_%s' % fields] = format_res['message']
value['vms_%s' % fields] = format_res['message']
value['for_%s' % fields] = format_res['formated']
value['vfo_%s' % fields] = format_res['formated']
value['val_%s' % fields] = format_res['is_valid']
r = { 'value': value }
if complete_place:
r.update(grab_focus='inp_%s' % complete_place)
return r
def fields_get(self, cr, uid, fields=None, context=None):
"""
Genera la lista de campos que se necesita para responder la encuesta.
"""
context = context or {}
questionnaire_id = context.get('questionnaire_id', context.get('actual_id', None))
actual_page = context.get('actual_page',1)
res = super(questionnaire, self).fields_get(cr, uid, fields, context)
if questionnaire_id is not None:
qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])
for qaire in self.browse(cr, uid, qaire_ids):
for question in qaire.survey_id.question_ids:
if question.page != actual_page:
continue
res["inp_%s" % question.complete_place] = {
'selectable': False,
'readonly': question.type != 'Variable',
'type': 'char',
'string': question.question,
}
res["msg_%s" % question.complete_place] = {
'selectable': False,
'readonly': False,
'type': 'char',
'string': 'Invisible Message',
}
res["vms_%s" % question.complete_place] = {
'selectable': False,
'readonly': False,
'type': 'char',
'string': 'Message',
}
res["sta_%s" % question.complete_place] = {
'selectable': False,
'readonly': False,
'type': 'char',
'string': 'Status',
}
res["for_%s" % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'char',
'string': 'Invisible Formated',
}
res["vfo_%s" % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'char',
'string': 'Formated',
}
res["val_%s" % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'boolean',
'string': 'Valid',
}
return res
def _get_tracked_fields(self, cr, uid, updated_fields, context=None):
r = super(questionnaire, self)._get_tracked_fields(cr, uid, updated_fields, context=context)
ks = [ k for k in r.keys() if k[3] != '_' ]
return dict( (k,v) for k,v in r.items() if k in ks )
def fields_view_get_dataentry(self, cr, uid, questionnaire_id, actual_page):
qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])[:1]
view_item = ['<group colspan="4" col="6">']
fields = {}
for qaire in self.browse(cr, uid, qaire_ids):
level = 1
for question in qaire.survey_id.question_ids:
new_level = len(question.complete_place)/2
if question.page != actual_page:
continue
if level < new_level:
level = new_level
elif level > new_level:
level = new_level
item_map = {
'name': question.name,
'complete_name': question.complete_name.replace(' ',''),
'complete_place': question.complete_place,
'question': question.question,
'readonly': question.type=="Variable" and question.initial_state=="enabled" and "false" or "true",
}
if question.type=='Null':
view_item.append(
'<label string="" colspan="1" class="sm_null"/>'
'<label string="%(name)s" colspan="1" class="sm_null"/>'
'<label string="%(question)s" colspan="3" class="sm_null"/>'
'<newline/>'
% item_map
)
if question.type=='View':
view_item.append(
'<label string="%(complete_name)s" colspan="1" class="sm_view"/>'
'<label string="%(question)s" class="sm_view" colspan="4"/>'
'<newline/>'
% item_map
)
if question.type=='Variable':
view_item.append(
'<label string="%(complete_name)s" colspan="1" class="sm_complete_name"/>'
'<label string="%(question)s" colspan="1" class="sm_question"/>'
'<field name="inp_%(complete_place)s" on_change="onchange_input(inp_%(complete_place)s, \'%(complete_place)s\')"'
' modifiers="{"readonly": [["sta_%(complete_place)s", "not in", ["enabled"]]]}"'
' nolabel="1" colspan="1" class="sm_input"/>'
'<field name="vms_%(complete_place)s" modifiers="{"readonly": true}" nolabel="1" colspan="1" widget="text_html" class="sm_message"/>'
'<field name="vfo_%(complete_place)s" modifiers="{"readonly": true}" nolabel="1" colspan="1" class="sm_formated"/>'
'<field name="val_%(complete_place)s" nolabel="1" modifiers="{"readonly": [["vms_%(complete_place)s", "in", [false, ""]]], "invisible": false }" colspan="1"/>'
'<field name="sta_%(complete_place)s" modifiers="{"invisible": true}" nolabel="1" colspan="1"/>'
'<field name="msg_%(complete_place)s" modifiers="{"readonly": false,"invisible": true}"/>'
'<field name="for_%(complete_place)s" modifiers="{"readonly": false,"invisible": true}"/>'
'<newline/>'% item_map
)
fields['inp_%s' % question.complete_place] = {
'selectable': False,
'readonly': question.type != 'Variable',
'type': 'char',
'string': "%s" % (question.question),
}
fields['msg_%s' % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'char',
'string': 'Invisible Message',
}
fields['vms_%s' % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'char',
'string': 'Message',
}
fields['sta_%s' % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'char',
'string': 'Status',
}
fields['for_%s' % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'char',
'string': 'Invisible Formated',
}
fields['vfo_%s' % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'char',
'string': 'Formated',
}
fields['val_%s' % question.complete_place] = {
'selectable': False,
'readonly': True,
'type': 'boolean',
'string': 'Valid',
}
view_item.append('</group>')
view_item.append(_enter_js)
view = """<group position="after"> <separator string="Page %i."/> %s </group>""" % (actual_page, ' '.join(view_item))
return view, fields
def fields_view_get_callcenter(self, cr, uid, questionnaire_id, actual_page=None):
qaire_ids = self.search(cr, uid, [('id','=',questionnaire_id)])[:1]
view_item = ['<group colspan="4" col="6">']
fields = {}
types = {
'Char': 'char',
'Boolean': 'boolean',
'Select one': 'selection',
}
for qaire in self.browse(cr, uid, qaire_ids):
level = 1
parameters = dict((p.name, p.value) for p in qaire.parameter_ids)
for question in qaire.survey_id.question_ids:
new_level = len(question.complete_place)/2
if actual_page is None or question.page != actual_page:
continue
if level < new_level:
level = new_level
elif level > new_level:
level = new_level
item_map = {
'name': question.name,
'complete_name': question.complete_name.replace(' ',''),
'complete_place': question.complete_place,
'question': question.question,
'readonly': question.type=="Variable" and question.initial_state=="enabled" and "false" or "true",
}
if question.type=='View':
view_item.append(
#'<label string="%(complete_name)s" colspan="1" class="sm_view"/>'
'<label string="%(question)s" class="sm_view" colspan="4"/>'
'<newline/>'
% item_map
)
if question.type=='Null':
view_item.append(
#'<label string="" colspan="1" class="sm_null"/>'
#'<label string="%(name)s" colspan="1" class="sm_null"/>'
'<label string="%(question)s" colspan="1" class="sm_null"/>'
'<newline/>'
% item_map
)
if question.type=='Variable':
enable_conditions = []
# Indico en que estado debe estar habilitada la entrada.
if question.enable_in:
enable_conditions.append('|')
enable_conditions.append([ 'state', '!=', question.enable_in.encode('ascii')])
# Armo las condiciones de control.
if question.enable_condition_ids:
for c in question.enable_condition_ids[:-1]:
enable_conditions.append('&')
enable_conditions.append(['inp_{0}'.format(c.operated_node_id.complete_place), c.operator.encode('utf8'), JavaScript(c.value)])
c = question.enable_condition_ids[-1]
enable_conditions.append(['inp_{0}'.format(c.operated_node_id.complete_place), c.operator.encode('utf8'), JavaScript(c.value)])
else:
# Le quito la operación OR que es una operación binaria.
enable_conditions = enable_conditions[1:]
# Compilo las condiciones.
rep_enable_conditions = repr(enable_conditions).replace('\'','"').replace('"','"')
item_map['enable_condition'] = 'modifiers="{{"readonly": {0!s}}}"'.format(rep_enable_conditions) if rep_enable_conditions else ""
view_item.append(
# '<label string="%(complete_name)s" colspan="1" class="sm_complete_name"/>'
'<label for="inp_%(complete_place)s" colspan="3" class="sm_complete_name"/>'
# '<label string="" colspan="1"/>'
'<field name="inp_%(complete_place)s"'
' colspan="3"'
' class="sm_input"'
' nolabel="1"'
' %(enable_condition)s/>'
% item_map
)
# Si no todos los parámetros fueron resueltos no
# se resuelven todos los parámetros.
try:
f_string = question.question.format(**parameters)
except:
f_string = question.question
# Declaro el campo.
fields['inp_%s' % question.complete_place] = {
'selectable': False,
'readonly': question.type != 'Variable',
'type': types.get(question.format_id.name, 'char'),
'string': f_string,
}
# Si es de tipo selection agrego las opciones
if types.get(question.format_id.name, 'char') == 'selection':
fields['inp_%s' % question.complete_place]['selection'] = [ (q.name, q.question) for q in question.child_ids if q.type == 'Null' ]
view_item.append('</group>')
view_item.append(_enter_js)
view = """
<group id="body" position="inside">
<separator string="%s."/>
<newline/>
%s
</group>""" % ((actual_page and "Page %i" % actual_page) or "No Page", '\n'.join(view_item))
_logger.debug(view)
return view, fields
def fields_view_get(self, cr, uid, view_id=None, view_type=None, context=None, toolbar=False, submenu=False):
"""
Genera la vista dinámicamente, según las preguntas de la encuesta.
"""
if context is None:
context = {}
questionnaire_id = context.get('questionnaire_id', context.get('actual_id', None))
actual_page = context.get('actual_page',1)
res = super(questionnaire, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
# En la primera vista, como es genérica para cualquier cuestionario, no vamos a tener la información
# de como se cargan los datos. Es por ello que va a aparecer sin el cuestionario. Una vez que sepamos
# cual es la encuesta, podemos completar el formulario.
if view_type == "form" and questionnaire_id is not None:
source = etree.fromstring(encode(res['arch']))
#insert_view, insert_fields = self.fields_view_get_dataentry(cr, uid, questionnaire_id, actual_page)
insert_view, insert_fields = self.fields_view_get_callcenter(cr, uid, questionnaire_id, actual_page=None)
res['fields'].update(insert_fields)
source = apply_inheritance_specs(source, insert_view, view_id)
res.update(
arch=etree.tostring(source)
)
return res
def prev_page(self, cr, uid, ids, context=None):
context = context or {}
for q in self.browse(cr, uid, ids, context=None):
cr.execute('SELECT MAX(Q.page) FROM sondaggio_answer AS A '
' LEFT JOIN sondaggio_node AS Q ON A.question_id=Q.id '
'WHERE A.questionnaire_id = %s '
' AND Q.page < %s '
' AND A.state = \'enabled\'', (q.id, q.actual_page))
next_page = cr.fetchall()
if next_page and next_page > q.actual_page:
actual_page = next_page[0][0]
self.write(cr, uid, [q.id], {'actual_page': actual_page})
context['questionnaire_id'] = q.id
context['actual_page'] = actual_page
return {
'type': 'ir.actions.act_window',
'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''),
'view_type': 'form',
'view_mode': 'form',
'target': 'current',
'res_model': 'sondaggio.questionnaire',
'res_id': context['questionnaire_id'],
'context': context,
}
def refresh_page(self, cr, uid, ids, context=None):
context = context or {}
for q in self.browse(cr, uid, ids, context=context):
actual_page = q.actual_page
context['questionnaire_id'] = q.id
context['actual_page'] = actual_page
return {
'type': 'ir.actions.act_window',
'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''),
'view_type': 'form',
'view_mode': 'form',
'target': 'current',
'res_model': 'sondaggio.questionnaire',
'res_id': context['questionnaire_id'],
'context': context,
}
def next_page(self, cr, uid, ids, context=None):
context = context or {}
for q in self.browse(cr, uid, ids, context=context):
cr.execute('SELECT MIN(Q.page) FROM sondaggio_answer AS A '
' LEFT JOIN sondaggio_node AS Q ON A.question_id=Q.id '
'WHERE A.questionnaire_id = %s '
' AND Q.page > %s '
' AND A.state = \'enabled\'', (q.id, q.actual_page))
next_page = cr.fetchall()
if next_page and next_page > q.actual_page:
actual_page = next_page[0][0]
self.write(cr, uid, [q.id], {'actual_page': actual_page})
context['questionnaire_id'] = q.id
context['actual_page'] = actual_page
return {
'type': 'ir.actions.act_window',
'name': 'Questionary.%s' % ( actual_page and ' Page %i' % actual_page or ''),
'view_type': 'form',
'view_mode': 'form',
'target': 'current',
'res_model': 'sondaggio.questionnaire',
'res_id': context['questionnaire_id'],
'context': context,
}
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
"""
Lee los campos a partir de las asnwer asociadas.
"""
answer_obj = self.pool.get('sondaggio.answer')
question_obj = self.pool.get('sondaggio.node')
res = super(questionnaire, self).read(cr, uid, ids, fields=fields, context=context, load=load)
for r in res:
if 'survey_id' not in r:
continue
survey_id = r['survey_id']
survey_id = survey_id if type(survey_id) is int else survey_id[0]
a_ids = answer_obj.search(cr, uid, [ ('questionnaire_id','=',r['id']) ])
# Creamos las preguntas si no existen.
if a_ids == []:
q_ids = question_obj.search(cr, uid, [('survey_id','=',survey_id), ('variable_name','!=','')])
for question in question_obj.browse(cr, uid, q_ids):
v = {
'name': question.variable_name,
'input': False,
'formated': False,
'message': False,
'valid': False,
'questionnaire_id': r['id'],
'question_id': question.id,
}
_logger.debug("Creating: %s", v)
a_ids.append(answer_obj.create(cr, uid, v))
answer_obj.write(cr, uid, a_ids[-1], {'state': question.initial_state})
# Leemos las preguntas.
for answer in answer_obj.browse(cr, uid, a_ids):
r['inp_%s' % answer.name]=answer.input
r['msg_%s' % answer.name]=answer.message
r['vms_%s' % answer.name]=answer.message
r['sta_%s' % answer.name]=answer.state
r['for_%s' % answer.name]=answer.formated
r['vfo_%s' % answer.name]=answer.formated
r['val_%s' % answer.name]=answer.valid
return res
def is_valid(self, cr, uid, ids, values, context=None):
for i in [ i for i in values.keys() if 'in_' in i ]:
import pdb; pdb.set_trace()
return True
def write(self, cr, uid, ids, values, context=None):
"""
Escribe los campos a las answers asociadas.
"""
answer_obj = self.pool.get('sondaggio.answer')
question_obj = self.pool.get('sondaggio.node')
# Actualizamos fecha de valudacion si hay cambio de parametros.
if 'parameter_ids' in values:
fecha_actual = datetime.now().strftime('%d%m%Y')
parameter_ids = values['parameter_ids']
parameter_obj = self.pool.get('sondaggio.parameter')
fecha_ver_id = parameter_obj.search(cr, uid, [('questionnaire_id','in',ids),('name','=','fecha_ver')])
if fecha_ver_id:
change = lambda a,b,c: b if a in fecha_ver_id else c
parameter_ids = [ [ change(b, 1, a), b, change(b, dict(c or {},value=fecha_actual), c) ]
for a,b,c in parameter_ids ]
else:
# Crear parametro fecha
parameter_ids = parameter_ids + [[0,0,{'name':'fecha_ver', 'value':fecha_actual}]]
values['parameter_ids'] = parameter_ids
res = super(questionnaire, self).write(cr, uid, ids, values, context=context)
if self.is_valid(cr, uid, ids, values, context=None):
answer_ids = answer_obj.search(cr, uid, [
('questionnaire_id','in',ids),
('name','in',[key[4:] for key in values.keys() if key[3]=="_"])
])
to_create = list(values.keys())
for answer in answer_obj.read(cr, uid, answer_ids, ['name']):
variable_name = answer['name']
v = { }
if 'msg_%s' % variable_name in values: v.update(message = values['msg_%s' % variable_name])
if 'sta_%s' % variable_name in values: v.update(state = values['sta_%s' % variable_name])
if 'inp_%s' % variable_name in values: v.update(input = values['inp_%s' % variable_name])
if 'for_%s' % variable_name in values: v.update(formated = values['for_%s' % variable_name])
if 'val_%s' % variable_name in values: v.update(valid = values['val_%s' % variable_name])
answer_obj.write(cr, uid, answer['id'], v)
to_create.remove('inp_%s' % answer['name'])
for a in to_create:
prefix, variable_name = a[:4], a[4:]
if 'inp_' == prefix:
question_ids = question_obj.search(cr, uid, [('variable_name','=',variable_name)])
for question_id in question_ids:
_logger.debug('Creating variable %s' % variable_name)
for _id in ids:
answer_obj.create(cr, uid, {'name': a[4:],
'questionnaire_id': _id,
'question_id': question_id,
'message': values.get('msg_%s' % variable_name, False),
'state': values.get('sta_%s' % variable_name, False),
'input': values.get('inp_%s' % variable_name, False),
'formated': values.get('for_%s' % variable_name, False),
'valid': values.get('val_%s' % variable_name, False),
})
pass
return True
else:
return False
def on_open_ui(self, cr, uid, ids, context=None):
context = context or {}
q = self.read(cr, uid, ids, ['code'])
if q:
context.update(
active_id=q[0]['id'],
active_code=q[0]['code'],
)
return {
'type' : 'ir.actions.client',
'name' : _('Start Questionnaire'),
'tag' : 'questionnaire.ui',
'context' : context
}
def on_open_online(self, cr, uid, ids, context=None):
return self.on_open_ui(cr, uid, ids, context=dict(context, channel='online'))
def on_open_offline(self, cr, uid, ids, context=None):
return self.on_open_ui(cr, uid, ids, context=dict(context, channel='offline'))
def on_open_telephonic(self, cr, uid, ids, context=None):
return self.on_open_ui(cr, uid, ids, context=dict(context, channel='telephonic'))
def on_open_personal(self, cr, uid, ids, context=None):
return self.on_open_ui(cr, uid, ids, context=dict(context, channel='personal'))
def on_open_mailing(self, cr, uid, ids, context=None):
return self.on_open_ui(cr, uid, ids, context=dict(context, channel='mailing'))
def exec_workflow_cr(self, cr, uid, ids, signal, context=None):
wf_service = netsvc.LocalService("workflow")
_logger.debug('Recibing signal %s for %s' % (signal, ids))
for id in ids:
wf_service.trg_validate(uid, self._name, id, signal, cr)
data = self.read(cr, uid, id, ['state'])
_logger.debug('Solve to state %s' % data['state'])
return data['state']
def do_backup(self, cr, uid, ids, state=None, context=None):
"""
Append the rotated questionnaire in a file.
"""
out_filename = "/tmp/questionnaire_bk.csv"
header = not os.path.exists(out_filename)
out_file = open(out_filename, 'a')
_logger.info("Backup questionnaire. header=%s" % str(header))
dump_inputs(cr, questionnaire_ids = ids, out_file=out_file, header=header, state=state)
return True
def onchange_survey_id(self, cr, uid, ids, survey_id):
"""
Set list of parameters if any questionnaire in the same survey have defined parameters.
"""
pars = []
if survey_id:
cr.execute("""
select P.name, '' as value
FROM sondaggio_questionnaire AS Q
LEFT JOIN sondaggio_parameter AS P ON (Q.id = P.questionnaire_id)
WHERE Q.survey_id=%s GROUP BY P.name ORDER BY P.name;
""", (survey_id,))
pars = cr.fetchall()
pars = map(lambda (n,v): (0,0,dict(name=n,value=v)), pars)
return {'value':{ 'parameter_ids': pars } }
questionnaire()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
UTF-8
|
Python
| false | false | 2,013 |
3,015,067,048,848 |
f73f069fd43a26691430baea254c1775018ee5c8
|
de230f2156f270a8022fef2a2e2a8f6d8e9bdf10
|
/draw.py
|
1c260e5e6537105dda65f5b4ceff12e71c134d30
|
[] |
no_license
|
crane-may/FlappyBirdBot
|
https://github.com/crane-may/FlappyBirdBot
|
2e35cfea1424e3a4e8c63694b9e768b4a421de27
|
77c33d101254ac71af4c8af207ad5c3f6ab54a9d
|
refs/heads/master
| 2016-09-06T18:33:47.569059 | 2014-04-05T23:43:41 | 2014-04-05T23:43:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
import cv2
from PIL import Image, ImageTk, ImageDraw
def c(color):
return (color[2],color[1],color[0])
def d(p):
return (int(p[0]),int(p[1]))
def cvImg(img, path):
if isinstance(img, ImageDraw.ImageDraw):
return cv2.imread(path)
else:
return img
def start(img):
if isinstance(img, Image.Image):
return ImageDraw.Draw(img)
else:
return img
def end(img):
if isinstance(img, ImageDraw.ImageDraw):
del img
def line(img, start, end, color=(0,0,0), width=1):
if isinstance(img, ImageDraw.ImageDraw):
img.line(start + end, fill=color, width=width)
else:
cv2.line(img, d(start), d(end), c(color), width)
def point(img, pos, color=(0,0,0), r=4):
if isinstance(img, ImageDraw.ImageDraw):
img.ellipse((pos[0]-r, pos[1]-r, pos[0]+r, pos[1]+r), fill=color)
else:
cv2.circle(img,d(pos),r/2,c(color),r)
def box(img, p1, p2, color=(0,0,0), width=3):
if isinstance(img, ImageDraw.ImageDraw):
img.rectangle(p1+p2, fill=color,width=3)
else:
cv2.rectangle(img,d(p1),d(p2),c(color),width)
|
UTF-8
|
Python
| false | false | 2,014 |
15,212,774,165,375 |
ea7b519ef807caa19f007b22d6e4016e3f9ca9e9
|
906cce89781b387955e67032167c6f53224bfac3
|
/src/hack4lt/templatetags/utils.py
|
121761e1ef9c1d8de912c6fda6ca92a8c8e67f29
|
[
"BSD-3-Clause"
] |
permissive
|
daukantas/Hack4LT
|
https://github.com/daukantas/Hack4LT
|
05eab65047077a0113acf96713b8666f15da8136
|
d45bf7d6fea9fd6f7910254f96823ff1345f6b5d
|
refs/heads/master
| 2021-01-01T19:41:39.347735 | 2014-06-07T11:33:47 | 2014-06-07T11:33:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django import template
register = template.Library()
@register.filter
def value(value, key):
return value[key]
|
UTF-8
|
Python
| false | false | 2,014 |
7,919,919,726,349 |
3e0ed1e27660277be044365a7bf39497eb08657c
|
8b650615d954f1c6e3e5d37d2f3fcd2eb5136abf
|
/numhw2.py
|
7a6d572ef815df70bd4832e905c913d907c75462
|
[
"LGPL-3.0-only"
] |
non_permissive
|
abrosen/numerical-analysis
|
https://github.com/abrosen/numerical-analysis
|
cc988fd537273a5d3786596589adb25b78c7d27d
|
1958eb02db4aa272112c6588227b34150be9039a
|
refs/heads/master
| 2021-01-15T14:03:18.145838 | 2014-07-05T20:06:13 | 2014-07-05T20:06:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#Andrew Rosen
from math import *
def computeCoeffs(x, y):
diffs = divDiffs(x,y)
coeffs = []
for diff in diffs:
coeffs.append(diff[0])
return coeffs
def divDiffs(x,y):
diffs = []
for i in range(0, len(x)):
diffs.append([None] * (len(x)-i))
for i, col in enumerate(diffs):
if i == 0 :
diffs[i] = y
else:
for j in range(0, len(col)):
col[j] = (diffs[i-1][j+1] - diffs[i-1][j])/(x[j+i] - x[j])
col[j] = (diffs[i-1][j+1])/(x[j+i] - x[j]) - (diffs[i-1][j])/(x[j+i] - x[j])
diffs[i] = col
return diffs
def dDiff(x,y):
F=[[None for n in xrange(len(x))] for n in xrange(len(x))]
for a in range(0,len(x)):
F[a][0] = y[a]
for i in range(1, len(x)):
for j in range(1,i+1):
F[i][j] = (F[i][j-1] - F[i-1][j-1])/(x[i] - x[i-j])
ret = []
for i in range(0, len(x)):
ret.append(F[i][i])
return ret
def evalP(x, coeffs, target):
terms = [1.0] * len(x)
for i in range(1, len(terms)):
terms[i] = terms[i-1] * (target - x[i-1])
return sum(map(lambda a, b: a*b, coeffs, terms))
def evalP2(x, coeffs, target):
p = coeffs[0]
for i in range(1,len(coeffs)):
term = 1.0
for j in range(0,i):
term = term * (target - x[j])
p = p + coeffs[i] * term
return p
def chebyZeros(num):
zeros = []
for k in range(1,num+1):
zeros.append(cos(pi*((2*k - 1.0)/(2*num))))
return zeros
f = lambda x: (1 +( 25* x** 2))**(-1)
target = .985
x1 = []
for j in range(0,21):
x1.append(-1 +(j/10.0))
x2 = chebyZeros(21)
y1 = map(f, x1)
y2 = map(f, x2)
ans = f(target)
calc1 = evalP(x1,computeCoeffs(x1,y1),target)
calc2 = evalP(x2,computeCoeffs(x2,y2),target)
print "f(x): ", ans
print "Calculated: ", calc1, calc2
print "Error: ", fabs(calc1 - ans), fabs(calc2 - ans)
|
UTF-8
|
Python
| false | false | 2,014 |
14,139,032,340,583 |
4fc5a0cd2e95e6ecd70c0b2fdb3e574b862e7101
|
833837058641a26337791bf4e06bb7f8925de149
|
/setup.py
|
c1a135c1d44e28fcb1afe0a370c4748814327f24
|
[
"GPL-1.0-or-later",
"GPL-2.0-only"
] |
non_permissive
|
thehub/hubspace
|
https://github.com/thehub/hubspace
|
4228f5fb81ce5a44a1bdc5ecfa12279c3f1a23cc
|
244028bb414bdefb5c1c8622e098ba643e7c73e0
|
refs/heads/master
| 2021-01-10T22:07:06.792136 | 2013-08-01T15:57:24 | 2013-08-01T15:57:24 | 228,562 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from setuptools import setup, find_packages
#from turbogears.finddata import find_package_data
import sys, os
version = '1.0'
setup(name='hubspace',
version=version,
description="Hub space management system",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='hub space mangement',
author='tom salfield',
author_email='tom.salfield@the-hub.net',
url='the-hub.net',
license='GPL',
packages=find_packages(),
#package_data = find_package_data(where='hubspace',
# package='hubspace'),
include_package_data=True,
zip_safe=False,
install_requires=[
"TurboGears == 1.0.7",
"SQLObject == 0.10.2",
"formencode >= 0.7.1",
"smbpasswd",
#"syncer",
"kid",
"docutils",
"TurboFeeds",
"funkload",
"pytz",
"pycountry",
"nose",
"BeautifulSoup",
"mechanize",
"whoosh",
"pycha",
"Mako",
"httpagentparser",
"html5lib",
"vobject",
"pisa",
"reportlab",
"psycopg2"
],
entry_points="""
[console_scripts]
run_hubspace = start_hubspace:main
export2ldap = hubspace.sync.export2ldap:main
exportmissingusers2ldap = hubspace.sync.tools:exportMissingUsers2LDAP
sync_static = git_postmerge:main
""",
test_suite = 'nose.collector',
)
|
UTF-8
|
Python
| false | false | 2,013 |
9,174,050,187,092 |
30b030319813071c7e546be1351b58e30d5ad348
|
347523b5ea88c36f6a7d7916426f219aafc4bbf8
|
/src/Tools/blocFissure/gmu/fissureGenerique.py
|
17518e8715f59b412faefee23b2cb9cadef5c672
|
[
"LGPL-2.1-only"
] |
non_permissive
|
FedoraScientific/salome-smesh
|
https://github.com/FedoraScientific/salome-smesh
|
397d95dc565b50004190755b56333c1dab86e9e1
|
9933995f6cd20e2169cbcf751f8647f9598c58f4
|
refs/heads/master
| 2020-06-04T08:05:59.662739 | 2014-11-20T13:06:53 | 2014-11-20T13:06:53 | 26,962,696 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from blocFissure import gmu
from blocFissure.gmu.initEtude import initEtude
from blocFissure.gmu.getStatsMaillageFissure import getStatsMaillageFissure
class fissureGenerique():
"""
classe générique problème fissure:
génération géométrie et maillage sain
définition et positionnement d'une fissure
génération d'un bloc défaut inséré dans le maillage sain
"""
nomProbleme = "generique"
def __init__(self, numeroCas):
initEtude()
self.numeroCas = numeroCas
self.nomCas = self.nomProbleme +"_%d"%(self.numeroCas)
self.fissureLongue = False
def setParamGeometrieSaine(self):
self.geomParams = {}
def genereGeometrieSaine(self, geomParams):
geometriesSaines = [None]
return geometriesSaines
def setParamMaillageSain(self):
self.meshParams = {}
def genereMaillageSain(self, geometriesSaines, meshParams):
maillagesSains = [None]
return maillagesSains
def setParamShapeFissure(self):
self.shapeFissureParams = {}
def genereShapeFissure(self, geometriesSaines, geomParams, shapeFissureParams):
shapesFissure = [None]
return shapesFissure
def setParamMaillageFissure(self):
self.maillageFissureParams = {}
def genereZoneDefaut(self, geometriesSaines, maillagesSains, shapesFissure, maillageFissureParams):
elementsDefaut = [None]
return elementsDefaut
def genereMaillageFissure(self, geometriesSaines, maillagesSains, shapesFissure,
maillageFissureParams, elementsDefaut, step):
maillageFissure = None
return maillageFissure
def setReferencesMaillageFissure(self):
referencesMaillageFissure = {}
return referencesMaillageFissure
# ---------------------------------------------------------------------------
def executeProbleme(self, step=-1):
print "executeProbleme", self.nomCas
if step == 0:
return
self.setParamGeometrieSaine()
geometriesSaines = self.genereGeometrieSaine(self.geomParams)
if step == 1:
return
self.setParamMaillageSain()
maillagesSains = self.genereMaillageSain(geometriesSaines, self.meshParams)
if step == 2:
return
self.setParamShapeFissure()
shapesFissure = self.genereShapeFissure(geometriesSaines, self.geomParams, self.shapeFissureParams)
if step == 3:
return
self.setParamMaillageFissure()
elementsDefaut = self.genereZoneDefaut(geometriesSaines, maillagesSains, shapesFissure, self.shapeFissureParams, self.maillageFissureParams)
if step == 4:
return
maillageFissure = self.genereMaillageFissure(geometriesSaines, maillagesSains,
shapesFissure, self.shapeFissureParams,
self.maillageFissureParams, elementsDefaut, step)
self.setReferencesMaillageFissure()
mesures = getStatsMaillageFissure(maillageFissure, self.referencesMaillageFissure, self.maillageFissureParams)
|
UTF-8
|
Python
| false | false | 2,014 |
18,923,625,912,029 |
1d5c8d1d6ac39288738199a3eace388b318b2802
|
d02a49c1f979fff8b095c3eef5539c865d30aaf8
|
/main.py
|
3e2f4a73d2c18400e912708701f4bbdca96e9cbe
|
[] |
no_license
|
zjedwin/predictiveCapability
|
https://github.com/zjedwin/predictiveCapability
|
e72cfbf576000f85fe3cb6c284fa16a2761b5879
|
6b5c51b17f57e9cb243ca2e243b738d1f22bb374
|
refs/heads/master
| 2020-12-11T04:20:17.102596 | 2014-12-16T03:57:00 | 2014-12-16T03:57:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Authors:
# uniqnames:
# Date:
# Purpose:
# Description:
import sys
import csv
import generation
import measures
import diagnostics
"""
Use this function for your testing for bare-bones, and then use it as the driver
for your project extension
"""
def main(argv):
pass
# DO NOT modify these 2 lines of code or you will be very sad
# Similarly, do not place any code below them
if __name__ == "__main__":
main(sys.argv)
|
UTF-8
|
Python
| false | false | 2,014 |
51,539,618,046 |
1cf81a27fe0e6b6a6b7687616b3437c2476b9862
|
23fc722fe3c80ee08641e5c19b9ea629092d91eb
|
/bracket/controllers/index.py
|
4fd56742b99046c1592ed6ced4d192c37233c6a3
|
[] |
no_license
|
dwiel/bowling-brackets
|
https://github.com/dwiel/bowling-brackets
|
2f7db5e58e0019cfb636cfa3e9af5d3d50074bea
|
62a5ba65c5441ec6570a684c92667846dd97c2da
|
refs/heads/master
| 2020-05-30T04:29:34.948207 | 2012-01-19T04:18:24 | 2012-01-19T04:18:24 | 301,623 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
import logging
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort
from bracket.lib.base import BaseController, render
log = logging.getLogger(__name__)
class IndexController(BaseController):
def index(self):
try :
c.names = [name.strip() for name in open('names', 'r')]
except IOError, e:
c.names = []
return render('/index.mako')
def create_new_person(self):
f = open('names', 'a')
print >>f, request.params['name']
f.close()
def remove_person(self):
# read names
f = open('names')
namesf = f.read()
f.close()
# remove name
names = namesf.split('\n')
names = [name for name in names if name != request.params['name'] and name != '']
# write names
f = open('names', 'w')
for name in names :
print >>f, name
f.close()
|
UTF-8
|
Python
| false | false | 2,012 |
3,255,585,211,863 |
22e80414886fff6137501a7fb2011c9a2a1302b3
|
3fa2f2c75f44ca561babe0012ccad35e7c4c67ed
|
/chapter3_p3.py
|
b5a12d17ed0b38d4310ca1b0cfcc46606f7ebaee
|
[] |
no_license
|
sparkoo/Python
|
https://github.com/sparkoo/Python
|
20efbd8477bce079fe831fed132fd989a5c8cfe5
|
4cfffb7c35495208c4a39786ed0421346c75d814
|
refs/heads/master
| 2016-09-07T02:34:20.941970 | 2013-07-17T21:58:02 | 2013-07-17T21:58:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import turtle
def turtleInit(worldcoordinates):
t = turtle.getturtle()
s = turtle.getscreen()
turtle.tracer(100, 0)
s.setworldcoordinates(worldcoordinates[0], worldcoordinates[1], worldcoordinates[2], worldcoordinates[3])
return (t, s)
def turtleClosing(screen):
screen.update()
screen.exitonclick()
def collatz(x):
output = [0,0,[]] #steps, maximum, sequence
while x != 1:
output[0] += 1
if output[1] < x:
output[1] = x
output[2] += [x]
if x % 2 == 0:
x //= 2
else:
x = x * 3 + 1
return output
def drawGraph(x):
l = collatz(x)
t = turtleInit([0, 0, l[0], l[1]])
x = 0
for i in l[2]:
t[0].goto(x, i)
t[0].dot()
x += 1
turtleClosing(t[1])
def graphWithStepCounts(n):
x, m, c = 0, 0, []
for i in range(1, n):
l = collatz(i)
c += [l[0]]
if m < l[0]:
m = l[0]
print(n, m)
t = turtleInit([0, 0, n, m])
t[0].pu()
for i in c:
t[0].goto(x, i)
t[0].dot()
x += 1
turtleClosing(t[1])
def graphWithMaxValuesCounts(n):
x, m, c = 0, 0, []
for i in range(1, n):
l = collatz(i)
c += [l[1]]
if m < l[1]:
m = l[1]
print(n, m)
t = turtleInit([0, 0, n, m])
t[0].pu()
for i in c:
t[0].goto(x, i)
t[0].dot()
x += 1
turtleClosing(t[1])
def getMaxStepsAndValue(n):
m = [0, 0, 0]
for i in range(1, n):
l = collatz(i)
if m[2] < l[0]:
m[0] = i
m[1] = l[1]
m[2] = l[0]
return m
def records(n):
output, lastRecord = [], 0
for i in range(1, n):
record = collatz(i)[0]
if lastRecord <= record:
output += [i]
lastRecord = record
return output
drawGraph(57)
graphWithStepCounts(10000)
graphWithMaxValuesCounts(10000)
print(getMaxStepsAndValue(100000))
print(records(100000))
|
UTF-8
|
Python
| false | false | 2,013 |
6,485,400,628,865 |
3aca8818a4239e745721f39f1f8aad7eb10c378e
|
abc0c03bc6e404bcd58742b674e73658d1d11a87
|
/blog/posts/rails-singularplural-reference-chart/meta.py
|
10f97d7f6b3daaac5ba2f366eb84561092bc5430
|
[] |
no_license
|
atefzed/Vert-Flask
|
https://github.com/atefzed/Vert-Flask
|
c85fd5bf771a47ca1f3ed41fbd62ac1f287ec044
|
0702ab36f4349ff056b7f74cd8030b82c088544e
|
refs/heads/master
| 2020-12-24T13:53:32.578456 | 2012-07-26T00:47:30 | 2012-07-26T00:47:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
title="""Rails Singular/Plural Reference Chart"""
description=""""""
time="""2011-09-08 Thu 17:03 PM"""
excerpt="""I've begun my descent into pure Rails. The whole naming convention idiom is hard to remember while I'm just learning, so here's a reference chart for myself and for any other Rails noobs."""
|
UTF-8
|
Python
| false | false | 2,012 |
17,678,085,402,527 |
88f18965e233fe7de76fda20c90d2bfe57830690
|
d486f9334ed2d9c35a5088710f51632fee46135c
|
/src/util/freespace.py
|
657b0425f1cbc1285e3306a6ccd11e92c0913ead
|
[] |
no_license
|
bluescorpio/PyProjs
|
https://github.com/bluescorpio/PyProjs
|
9ae1451fc6035c70c97015887fe40947fbe0b56d
|
7df126ec7930484b4547aaf15fa8c04f08a5ca7e
|
refs/heads/master
| 2016-08-01T13:36:51.555589 | 2014-05-28T14:00:56 | 2014-05-28T14:00:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#coding=utf-8
import win32file
sectorsPerCluster, bytesPerSector, numFreeClusters, totalNumClusters \
= win32file.GetDiskFreeSpace("c:\\")
print "FreeSpace: ", (numFreeClusters * sectorsPerCluster * bytesPerSector)/(1024*1024), "MB"
|
UTF-8
|
Python
| false | false | 2,014 |
7,825,430,416,138 |
b21add0562d50641aaef4fef6aec2f65a660c69f
|
f1ec1a0ccc09732338ffdd5bb6e4563cd9a47888
|
/priorityDB/priorityDB/admin.py
|
f0b399c3f1d41ac56233cb3b44cbf8a47ee2b202
|
[
"GPL-2.0-only",
"Apache-2.0"
] |
non_permissive
|
lowellbander/ngVote
|
https://github.com/lowellbander/ngVote
|
61f99ed8d5686e065137ddec96a5b43df7e9592c
|
f00939b070721af52ec745235777baeccafaad74
|
refs/heads/master
| 2020-05-20T11:09:16.668450 | 2013-11-15T07:18:44 | 2013-11-15T07:18:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.contrib import admin
from priorityDB.models import *
# Register your models here
# For more information on this file, see
# https://docs.djangoproject.com/en/dev/intro/tutorial02/
class TaskHistoryInline(admin.StackedInline):
model = TaskHistory
extra = 0
class EventAdmin(admin.ModelAdmin):
inlines = [TaskHistoryInline]
admin.site.register(Event, EventAdmin)
admin.site.register(Task)
|
UTF-8
|
Python
| false | false | 2,013 |
4,887,672,826,531 |
93134187cb4f6693f57b1d2466e887ea7bc26705
|
c27d9b31be4874d81aee0fdb4ffb9710b3419e9a
|
/atoggleSubD.py
|
5e827bc140996a9917fda539fff32b193b483fbc
|
[
"MIT"
] |
permissive
|
arubertoson/maya-aru
|
https://github.com/arubertoson/maya-aru
|
cd9894cfe3ecdb016c6300fcd49950feafeed1c5
|
533763d26748deed3396a94b94c9dc48e739a34e
|
refs/heads/master
| 2015-08-12T13:53:29.345836 | 2014-09-21T20:45:34 | 2014-09-21T20:45:34 | 22,063,187 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
asubdToggle.py
author: Marcus Albertsson
marcus.arubertoson_at_gmail.com
Toggle smoothmesh.
callable:
asubdToggle.toggle(hierarchy)
hierarchy: [True, False]
asubdToggle.all_on()
asubdToggle.all_off()
asubdToggle.add_level()
asubdToggle.sub_level()
"""
import pymel.core as pymel
class SubD(object):
def __init__(self, hierarchy=True):
self.hierarchy = hierarchy
self.meshes = []
self.all_off, self.all_on = False, False
def perform_all(self, on_off):
if on_off:
self.all_on = True
else:
self.all_off = True
self.meshes = pymel.ls(type='mesh')
self.__toggle()
def perform_change_level(self, up_down):
self.__get_mesh_in_selection()
self.__adjust_level(up_down)
def perform_toggle(self):
self.__get_mesh_in_selection()
print self.meshes
self.__toggle()
def __get_mesh_in_selection(self):
hilited = pymel.ls(hl=True)
if hilited:
self.meshes = [i.getShape() for i in hilited]
return
if self.hierarchy:
self.meshes = pymel.ls(sl=True, dag=True, type='mesh')
else:
self.meshes = pymel.ls(sl=True, type='mesh')
def __adjust_level(self, mode):
level = 1 if mode else -1
for mesh in self.meshes:
current_level = mesh.smoothLevel.get()
mesh.smoothLevel.set(current_level+level)
def __toggle(self):
for mesh in self.meshes:
if self.all_off:
pymel.displaySmoothness(mesh, polygonObject=0)
continue
elif self.all_on:
pymel.displaySmoothness(mesh, polygonObject=3)
continue
state = pymel.displaySmoothness(mesh, q=True, polygonObject=True)
if state is None:
continue
mode = 0 if state.pop() else 3
pymel.displaySmoothness(mesh, polygonObject=mode)
# Public
def add_level(hierarchy=True):
SubD(hierarchy).perform_change_level(1)
def sub_level(hierarchy=True):
SubD(hierarchy).perform_change_level(0)
def toggle(hierarchy=True):
SubD(hierarchy).perform_toggle()
def all_on():
SubD().perform_all(1)
def all_off():
SubD().perform_all(0)
|
UTF-8
|
Python
| false | false | 2,014 |
670,014,934,819 |
ec45482d32a1efe93b193ff92138d605ec2979e1
|
517c8f9b9a49cddde926b70d46a57ae2765b0b13
|
/src/util/dot.py
|
6a737a565c51da9d6c88aded4e44bc299cc6585f
|
[
"BSD-3-Clause"
] |
permissive
|
christophevg/py-util
|
https://github.com/christophevg/py-util
|
b42ab20aa9e48a43f0291cbdd45516c199216bce
|
184f2e38d8db4805e1400c47c49b1ebb04d67fdf
|
refs/heads/master
| 2020-05-27T18:10:48.011013 | 2014-09-05T11:50:33 | 2014-09-05T11:50:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# dot.py
# tools to construct and handle Graphviz dot files
# author: Christophe VG
class DotBuilder():
def __init__(self):
self.declarations = []
self.index = 0
def __str__(self):
return """
digraph {
ordering=out;
ranksep=.4;
node [shape=plaintext, fixedsize=true, fontsize=11, fontname="Courier",
width=.25, height=.25];
edge [arrowsize=.5]
""" + "\n".join(self.declarations) + "}"
def node(self, label, options={}):
node = "n" + str(self.index)
self.index+=1
options["label"] = label
if "color" in options: options["style"] = "filled"
self.declarations.append( node + "[" +
",".join(['{0}="{1}"'.format(k, v) for k, v in options.items()]) + "]" )
return node
def vertex(self, src, dest, options={}):
self.declarations.append("{0} -> {1} [{2}];".format(src, dest,
",".join(['{0}="{1}"'.format(k, v) for k, v in options.items()])))
|
UTF-8
|
Python
| false | false | 2,014 |
919,123,048,359 |
e8b8847b67a8ebf05c902103f3443a9f75c889a8
|
ff78b2043fd5a30647dfb5a29ebea74b370af3f6
|
/students/ElizabethRives/mailroom.py
|
4716db4815b8bed934300e29db0e7b14ea10cedb
|
[
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GPL-3.0-only",
"GPL-2.0-only",
"CC-BY-SA-4.0"
] |
non_permissive
|
AmandaMoen/AmandaMoen
|
https://github.com/AmandaMoen/AmandaMoen
|
7f1bd10c87eb8b3873caf2272d22a46a89db413c
|
6f4997aef6f0aecb0e092bc4b1ec2ef61c5577e8
|
refs/heads/master
| 2020-05-17T09:17:15.925291 | 2014-05-29T04:07:19 | 2014-05-29T04:07:19 | 19,657,795 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
state = 'menu'
database = {'Philip Jordan': [500.0, 200.0], 'Tom Parker': [750.0, 800.0, 750.0], 'Lisa Smith': [500.0, 500.0], 'Wayne Tucker': [400.0, 500.0], 'Jane Winkle': [800.0, 800.0, 780.0]}
def menu():
u"""Prompt the user to choose from a menu of options."""
print '## -- Type q to exit program or menu to return to main menu -- '
action = raw_input('Please choose from the following menu:\n1. Record donors and contribution amounts\n2. Create a Report\n3. Write Letters\n4. View Full Set of Letters\n')
if action == 'q':
return 'quit'
elif action == '1':
return 'record donors and contribution amounts'
elif action == '2':
return 'create a report'
elif action == '3':
return 'write letters'
elif action == '4':
return 'view full set of letters'
else:
return 'menu'
def add_to_database():
u"""Add donor name and contribution amount to the database."""
input_name = raw_input(u"Please enter the donor's first and last name\n-- type list to display donors in the database -- ")
if input_name == 'list':
print database
input_name = raw_input(u"Please enter the donor's first and last name")
if input_name == 'menu':
return 'menu'
database.setdefault(input_name, [])
while True:
input_amount = raw_input(u'Enter the donation amount')
if input_amount == 'menu':
return 'menu'
try:
input_amount = float(input_amount)
break
except ValueError:
print 'Donation amount must be a numeric input, please try again.'
database[input_name].append(input_amount)
return 'record donors and contribution amounts'
def write_letters():
u"""Write a full set of letters thanking donors for their total contribution."""
letter_file = open('letterfile.txt', 'w')
for (k, v) in database.iteritems():
letter_file.write('Dear {name},\nThank you for your generous donation of ${amount}. Your contribution will help make the impossible, possible.\nSincerely,\nOrganizationX\n\n'.format(name = k, amount = sum(v)))
letter_file.close()
print u'Done...returning to main menu'
return 'menu'
def view_letters():
u"""View content of file containing all thank you letters written."""
while True:
try:
letter_file = open('letterfile.txt', 'U')
break
except IOError:
print 'Sorry, file not found'
raise
for line in letter_file:
print line
letter_file.close()
return 'menu'
def report():
u"""Display a list of donors sorted by total historical donation amount."""
d_new = {}
for key in database.iterkeys():
name = key
values = database[key]
total = sum(values)
count = len(values)
average = sum(values)/len(values)
d_new[name] = (total, count, average)
x = list(d_new.items())
y = sorted(x, key=lambda a: a[1])
for (k, v) in y:
print u'{name}\t {total}\t {count}\t {average}\t'.format(name = k, total = v[0], count = v[1], average = v[2])
return 'menu'
lookup = {'1': add_to_database, '2': report, '3': write_letters, '4': view_letters, 'menu': menu}
if __name__ == '__main__':
while True:
if state == 'menu':
state = lookup['menu']()
if state == 'record donors and contribution amounts':
state = lookup['1']()
if state == 'create a report':
state = lookup['2']()
if state == 'write letters':
state = lookup['3']()
if state == 'view full set of letters':
state = lookup['4']()
if state == 'quit':
break
|
UTF-8
|
Python
| false | false | 2,014 |
3,590,592,701,923 |
0a6be081007bbfc560caced8cf8eb6357d32f1f2
|
b581b5cabd2090ba65c5d735bcd915a4cf12d601
|
/sensor/lsm303d.py
|
9a0e5bbefc9e8d41f11f598fdba32a5bfb1f3fd6
|
[] |
no_license
|
wll745881210/RPi_GG_HUD
|
https://github.com/wll745881210/RPi_GG_HUD
|
27e5e7bbfb6eb01eb1297745a1b901611566e7c7
|
1159af09cd9fa9095d1d2b45661d097e669f436c
|
refs/heads/master
| 2016-08-04T18:06:21.355599 | 2014-07-27T03:05:12 | 2014-07-27T03:05:12 | 22,196,626 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import i2c
from math import sqrt
############################################################
class lsm303d:
def __init__( self, i2c_bus = 1, sa0_level = 'high' ):
if sa0_level == 'high':
dev = 0b0011101;
elif sa0_level == 'low':
dev = 0b0011110;
else:
raise TypeError;
#
self.sensor_id = i2c.init( i2c_bus, dev );
self.acc_dx = 0.;
self.acc_dy = 0.;
self.acc_dz = 0.;
self.set_sample_rate( );
self.set_acc_full_scale_anti_alias( );
self.set_mag_mode( );
return;
#
def close( self ):
i2c.destruct( self.sensor_id );
def write_reg( self, reg, flag ):
i2c.write_reg( self.sensor_id, reg, flag );
return;
#
def read_reg( self, reg, size = 2 ):
return i2c.read( self.sensor_id, reg, size );
#
def magnitude( self, x, y, z ):
return sqrt( x**2 + y**2 + z**2 );
#
def set_sample_rate( self, sample_rate = '50Hz', \
block = False ):
self.sample_rate_dict \
= { 'Down' : 0b0000, \
'3.125Hz' : 0b0001, \
'6.25Hz' : 0b0010, \
'12.5Hz' : 0b0011, \
'25Hz' : 0b0100, \
'50Hz' : 0b0101, \
'100Hz' : 0b0110, \
'200Hz' : 0b0111, \
'400Hz' : 0b1000, \
'800Hz' : 0b1001, \
'1600Hz' : 0b1010 \
};
sample_rate_flag\
= self.sample_rate_dict[ sample_rate ] << 4;
if block:
block_flag = 0b1000;
else:
block_flag = 0b0000;
#
enable_flag = 0b111;
flag = sample_rate_flag + block_flag + enable_flag;
self.write_reg( self.CTRL1, flag );
return;
#
def set_acc_full_scale_anti_alias\
( self, full_scale = '4g', aa_bw = '773Hz' ):
self.aa_bw_dict \
= { '773Hz' : 0b00, \
'194Hz' : 0b01, \
'362Hz' : 0b10, \
'50Hz' : 0b11 \
};
aa_bw_flag \
= self.aa_bw_dict[ aa_bw ] << 6;
self.full_scale_dict \
= { '2g' : 0b000, \
'4g' : 0b001, \
'6g' : 0b010, \
'8g' : 0b011, \
'16g' : 0b100 \
};
full_scale_flag \
= self.full_scale_dict[ full_scale ] << 3;
self.full_scale_conv \
= { '2g' : 0.061, \
'4g' : 0.122, \
'6g' : 0.183, \
'8g' : 0.244, \
'16g' : 0.732 \
};
self.acc_conv = self.full_scale_conv[ full_scale ] \
* 0.001; # From mg to g
flag = aa_bw_flag + full_scale_flag;
self.write_reg( self.CTRL2, flag );
return;
#
def set_mag_mode( self, full_scale = '4gauss' ):
self.full_scale_dict \
= { '2gauss' : 0b00, \
'4gauss' : 0b01, \
'8gauss' : 0b10, \
'12gauss' : 0b11, \
};
full_scale_flag \
= self.full_scale_dict[ full_scale ] << 5;
self.full_scale_conv \
= { '2gauss' : 0.080, \
'4gauss' : 0.160, \
'8gauss' : 0.320, \
'12gauss' : 0.479, \
};
self.mag_conv = self.full_scale_conv[ full_scale ] \
* 0.001; # From mGauss to Gauss
flag = full_scale_flag;
self.write_reg( self.CTRL6, flag );
flag = 0b00000000;
self.write_reg( self.CTRL7, flag );
#
def get_acc( self ):
acc_x = self.read_reg( self.OUT_X_L_A ) \
* self.acc_conv - self.acc_dx;
acc_y = self.read_reg( self.OUT_Y_L_A ) \
* self.acc_conv - self.acc_dy;
acc_z = self.read_reg( self.OUT_Z_L_A ) \
* self.acc_conv - self.acc_dz;
return acc_x, acc_y, acc_z;
#
def get_mag( self ):
mag_x = self.read_reg( self.OUT_X_L_M ) \
* self.mag_conv;
mag_y = self.read_reg( self.OUT_Y_L_M ) \
* self.mag_conv;
mag_z = self.read_reg( self.OUT_Z_L_M ) \
* self.mag_conv;
return mag_x, mag_y, mag_z;
#
#######################################################
# Registers
##############################
TEMP_OUT_L = 0x05;
TEMP_OUT_H = 0x06;
STATUS_M = 0x07;
INT_CTRL_M = 0x12;
INT_SRC_M = 0x13;
INT_THS_L_M = 0x14;
INT_THS_H_M = 0x15;
OFFSET_X_L_M = 0x16;
OFFSET_X_H_M = 0x17;
OFFSET_Y_L_M = 0x18;
OFFSET_Y_H_M = 0x19;
OFFSET_Z_L_M = 0x1A;
OFFSET_Z_H_M = 0x1B;
REFERENCE_X = 0x1C;
REFERENCE_Y = 0x1D;
REFERENCE_Z = 0x1E;
CTRL0 = 0x1F;
CTRL1 = 0x20;
CTRL2 = 0x21;
CTRL3 = 0x22;
CTRL4 = 0x23;
CTRL5 = 0x24;
CTRL6 = 0x25;
CTRL7 = 0x26;
STATUS_A = 0x27;
OUT_X_L_A = 0x28;
OUT_X_H_A = 0x29;
OUT_Y_L_A = 0x2A;
OUT_Y_H_A = 0x2B;
OUT_Z_L_A = 0x2C;
OUT_Z_H_A = 0x2D;
OUT_X_L_M = 0x08;
OUT_X_H_M = 0x09;
OUT_Y_L_M = 0x0A;
OUT_Y_H_M = 0x0B;
OUT_Z_L_M = 0x0C;
OUT_Z_H_M = 0x0D;
FIFO_CTRL = 0x2E;
FIFO_SRC = 0x2F;
IG_CFG1 = 0x30;
IG_SRC1 = 0x31;
IG_THS1 = 0x32;
IG_DUR1 = 0x33;
IG_CFG2 = 0x34;
IG_SRC2 = 0x35;
IG_THS2 = 0x36;
IG_DUR2 = 0x37;
CLICK_CFG = 0x38;
CLICK_SRC = 0x39;
CLICK_THS = 0x3A;
TIME_LIMIT = 0x3B;
TIME_LATENCY = 0x3C;
TIME_WINDOW = 0x3D;
Act_THS = 0x3E;
Act_DUR = 0x3F;
WHO_AM_I = 0x0F;
#######################################################
#
|
UTF-8
|
Python
| false | false | 2,014 |
14,224,931,692,186 |
86f67cff5c3c4e941889f40578186ac14bb22a01
|
4104cea123d56d25e5bf52588691d682158ac2b5
|
/demo/demo.py
|
643168c63c03d4494edfaacd392268785898b16a
|
[] |
no_license
|
seckcoder/kikyo
|
https://github.com/seckcoder/kikyo
|
531825f084af81d2206bcd5b551ac4014224798d
|
0f9efbdffa5a19cc0cf8dc2fe8284062a046234b
|
refs/heads/master
| 2021-01-10T00:53:47.104508 | 2013-04-02T12:17:19 | 2013-04-02T12:17:19 | 9,115,898 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import kikyo
from kikyo import KQue
kikyo.monkey_patch(socket=True)
mykikyo = kikyo.Kikyo()
urgent_que = GroupQue(qkey="urgent", rate_limit="200/s")
kque1 = KQue(qkey="10.1.9.9", rate_limit="100/s")
kque2 = KQue(qkey="10.1.9.10", rate_limit="200/s")
urgent_que.add(kque1, kque2)
normal_que = GroupQue(qkey="normal", rate_limit="400/s")
normal_que.add(kque1, kque2)
mykikyo.addque(urget_que,, normal_que)
@mykikyo.async(qkey="urgent/10.1.9.9")
def foo(arg):
print "foo"
@mykikyo.async(rate_limit="xxx") # add a queue for this task type
def foo2(arg):
print "foo"
def bar(arg):
print "bar"
@mykikyo.beat()
def beat():
print "beat"
class Study(object):
@mykikyo.async
def foo(self):
pass
foo(link_value=bar,
link_exception=exception)
sdk.statuses_show = kikyo.async(sdk.statuses_show)
def handle_req(req):
def callback(results):
pass
sdk.statuses_show(link=callback, qkey="urgent/10.1.9.9;")
sdk.statuses_show(link=callback) # no qkey specified, use cycling
|
UTF-8
|
Python
| false | false | 2,013 |
14,078,902,814,899 |
152eab800a13a4bded9229741e940d5cf9422d96
|
69aa924acd15fc0b8bc8fbd255b15c8b0d2ebf18
|
/rowsite/row/urls.py
|
7d865835460fd910ae5cadc3d2ef614da1d2298a
|
[] |
no_license
|
eswalker/cos333
|
https://github.com/eswalker/cos333
|
a69847f374e6c2893871b0904d3c2e12b4b39f4d
|
ba668555bdbe1cacc1d6c110e1c8271dabfc8a86
|
refs/heads/master
| 2021-01-23T03:53:18.063374 | 2014-05-12T04:32:46 | 2014-05-12T04:32:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.conf.urls import patterns, url
from row import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^profile/$', views.my_profile, name='my_profile'),
url(r'^athletes/$', views.athlete_index, name='athlete_index'),
url(r'^athlete/(?P<athlete_id>\d+)/$', views.athlete_detail, name='athlete_detail'),
url(r'^athlete/(?P<athlete_id>\d+)/edit/$', views.athlete_edit, name='athlete_edit'),
url(r'^invites/$', views.invite_index, name='invite_index'),
url(r'^invite/add/$', views.invite_add, name='invite_add'),
url(r'^invite/(?P<id>\d+)/cancel/$', views.invite_cancel, name='invite_cancel'),
url(r'^invited/(?P<invite_key>\w+)/$', views.invited, name='invited'),
url(r'^weight/add/$', views.weight_add, name='weight_add'),
url(r'^athlete/(?P<athlete_id>\d+)/weight/add/$', views.weight_add, name='athlete_weight_add'),
url(r'^weight/(?P<id>\d+)/edit/$', views.weight_edit, name='weight_edit'),
url(r'^weight/(?P<id>\d+)/delete/$', views.weight_delete, name='weight_delete'),
#url(r'^practice/add/$', views.practice_add, name='practice_add'),
url(r'^practice/(?P<practice_id>\d+)/$', views.practice_detail, name='practice_detail'),
url(r'^practices/$', views.practice_index, name='practice_index'),
url(r'^practice/(?P<id>\d+)/edit/$', views.practice_edit, name='practice_edit'),
url(r'^practice/(?P<id>\d+)/delete/$', views.practice_delete, name='practice_delete'),
url(r'^practice/erg/add/$', views.practice_erg_add, name='practice_erg_add'),
url(r'^practice/water/add/$', views.practice_water_add, name='practice_water_add'),
#url(r'^result/add/$', views.result_add, name='result_add'),
url(r'^piece/(?P<piece_id>\d+)/result/add/$', views.result_add, name='piece_result_add'),
url(r'^practice/(?P<practice_id>\d+)/ergroom/$', views.practice_ergroom, name='practice_ergroom'),
url(r'^practice/(?P<practice_id>\d+)/ergroom/timed$', views.practice_ergroom_timed, name='practice_ergroom_timed'),
url(r'^practice/(?P<practice_id>\d+)/lineups/$', views.practice_lineups, name='practice_lineups'),
#url(r'^athlete/(?P<athlete_id>\d+)/result/add/$', views.result_add, name='athlete_result_add'),
url(r'^result/(?P<id>\d+)/edit/$', views.result_edit, name='result_edit'),
url(r'^result/(?P<id>\d+)/delete/$', views.result_delete, name='result_delete'),
url(r'^accounts/login/', views.user_login, name="login"),
url(r'^accounts/logout/', views.user_logout, name="logout"),
# From http://runnable.com/UqMu5Wsrl3YsAAfX/using-django-s-built-in-views-for-password-reset-for-python
# Map the 'app.hello.reset_confirm' view that wraps around built-in password
# reset confirmation view, to the password reset confirmation links.
url(r'^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.user_reset_confirm, name='reset_confirm'),
url(r'^accounts/reset/', views.user_password_reset, name="reset"),
url(r'^accounts/change/', views.user_password_change, name="password_change"),
url(r'^boats/$', views.boat_index, name='boat_index'),
url(r'^boat/add/$', views.boat_add, name='boat_add'),
url(r'^boat/(?P<id>\d+)/edit/$', views.boat_edit, name='boat_edit'),
url(r'^boat/(?P<id>\d+)/delete/$', views.boat_delete, name='boat_delete'),
#url(r'^lineup/add/$', views.lineup_add, name='lineup_add'),
#url(r'^piece/(?P<piece_id>\d+)/lineup/add/$', views.lineup_add, name='piece_lineup_add'),
#url(r'^lineup/(?P<id>\d+)/edit/$', views.lineup_edit, name='lineup_edit'),
url(r'^lineup/(?P<id>\d+)/delete/$', views.lineup_delete, name='lineup_delete'),
url(r'^erg', views.erg, name='erg'),
url(r'^denied/$', views.denied, name='denied'),
url(r'^json/athletes/$', views.json_athletes, name='json_athletes'),
url(r'^json/practices/$', views.json_practices, name='json_practices'),
url(r'^json/practice/recent$', views.json_recent_practice, name='json_recent_practice'),
url(r'^json/lineups/recent$', views.json_recent_lineups, name='json_recent_lineups'),
url(r'^json/lineup/athletes$', views.json_lineup_athletes, name='json_lineup_athletes'),
#url(r'^json/practice/(?P<id>\d+)/lineups/$', views.json_practice_lineups, name='json_practice_lineups'),
url(r'^json/boats/$', views.json_boats, name='json_boats'),
url(r'^json/login/$', views.json_login, name='json_login'),
url(r'^json/pieces/add$', views.json_pieces_add, name='json_pieces_add'),
url(r'^json/lineups/add$', views.json_lineups_add, name='json_lineups_add'),
url(r'^json/results/add$', views.json_results_add, name='json_results_add'),
url(r'^json/notes/add$', views.json_notes_add, name='json_notes_add'),
url(r'^athletes/csv/$', views.athlete_index_csv, name='athlete_index_csv'),
#url(r'^piece/add/$', views.piece_add, name='piece_add'),
#url(r'^practice/(?P<practice_id>\d+)/piece/add/$', views.piece_add, name='practice_piece_add'),
url(r'^piece/(?P<id>\d+)/edit/$', views.piece_edit, name='piece_edit'),
url(r'^piece/(?P<id>\d+)/delete/$', views.piece_delete, name='piece_delete'),
url(r'^piece/(?P<piece_id>\d+)/$', views.piece_detail, name='piece_detail'),
url(r'^piece/(?P<piece_id>\d+)/note/add/$', views.note_add, name='piece_note_add'),
url(r'^practice/(?P<practice_id>\d+)/note/add/$', views.note_add, name='practice_note_add'),
url(r'^note/(?P<id>\d+)/delete/$', views.note_delete, name='note_delete'),
url(r'^note/(?P<id>\d+)/edit/$', views.note_edit, name='note_edit'),
)
|
UTF-8
|
Python
| false | false | 2,014 |
17,746,804,901,657 |
04716b631380cf7f6fb7cf37d7699499be5a736f
|
783b81c7939e7db4d8178fbbec7a3da217f97fa4
|
/core/app/brushresizer.py
|
8e501bc03cab5b8909543ee1ab288b918a408a17
|
[
"GPL-3.0-only"
] |
non_permissive
|
nuigroup/nuipaint
|
https://github.com/nuigroup/nuipaint
|
ba1bfb2f73949b6fc918c5e08b5a9af63d06a752
|
2fd9cd798085c65ed94465aef303f93b2d8fbf4c
|
refs/heads/master
| 2016-09-05T20:20:49.744147 | 2009-08-26T09:38:18 | 2009-08-26T09:38:18 | 8,322,695 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from __future__ import with_statement
from pymt import *
from pyglet.gl import *
from core.app.observer import *
class MTBrushResizer(MTWidget):
def __init__(self, **kwargs):
kwargs.setdefault('canvas', None)
super(MTBrushResizer, self).__init__(**kwargs)
self.canvas = Observer.get('canvas')
self.bound = MTStencilContainer(size=self.size,pos=self.pos)
self.add_widget(self.bound)
self.brush_image = MTScatterImage(pos=self.pos,filename="brushes/brush_particle.png",do_translation=False,do_rotation=False,scale_min=0.1)
self.bound.add_widget(self.brush_image)
self.current_brush = "brushes/brush_particle.png"
self.original_brush_size = 64
self.current_brush_size = 64
def on_touch_down(self,touch):
if self.collide_point(touch.x,touch.y):
touch.grab(self)
self.brush_image.on_touch_down(touch)
return True
def on_touch_move(self,touch):
if self.collide_point(touch.x,touch.y) and touch.grab_current == self:
self.brush_image.on_touch_move(touch)
self.brush_image.do_translation = True
self.brush_image.center = (self.bound.width/2,self.bound.height/2)
self.brush_image.do_translation = False
brush_scale = self.brush_image.get_scale_factor()
self.current_brush_size = int(self.original_brush_size * brush_scale)
Observer.get('canvas').set_brush(sprite=self.current_brush,size=self.current_brush_size)
return True
def set_brush(self,brush_image,brush_size):
self.bound.remove_widget(self.brush_image)
self.brush_image = MTScatterImage(filename=brush_image,do_translation=False,do_rotation=False,scale_min=0.1)
self.current_brush = brush_image
self.bound.add_widget(self.brush_image)
Observer.get('canvas').set_brush(sprite=brush_image,size=brush_size)
self.current_brush_size = self.original_brush_size
Observer.register('current_brush_size',self.current_brush_size)
|
UTF-8
|
Python
| false | false | 2,009 |
12,086,038,012,135 |
7501b063d14c1011333e8c166f90b29c3bc96129
|
248c907490779d5e8ec516a99f65dd8ec1346801
|
/test_compliance.py
|
034fa915e14b81a0f8d687119354220ff74beff6
|
[] |
no_license
|
miebach/pydertron
|
https://github.com/miebach/pydertron
|
7a06b5f0df5a2a1295a4e5cb6abe11bb45eacc87
|
d44a8ce637a3e570b9ef40df4b4a23b2a5a33289
|
refs/heads/master
| 2020-04-05T22:50:16.816238 | 2009-09-25T13:36:53 | 2009-09-25T13:36:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Pydertron.
#
# The Initial Developer of the Original Code is Mozilla.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Atul Varma <atul@mozilla.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""
CommonJS SecurableModule standard compliance tests for Pydertron.
"""
import os
import sys
import pydermonkey
from pydertron import JsSandbox, jsexposed
from pydertron import LocalFileSystem, HttpFileSystem
def run_test(name, fs):
sandbox = JsSandbox(fs)
stats = {'pass': 0, 'fail': 0, 'info': 0}
@jsexposed(name='print')
def jsprint(message, label):
stats[label] += 1
print "%s %s" % (message, label)
sandbox.set_globals(
sys = sandbox.new_object(**{'print': jsprint}),
environment = sandbox.new_object()
)
retval = sandbox.run_script("require('program')")
sandbox.finish()
print
if retval != 0:
stats['fail'] += 1
return stats
if __name__ == '__main__':
base_libpath = os.path.join("interoperablejs-read-only",
"compliance")
if len(sys.argv) == 2 and sys.argv[1] == '--with-http':
with_http = True
else:
with_http = False
if not os.path.exists(base_libpath) and not with_http:
print "Please run the following command and then re-run "
print "this script:"
print
print ("svn checkout "
"http://interoperablejs.googlecode.com/svn/trunk/ "
"interoperablejs-read-only")
print
print "Alternatively, run this script with the '--with-http' "
print "option to run the tests over http."
sys.exit(1)
BASE_URL = "http://interoperablejs.googlecode.com/svn/trunk/compliance/"
if with_http:
names = ['absolute', 'cyclic', 'determinism', 'exactExports',
'hasOwnProperty', 'method', 'missing', 'monkeys',
'nested', 'reflexive', 'relative', 'transitive']
dirs = [("%s%s/"% (BASE_URL, name), name)
for name in names]
fsfactory = HttpFileSystem
else:
dirs = [(os.path.join(base_libpath, name), name)
for name in os.listdir(base_libpath)
if name not in ['.svn', 'ORACLE']]
fsfactory = LocalFileSystem
totals = {'pass': 0, 'fail': 0}
for libpath, name in dirs:
fs = fsfactory(libpath)
stats = run_test(name, fs)
totals['pass'] += stats['pass']
totals['fail'] += stats['fail']
print "passed: %(pass)d failed: %(fail)d" % totals
import gc
gc.collect()
if pydermonkey.get_debug_info()['runtime_count']:
sys.stderr.write("WARNING: JS runtime was not destroyed.\n")
sys.exit(totals['fail'])
|
UTF-8
|
Python
| false | false | 2,009 |
13,383,118,098,873 |
9f68ed061c1655e5df7c7ad9486c495febdb1325
|
6f7cd4b20bee27d4320f70333132f3ae39942771
|
/scripts/missing_images_scraper.py
|
7a1b3f8ef1aa3a23d54f87feaece9400c6f82817
|
[] |
no_license
|
larsendt/mtg-organizer
|
https://github.com/larsendt/mtg-organizer
|
adc6928ca5f72f62e9df905907643095102834c7
|
ee69a08d4e973d8f36cff894d29b427a328d7d51
|
refs/heads/master
| 2021-01-20T11:31:10.766542 | 2014-01-24T22:03:31 | 2014-01-24T22:03:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import sqlite3
import os
DB_FILE = "../data/cards.sqlite"
B = "../static_web/i/cards/"
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute("SELECT name, printing, multiverseid FROM reference_cards")
data = c.fetchall()
for (name, printing, i) in data:
if not os.path.exists(os.path.join(B, i+".jpg")):
print "No image for %s : %s : %s" % (name, printing, i)
|
UTF-8
|
Python
| false | false | 2,014 |
14,731,737,875,082 |
3c4ebea440914ae58432acd68f991c9100552600
|
c940dc48e25a809fad0a9ef495b74c988b4a1c25
|
/002.py
|
d69bd1af8ffadabc8a63afaf514509a298185e68
|
[] |
no_license
|
jg-martinez/projectEuler
|
https://github.com/jg-martinez/projectEuler
|
39c1cd7973e8a75c31c6235b73a008d58da2c4ac
|
13bb46f006201dabb3ba7625dd2223190180439a
|
refs/heads/master
| 2021-01-20T11:05:51.021545 | 2014-08-31T16:21:35 | 2014-08-31T16:21:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
Project Euler Problem 2
=======================
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
"""
def solve(num):
result = 0
max = 2
min = 1
aux = 0
count = 0
while (max < num):
if (max % 2 == 0):
result += max
aux = max
max = max + min
min = aux
return result
if __name__=="__main__":
print(solve(4000000))
|
UTF-8
|
Python
| false | false | 2,014 |
2,800,318,705,080 |
bfa2cde55f7d27e58b1cf6895b028224b5a3f7aa
|
73949e08b48d5a677fcf00e54b2032f0380130f0
|
/RG.py
|
fff867ed3fb0f9a204ebb1059c152f67d31fad5b
|
[] |
no_license
|
obbele/rg2010
|
https://github.com/obbele/rg2010
|
6bf1e613590ccd4567e2638e50adc118d344176e
|
d94597303b71d2582365e9aa74e7a9a1144fe535
|
refs/heads/master
| 2016-09-03T07:28:28.665525 | 2010-05-28T15:57:28 | 2010-05-28T15:57:28 | 691,279 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
# Copyright 2010 John Obbele <john.obbele@gmail.com>
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# Version 2, December 2004
#
# Copyright (C) 2004
# Sam Hocevar 14 rue de Plaisance, 75014 Paris, France
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long as
# the name is changed.
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
=== Python Player for Roland-Garos ===
- retrieve JSON and extract from it the list of mms flux
- parse website mainpage and extract from it the list of current matches
- provide a CLI interface as a proof of concept (see cli())
- provide a PyGTK interface for lazy men (see class MainWindow)
The function LAUNCH_EXTERNAL_PLAYER (url) try to guess your preferred
video player for mms/wmv flux, if it's not working, you will have to
hack it yourself.
"""
import json
import urllib, BeautifulSoup
import os, os.path
OFFLINE=False
def LAUNCH_EXTERNAL_PLAYER( url):
""" FIXME: hack your video player here ! """
print "Processing:", url
if OFFLINE : return
if os.path.exists( "/usr/bin/mplayer" ):
bin = "/usr/bin/mplayer"
elif os.path.exists( "/usr/bin/parole" ):
bin = "/usr/bin/parole"
elif os.path.exists( "/usr/bin/dragon" ):
bin = "/usr/bin/dragon"
elif os.path.exists( "/usr/bin/totem" ):
bin = "/usr/bin/totem"
os.spawnlp(os.P_NOWAIT, bin, bin, url)
if OFFLINE :
HOME_PAGE="page_blank.html"
TOKEN="token.txt"
WMV_JSON="wmv.json"
else :
HOME_PAGE="http://roland-garros.sport.francetv.fr/video-direct"
TOKEN="http://roland-garros.sport.francetv.fr/appftv/akamai/token/gentoken1.php?flux=roland_%s_%s"
WMV_JSON="http://roland-garros.sport.francetv.fr/sites/www.sport/themes/roland-garros/php/direct/getListVideo.php?player=WMV"
# javascript file describing managing the authentication process
# keep this for reference
JSOURCE="http://roland-garros.sport.francetv.fr/sites/sport.francetv.fr/themes/roland-garros/js/direct-min.js"
def _wget(url) :
""" get data from an url and return raw text """
response = urllib.urlopen(url)
return response.read()
class Crawler():
""" Using BeautifulSoup, parse the HTML page
and map idFlux versus match information
You can retrieve current information throught self.matches
You can refresh the match list with self.refresh()
"""
def __init__(self):
self.refresh()
def refresh(self) :
""" Refresh the dictionary 'matchID' => match
"""
self.matches = {}
data = _wget(HOME_PAGE)
soup = BeautifulSoup.BeautifulSoup(data)
for div in soup.findAll("div", {"class":"JeuParJeu"}) :
try :
id,match = self._parseMatch( div)
self.matches[id] = match
except AttributeError:
pass
#print "Error when parsing", div
def _parseMatch(self, div) :
"""
<div class="JeuParJeu" id="match3">
<h3>Court 1</h3>
<p class="duree">Durée 1h20</p>
<div class="equipe1"> <img
src="http://medias.francetv.fr/STATIC/salma/images/flag/png/GBR.png"
class="png" alt="" border="0" /> A.MURRAY (4)</div>
<div class="equipe2"> <img
src="http://medias.francetv.fr/STATIC/salma/images/flag/png/ARG.png"
class="png" alt="" border="0" /> J.CHELA</div>
<div class="equipe1-balle"></div>
<div class="equipe2-balle"><img
src="/sites/www.sport/themes/roland-garros/img/balle.png" class="png"
alt="" border="0" /></div>
<div class="equipe1-score"><span>6</span> 3 </div>
<div class="equipe2-score">2 3 </div>
<a href="?idFlux=3"><span>Voir le match</span></a>
</div>
"""
match = {}
match['name'] = div.attrMap['id']
equipe1 = []
for p in div.findAll("div", {"class":"equipe1"}) :
equipe1 += p.text
match['players1'] = "".join(equipe1)
equipe2 = []
for p in div.findAll("div", {"class":"equipe2"}) :
equipe2 += p.text
match['players2'] = "".join(equipe2)
score1 = div.find("div" , {"class":"equipe1-score"})
match['score1'] = score1.text.replace(" ", "")
score2 = div.find("div" , {"class":"equipe2-score"})
match['score2'] = score2.text.replace(" ", "")
idFlux = div.find('a').attrs[0][1]
idFlux = idFlux[len('?idFlux='):] # strip '?idFlux='
return idFlux, match
class AkamaiPlayer():
""" Retrieve the list of WMVs flux
and manage authentication tokens
You can retrieve information throught self.list() or self.videos
You can retrieve refresh the list with self.refresh()
"""
def __init__(self, quality="SQ"):
self.changeQuality(quality)
self.refresh()
def changeQuality(self, quality):
if quality == "SQ" or quality == "HQ" :
self.quality = quality
else :
raise Exception("quality should be either 'SQ' or 'HQ'")
def get(self, id):
""" Given video ID, return its url,
including authentication token
"""
id = str(id) # force str object
identifier = id + "_" + self.quality
try :
return self._akamaiToken( self.videos[identifier]
, id
, self.quality)
except KeyError:
print "Error: unknown key"
print " available videos: ", ", ".join(self.videos.keys())
def list(self):
""" Return the list of available videos """
keys = self.videos.keys()
for i,k in enumerate(keys):
keys[i] = k[0:-3] # skip last 3 chars ("_{S,H}Q")
return keys
def refresh(self):
""" Return a dictionary similar to js's itemListSL
each element is a simple association "flux" -> "url"
where flux looks like "1_HQ"
"""
raw_data = _wget(WMV_JSON)
data = json.loads( raw_data)
itemListSL = {}
for e in data['videos'] :
if e['url_HQ'] == "smooth" :
raise NotImplementedError
else :
id = e['idMatch']
itemListSL[id + "_SQ"] = e['url_SQ']
itemListSL[id + "_HQ"] = e['url_HQ']
self.videos = itemListSL
""" JAVASCRIPT decypher
function decryptToken(a) {
return (a + "").replace(/[A-Za-z]/g, function (b) {
return String.fromCharCode((((b = b.charCodeAt(0)) & 223) - 52) % 26 + (b & 32) + 65)
})
}
"""
def _decryptToken(self, id):
l = list(id)
for i,k in enumerate(l) :
if k.isalpha() :
b = ord(k)
l[i] = chr(((b & 223) - 52) % 26 + (b & 32) + 65)
return "".join(l)
""" JAVASCRIPT token
function isActiveToken(a) {
return /\?aifp=/i.test(a)
}
function akamaiToken(e, b, d) {
var a = isActiveToken(e);
if (a) {
if (b == "8") {
b = "6"
}
if (b == "9") {
b = "7"
}
var c = $.ajax({
url: "/appftv/akamai/token/gentoken1.php?flux=roland_" + b + "_" + d,
async: false
}).responseText;
c = decryptToken(c);
e = e + "&auth=" + c
}
return e
}
...
akamaiToken(b.src, idMatch, qualityDirect)
where b.src = "mms://.../e_rg_2010_7l.wsx?aifp=v052"
idMath = 1 | 2 | 3 | ...
qualityDirect = "SQ" | "HQ"
"""
def _akamaiToken(self, url, id, quality):
e,b,d = url, id, quality
#FIXME: check if the token is active
if (b == "8") :
b = "6"
if (b == "9") :
b = "7"
if OFFLINE : raw_hash = _wget( TOKEN )
else : raw_hash = _wget( TOKEN % (id, quality) )
c = decrypted_hash = self._decryptToken(raw_hash)
return e + "&auth=" + c
def _create_asx(self):
""" WARNING: function not working
Should properly encode XML entities ('&' => '&')
USE AT YOUR OWN RISKS
"""
raise NotImplementedError
head = """<ASX VERSION = \"3.0\">
<TITLE>Title</TITLE>
"""
tail = "</ASX>"
ENTRY = """
<ENTRY>
<TITLE>%s</TITLE>
<REF HREF = \"%s\" />
</ENTRY>
"""
r = head
for identifierk,url in self.videos.iteritems() :
id = identifierk[0]
quality = identifierk[-2:]
try :
url = akamaiToken(url, id, quality)
r += ENTRY % (identifierk, url)
except :
print "Error: ignoring", url
r += tail
return r
class LOLO():
""" Tie a crawler and a player together
"""
def __init__(self,quality="SQ"):
self.crawler = Crawler()
self.player = AkamaiPlayer(quality)
self.list = self.crawler.matches
def refresh(self):
""" Refresh both the player and the crawler component
"""
self.crawler.refresh()
self.player.refresh()
def get(self, id):
""" Given a flux ID, return the URL,
including a authentication token
"""
return self.player.get(id)
def __str__(self):
""" Internal function invoked when calling "print"
"""
s = ""
for i,v in self.crawler.matches.iteritems() :
s += "Id:" + i + "\n"
s += "\tjoueur(s) 1: " + v['players1'] + "\n"
s += "\tjoueur(s) 2: " + v['players2'] + "\n"
s += "\t" + v['score1'] + "\n"
s += "\t" + v['score2'] + "\n"
s += "\n"
return s
def cli():
""" A simple Read-eval-print loop (REPL) for selecting a match
and launching the video player.
"""
print "Testing flying dog"
print "quality ?(SQ|HQ)"
q = raw_input()
client = LOLO(q)
print "available matches:"
print client
end = False
while not end :
print "choice ? (q=exit, r=refresh, x=play match number x)"
r = raw_input()
if r == "q" :
end = True
elif r == "r" :
client.refresh()
print client
continue
else :
url = client.get(r)
LAUNCH_EXTERNAL_PLAYER( url)
###
### GTK stuff
###
import pygtk
pygtk.require('2.0')
import gtk
class MainWindow(LOLO):
"""Adapted from the PyGTK tutorial, chapter 2
"""
def __init__(self,quality="HQ"):
LOLO.__init__(self, quality)
self._init_gtk()
self.refresh()
def refresh(self):
LOLO.refresh(self)
self._refresh_list_store()
def _refresh_list_store(self) :
self.liststore.clear()
for id,match in self.crawler.matches.iteritems():
score = match['score1'] + "\n" + match['score2']
players = match['players1'] + "\n" + match['players2']
self.liststore.append( [int(id), score, players ])
self.liststore.set_sort_column_id( 0, gtk.SORT_ASCENDING)
def _init_gtk(self):
"""Create the GTK widgets
"""
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title('Roland Garros 2010')
window.set_size_request(300, 400)
window.show()
window.connect('delete_event', self.quit)
window.set_border_width(10)
vbox = gtk.VBox()
window.add( vbox)
label = gtk.Label("¡ Pirater TUE des chatons !")
vbox.pack_start( label, expand=False, fill=False)
liststore = gtk.ListStore(int,str,str)
listview = gtk.TreeView( liststore)
vbox.pack_start( listview)
#Creating ID column
#
column = gtk.TreeViewColumn('ID')
listview.append_column( column)
cell = gtk.CellRendererText()
column.pack_start( cell, True)
column.add_attribute( cell, 'text', 0)
column.set_sort_column_id(0)
listview.set_search_column( 0)
#Creating score column
#
column = gtk.TreeViewColumn('Score')
listview.append_column( column)
cell = gtk.CellRendererText()
column.pack_start( cell, True)
column.add_attribute( cell, 'text', 1)
#Creating players column
#
column = gtk.TreeViewColumn('Joueurs')
listview.append_column( column)
cell = gtk.CellRendererText()
column.pack_start( cell, True)
column.add_attribute( cell, 'text', 2)
#Qualitay box
qualitystore = gtk.ListStore(str)
combobox = gtk.ComboBox(qualitystore)
cell = gtk.CellRendererText()
cell.set_property( 'xalign', 0.5)
combobox.pack_start(cell, True)
combobox.add_attribute(cell, 'text', 0)
combobox.append_text("SQ")
combobox.append_text("HQ")
if self.player.quality == "SQ" :
combobox.set_active(0)
else :
combobox.set_active(1)
def on_quality_box__changed( combobox):
model = combobox.get_model()
active = combobox.get_active()
if active < 0 : return
value = model[active][0]
self.player.changeQuality( value)
combobox.connect( "changed", on_quality_box__changed)
vbox.pack_start( combobox, expand=False, fill=False)
#Buttonbox
buttonbox = gtk.HBox()
vbox.pack_end( buttonbox, expand=False, fill=True)
button = gtk.Button("_Refresh", gtk.STOCK_REFRESH)
def on_refresh__clicked( button) :
self.refresh()
button.connect( "clicked", on_refresh__clicked)
buttonbox.pack_start( button, expand=True, fill=True)
button = gtk.Button("_Quit", gtk.STOCK_QUIT)
button.connect( "clicked", self.quit)
buttonbox.pack_start( button, expand=True, fill=True)
def on_listview__row_activated(tv, path, view_column=None) :
""" Trigger when a row is doubled-clicked or
Ctrl+Space is pressed
"""
iter = liststore.get_iter( path)
id = liststore.get_value( iter, 0)
url = self.get( id)
LAUNCH_EXTERNAL_PLAYER( url)
listview.connect( "row-activated", on_listview__row_activated)
window.show_all()
#Keep at hand
self.liststore = liststore
def quit(self, widget, data=None):
""" End GTK main loop
and thus terminate the program
"""
print "ByeBye !"
gtk.main_quit()
def launch_gtk():
""" Guess it ?
"""
widget = MainWindow()
gtk.main()
if __name__ == '__main__':
#cli()
launch_gtk()
# vim:textwidth=72:
|
UTF-8
|
Python
| false | false | 2,010 |
12,214,887,032,565 |
c7c3f6cc34f4f7e2d66d3181d0cdcbd1d91ca4a0
|
2ad9b0245ae49ee62bf9058cff3e4bd5cd8f5a8c
|
/algorithm/__init__.py
|
f725f60f75cd40a46c517e303086baee5b5d4e13
|
[] |
no_license
|
hbradlow/pygeom
|
https://github.com/hbradlow/pygeom
|
7918904b837da45baac2b5289b976eca9424c7b6
|
8bc5a7e871b4acb23aa6c1eaf8bfefe85e6c7d3d
|
refs/heads/master
| 2021-01-22T09:47:56.097964 | 2013-02-02T11:53:02 | 2013-02-02T11:53:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
def lexicographic_sort(points):
indices = np.lexsort(zip(*points))
return [points[i] for i in indices]
|
UTF-8
|
Python
| false | false | 2,013 |
1,554,778,192,223 |
80d2305546840e2064f58ea3f9a6f5635925dab4
|
ab179a8b20a90bdad1d8e172368ccdbf793a2c14
|
/splitted. browse into xbian-* repositories for sources/xbian/.xbmc/addons/plugin.xbianconfig/resources/lib/xbianWindow.py
|
fc8e21a9116d3ea52933be75d7a8e197a7173e1f
|
[
"GPL-3.0-only",
"Linux-syscall-note",
"GPL-2.0-only",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown"
] |
non_permissive
|
mpoulter/xbian
|
https://github.com/mpoulter/xbian
|
0497e05be8fea8272aa41136ec226fee24103066
|
2188c60bf7b8ee8846662dcd43113a6cfc842ade
|
HEAD
| 2019-04-14T11:56:46.714627 | 2014-04-02T18:56:08 | 2014-04-02T18:56:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os,sys
from xbmcguie.window import WindowSkinXml
import xbmcgui
import threading
class XbianWindow(WindowSkinXml):
def __init__(self,strXMLname, strFallbackPath, strDefaultName=False, forceFallback=False) :
WindowSkinXml.__init__(self,strXMLname, strFallbackPath, strDefaultName=False, forceFallback=False)
self.categories = []
self.publicMethod = {}
self.stopRequested = False
def onInit(self):
WindowSkinXml.onInit(self)
#first, get all public method
for category in self.categories :
self.publicMethod[category.getTitle()] = {}
for setting in category.getSettings():
public = setting.getPublicMethod()
for key in public :
self.publicMethod[category.getTitle()][key] = public[key]
#set the windows instance in all xbmc control
for category in self.categories :
if self.stopRequested :
break
initthread = threading.Thread(None,self.onInitThread, None, (category,))
initthread.start()
def onInitThread(self,category):
#set default value to gui
for setting in category.getSettings():
if self.stopRequested :
break
try :
setting.updateFromXbian()
setting.setPublicMethod(self.publicMethod)
except :
#don't enable control if error
print 'Exception in updateFromXbian for setting'
print sys.exc_info()
else :
setting.getControl().setEnabled(True)
def addCategory(self,category):
self.categories.append(category)
self.addControl(category.getCategory())
def doXml(self,template) :
xmltemplate = open(template)
xmlout = open(self.xmlfile,'w')
for line in xmltemplate.readlines() :
if '<control type="xbian" value="Menucategories"/>' in line :
for category in self.categories :
xmlout.write(category.getTitleContent().toXml())
elif '<control type="xbian" value="categories"/>' in line :
for category in self.categories :
xmlout.write(category.getCategory().toXml())
#xmlout.write(category.getScrollBar().toXml())
else :
xmlout.write(line)
xmltemplate.close()
xmlout.close()
|
UTF-8
|
Python
| false | false | 2,014 |
5,952,824,686,989 |
9df10a4762c24cb68e080aa0fa9078ee856156aa
|
d728828374c0e719dda4da99408906eea5d169a2
|
/DragAndDrop/Trigger.py
|
1ab94b1c3b1350eb7e18c4daa2a660c1882030c8
|
[] |
no_license
|
TradeUp/Demo
|
https://github.com/TradeUp/Demo
|
845cabd4cc590903a3166a6f25a0882a9cac8e4f
|
69ee77c4778fdeb06577b2f3778bb1ac8c26e6ce
|
refs/heads/master
| 2016-09-06T16:01:43.479499 | 2012-06-30T03:08:27 | 2012-06-30T03:08:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
Created on Apr 21, 2012
@author: Paavan
'''
import PySide
import sys
from PySide import QtCore
from PySide import QtGui
import Function
from backend import *
from FunctionSelector import *
import string
class TriggerWidget(QtGui.QFrame):
request_selection = QtCore.Signal(object);
request_removal = QtCore.Signal(object);
def __init__(self, parent):
super(TriggerWidget, self).__init__(parent);
self._layout = QtGui.QVBoxLayout(self);
self._mainTriggerLayout = QtGui.QHBoxLayout();
btnRemove = QtGui.QPushButton("-")
btnRemove.clicked.connect(self.removeRow);
btnRemove.setMaximumWidth(20)
self.setStyleSheet("QFrame { color: #fff; border-radius: 5px; border: 1px solid #777; background: #ccc; }")
self.leftTarget = FunctionDropTarget()
self.leftTarget.request_selection.connect(self.selectionRequested)
self.leftTarget.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter)
self.leftTarget.setStyleSheet("QLabel { padding-top:5px; background-color: #eee; border-radius: 5px; color: #555; border: 1px solid #777 }")
self.leftTarget.setText('this is')
self.rightTarget = FunctionDropTarget()
self.rightTarget.request_selection.connect(self.selectionRequested)
self.rightTarget.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter)
self.rightTarget.setStyleSheet("QLabel { padding-top:5px; background-color: #eee; border-radius: 5px; color: #555; border: 1px solid #777 }")
self.rightTarget.setText('that')
self.combobox = ComparisonComboBox(self);
self._mainTriggerLayout.addWidget(btnRemove,1);
self._mainTriggerLayout.addWidget(self.leftTarget,5);
self._mainTriggerLayout.addWidget(self.combobox,1);
self._mainTriggerLayout.addWidget(self.rightTarget,5);
self._layout.addLayout(self._mainTriggerLayout);
self.setLayout(self._layout);
self.setAcceptDrops(True);
"""
Convert this trigger into a recipe row object.
Returns None if invalid row.
"""
def getRecipeRow(self):
#If one of the functions are None or the units don't match, return None
error = False
print 'getting recipe row'
print 'checking left'
if(not self.leftTarget.validate()):
self.setInvalid(self.leftTarget)
error = True
print 'checking right'
if not self.rightTarget.validate():
self.setInvalid(self.rightTarget)
error = True
print 'checking units'
if not error and self.leftTarget.function().getUnits() != self.rightTarget.function().getUnits():
self.setInvalid(self);
error = True
print 'error exists? ' + str(error)
if error: return None
exprLeft = self.leftTarget.function().getExpression()
exprRight = self.rightTarget.function().getExpression()
comparison = self.combobox.currentText()
return RecipeRow(exprLeft, exprRight, comparison);
"""
Set this triggerwidget to match the RecipeRow object passed in
"""
def setRecipeRow(self, row):
leftFunction = Function.Function.inflateFunction(row.expr_a)
rightFunction = Function.Function.inflateFunction(row.expr_b)
comparator = row.operator
self.leftTarget.setFunction(leftFunction)
self.leftTarget.setText(FunctionScrollWidget.getDisplayNameForFunction(row.expr_a.funcName))
self.rightTarget.setFunction(rightFunction)
self.rightTarget.setText(FunctionScrollWidget.getDisplayNameForFunction(row.expr_b.funcName))
self.combobox.setSelected(comparator)
"""
Mark as invalid: make red
"""
def setInvalid(self, target):
target.setStyleSheet("background-color:#FF0000;");
"""Connected to request_selection signal of FunctionDropTarget class"""
@QtCore.Slot(object)
def selectionRequested(self, e):
#undo marking invalid
# self.setStyleSheet("border-radius: 5px; border: 1px solid #000");
# self.leftTarget.setStyleSheet("border-radius: 5px; border: 1px solid #000")
# self.rightTarget.setStyleSheet("border-radius: 5px; border: 1px solid #000")
e._target = self;
self.request_selection.emit(e);
def deselect(self):
self.leftTarget.deselect();
self.rightTarget.deselect();
"""
Send the removal request
"""
@QtCore.Slot(object)
def removeRow(self):
self.request_removal.emit(self)
class FunctionDropTarget(QtGui.QLabel):
#Create a signal to tell the parent that this function target is requesting selection
request_selection = QtCore.Signal(object);
def __init__(self, text="None"):
super(FunctionDropTarget, self).__init__(text);
self.setAcceptDrops(True);
#at first, this target does not represent a function
self.func = None
palette = self.palette()
palette.setColor(QtGui.QPalette.ColorRole.Highlight, QtGui.QColor(0,0,255));
self.setPalette(palette);
self.setAutoFillBackground(True);
def validate(self):
print 'validating func' + str(self.function())
if(self.function() == None or not self.function().isValid()):
return False
return True
def function(self):
return self.func;
def setFunction(self, func):
self.func = func
def dragEnterEvent(self, e):
print "DRAG ENTER"
e.accept();
def dragLeaveEvent(self, e):
print "DRAG LEAVE"
e.accept();
def dropEvent(self, e):
print "DROPPED"
#parse the data into a function object
if e.mimeData().hasFormat('text/plain'):
tokens = e.mimeData().text().split('/');
self.setText(tokens[0])
self.func = Function.Function.getFunction(tokens[1])
#send the request selection signal
self.request_selection.emit(FunctionSelectionEvent(self, self.func, self.onSelected));
e.setDropAction(QtCore.Qt.CopyAction);
e.accept()
else:
e.ignore()
def mousePressEvent(self, e):
if e.button() == QtCore.Qt.LeftButton:
self.request_selection.emit(FunctionSelectionEvent(self, self.func, self.onSelected));
def onSelected(self):
self.setBackgroundRole(QtGui.QPalette.ColorRole.Highlight);
def deselect(self):
self.setBackgroundRole(QtGui.QPalette.ColorRole.Base);
class FunctionSelectionEvent():
"""
Take the object requesting selection, and the function to call should this event be accepted
"""
def __init__(self, target, function, onAccept):
self._target = target;
self._func = function;
self._onAccept = onAccept;
def accept(self):
self._onAccept();
def ignore(self):
pass
def target(self):
return self._target;
def function(self):
return self._func;
class ActionTrigger(QtGui.QFrame):
def __init__(self, parent):
super(ActionTrigger, self).__init__(parent)
self.setStyleSheet("QFrame { color: #fff; border-radius: 5px; border: 1px solid #777; background: #ccc; }")
self._layout = QtGui.QHBoxLayout(self);
self._cmbAction = ActionComboBox(self)
self._cmbUnits = UnitComboBox(self)
self._txtAmount = QtGui.QLineEdit(self)
self._txtAmount.textChanged.connect(self.resetTextAmount)
self._txtStock = QtGui.QLineEdit(self)
self._txtStock.textChanged.connect(self.resetTextStock)
lblOf = QtGui.QLabel("of", self)
lblOf.setMaximumWidth(25)
self._layout.addWidget(self._cmbAction, 1)
self._layout.addWidget(self._txtAmount, 2)
self._layout.addWidget(self._cmbUnits, 1)
self._layout.addWidget(lblOf, 1)
self._layout.addWidget(self._txtStock, 2)
self.setLayout(self._layout);
self.setMaximumHeight(43);
"""
Convert this trigger into a trigger function
"""
def convertToTriggerFunc(self):
ticker = self._txtStock.text()
amount = self._txtAmount.text()
unit = self._cmbUnits.getType()
onCall = self._cmbAction.getOnCallFunction()
return Trigger(ticker, amount, unit, onCall)
"""
Convert a trigger function into this trigger object
"""
def inflateTriggerFunction(self, func):
self._txtAmount.setText(str(func.amount));
self._txtStock.setText(func.ticker)
self._cmbAction.setSelected(func.amount_type)
if(func.funcName == "buy_stock"):
self._cmbAction.setSelected("buy")
elif func.funcName == "sell_stock":
self._cmbAction.setSelected("sell")
elif func.funcName == "sell_short":
self._cmbAction.setSelected("sell short")
"""
Validate this trigger
"""
def validate(self, controller):
valid = True
try:
if int(self._txtAmount.text()) < 0: raise ValueError()
except ValueError:
self._txtAmount.setStyleSheet("background-color:#FF0000; border-radius: 5px; border: 1px solid #f33;")
valid = False
if not controller.validate_ticker(self._txtStock.text()):
self._txtStock.setStyleSheet("background-color:#FF0000; border-radius: 5px; border: 1px solid #f33;");
valid = False
return valid
@QtCore.Slot()
def resetTextStock(self):
self._txtStock.setStyleSheet("border-radius: 5px; background: #fff; color: #444;");
@QtCore.Slot()
def resetTextAmount(self):
self._txtAmount.setStyleSheet("border-radius: 5px; background: #fff; color:#444");
class ActionComboBox(QtGui.QComboBox):
def __init__(self, parent):
super(ActionComboBox, self).__init__(parent);
"""TODO: implement generic Comparator class, compare two objects of some type """
self.addItem("Buy")
self.addItem("Sell")
self.addItem("Sell short")
def getOnCallFunction(self):
if self.currentText() == "Buy": return "buy_stock"
elif self.currentText() == "Sell": return "sell_stock"
else:
return "sell_short"
"""
Set the specified action as selected
"""
def setSelected(self, action):
if string.lower(action) == "buy":
self.setCurrentIndex(0)
elif string.lower(action) == "sell":
self.setCurrentIndex(1)
elif string.lower(action) == "sell short":
self.setCurrentIndex(2)
class UnitComboBox(QtGui.QComboBox):
def __init__(self, parent):
super(UnitComboBox, self).__init__(parent);
"""TODO: implement generic Comparator class, compare two objects of some type """
self.addItem("Shares")
self.addItem("Dollars")
def getType(self):
if self.currentText() == "Shares": return 'SHARES'
else: return 'DOLLARS'
def setSelected(self, unit):
if string.lower(unit) == "shares":
self.setCurrentIndex(0)
elif string.lower(unit) == "dollars":
self.setCurrentIndex(1)
class ComparisonComboBox(QtGui.QComboBox):
def __init__(self, parent):
super(ComparisonComboBox, self).__init__(parent);
"""TODO: implement generic Comparator class, compare two objects of some type """
self.addItem("<")
self.addItem("<=")
self.addItem("=")
self.addItem(">")
self.addItem(">=")
"""
Set the indicated operator as selected
"""
def setSelected(self, operator):
if operator == "<":
self.setCurrentIndex(0)
elif operator == "<=":
self.setCurrentIndex(1)
elif operator == "=" or operator == "==":
self.setCurrentIndex(2)
elif operator == ">":
self.setCurrentIndex(3)
elif operator == ">=":
self.setCurrentIndex(4)
|
UTF-8
|
Python
| false | false | 2,012 |
4,724,464,032,032 |
0244399903869ccb02307e989e6dd4238bdd4355
|
f16e13dec47379ae4aba2896023299c53a0985f4
|
/test2.py
|
b480d450e5dc036f4d91f61c293a520b202e0d09
|
[] |
no_license
|
WDC/Delcoe-Communications
|
https://github.com/WDC/Delcoe-Communications
|
41ade0f0fd9ead12781b23d9421a9d4cfc6a5bf3
|
fb290d47ee05c80fec8a7faec80173d142d33ebd
|
refs/heads/master
| 2016-09-06T06:04:28.289755 | 2012-10-16T20:09:17 | 2012-10-16T20:09:17 | 2,852,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
import time
count = 0
string = ''
a = time.time()
while (count < 100000):
string = string + str(count)
count = count + 1
print time.time() - a
|
UTF-8
|
Python
| false | false | 2,012 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.