__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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,439,541,448,936 |
a7d2625aa3cd377052392090b8713a5d7677681c
|
ac4bdf074dbdaf761183c6cea0ac0973dfca4657
|
/cuse-maru/mix/gui/cuse-mixgui.py
|
6b0e0ad795f60f76256c95e09fbbefcc6f14463f
|
[
"GPL-3.0-or-later",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"GPL-3.0-only"
] |
non_permissive
|
mcuee/libmaru
|
https://github.com/mcuee/libmaru
|
74e47140760797bb7b667bcfb87b1163be428ee7
|
9a2ac0635f12485f15d68b90eed3f60ab9a86123
|
refs/heads/master
| 2022-04-22T14:30:10.900399 | 2012-07-06T15:16:06 | 2012-07-06T15:18:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
from gi.repository import Gtk, GObject
import socket, os, sys, fcntl, array, struct
class Connection:
def __init__(self, sock):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(sock)
def get_reply(self):
reply = self.sock.recv(8)
length = int(reply.decode().split(" ")[-1])
return self.sock.recv(length)
def set_volume(self, stream, vol):
command = "SETPLAYVOL {} {}".format(stream, vol)
message = "MARU{:4} {}".format(len(command) + 1, command)
self.sock.send(message.encode())
return self.get_reply()
def get_volume(self, stream):
command = "GETPLAYVOL {}".format(stream)
message = "MARU{:4} {}".format(len(command) + 1, command)
self.sock.send(message.encode())
reply = self.get_reply()
vol = int(reply.decode().split(" ")[-1])
return vol
def get_name(self, stream):
command = "GETNAME {}".format(stream)
message = "MARU{:4} {}".format(len(command) + 1, command)
self.sock.send(message.encode())
return self.get_reply().decode().split(" ")[-1]
class MasterControl(Gtk.HBox):
def __init__(self, path):
Gtk.HBox.__init__(self)
self.pack_start(Gtk.Label("Master"), False, True, 30)
self.scale = Gtk.HScale()
self.scale.set_range(0, 100)
self.scale.set_value(0)
self.scale.set_size_request(200, -1)
self.scale.set_round_digits(0)
self.scale.set_sensitive(False)
self.scale.connect("value-changed", self.vol_change)
self.setplayvol = 0xc0045018 # IOCTL stuff
self.getplayvol = 0x80045018 # IOCTL stuff
self.fd = open(path, 'wb')
self.pack_start(self.scale, True, True, 20)
self.update_timer()
def set_volume(self, vol):
buf = array.array('i', [vol])
fcntl.ioctl(self.fd.fileno(), self.setplayvol, buf)
def get_volume(self):
buf = array.array('i', [0])
fcntl.ioctl(self.fd.fileno(), self.getplayvol, buf, 1)
return struct.unpack('i', buf)[0] & 0xff
def vol_change(self, widget):
self.set_volume(int(self.scale.get_value()))
def update_timer(self):
try:
self.scale.set_value(self.get_volume())
self.scale.set_sensitive(True)
except:
self.scale.set_sensitive(False)
self.scale.set_value(0)
GObject.timeout_add_seconds(5, self.update_timer)
class Control(Gtk.VBox):
def __init__(self, conn, i):
Gtk.VBox.__init__(self)
self.scale = Gtk.VScale()
self.process = Gtk.Label()
self.pack_start(self.process, False, True, 10)
self.scale.set_range(0, 100)
self.scale.set_value(0)
self.scale.set_size_request(-1, 300)
self.scale.set_round_digits(0)
self.set_size_request(25, -1)
self.scale.set_inverted(True)
self.scale.set_sensitive(False)
self.pack_start(self.scale, True, True, 10)
self.i = i
self.conn = conn
self.scale.connect("value-changed", self.vol_change)
self.update_timer()
def vol_change(self, widget):
self.conn.set_volume(self.i, int(self.scale.get_value()))
def update_timer(self):
try:
self.scale.set_value(self.conn.get_volume(self.i))
self.process.set_text(self.conn.get_name(self.i))
self.scale.set_sensitive(True)
except:
self.scale.set_sensitive(False)
self.process.set_text("")
self.scale.set_value(0)
GObject.timeout_add(100, self.update_timer)
class Window(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title = "MARU Volume Control")
self.conn = Connection("/tmp/maru")
self.set_border_width(5)
vbox = Gtk.VBox()
vbox.pack_start(MasterControl("/dev/maru"), False, True, 3)
vbox.pack_start(Gtk.HSeparator(), False, True, 3)
box = Gtk.HBox()
box.pack_start(Control(self.conn, 0), True, True, 3)
box.pack_start(Gtk.VSeparator(), False, True, 3)
box.pack_start(Control(self.conn, 1), True, True, 3)
box.pack_start(Gtk.VSeparator(), False, True, 3)
box.pack_start(Control(self.conn, 2), True, True, 3)
box.pack_start(Gtk.VSeparator(), False, True, 3)
box.pack_start(Control(self.conn, 3), True, True, 3)
vbox.pack_start(box, True, True, 0)
self.add(vbox)
if __name__ == '__main__':
win = Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
|
UTF-8
|
Python
| false | false | 2,012 |
13,881,334,344,651 |
f7aaf2455920fac4afeeaf6f33abd4a6fbe48a95
|
d46023e4720cd4b227c8527a39dfdfd5cfa365d3
|
/tempus_api/models/token.py
|
97d51fd21e5f780df577c58d71c683d27b437c4b
|
[] |
no_license
|
iskracat/tempus_api
|
https://github.com/iskracat/tempus_api
|
4350c92c47edbae95d54dc03320e1bf822bbc45c
|
0234de881b9a9c30bd8a1a01ad1560353f56cbdf
|
refs/heads/master
| 2015-08-06T01:10:39.456953 | 2014-05-27T07:41:11 | 2014-05-27T07:41:11 | 3,346,665 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- encoding: utf-8 -*-
from datetime import datetime
import uuid
import persistent
import transaction
from mongopersist import mapping
from user import UsersByEmail
class Token(persistent.Persistent):
"""
Token object for sessions
"""
_p_mongo_collection = 'tokens'
def __init__(
self,
email="",
token="",
ip="",
active=True,
agent=""):
# DB id
self.email = email
self.last_modified = ""
self.token = token
self.ip = ip
self.active = active
self.agent = agent
self.signup_date = datetime.now()
def getPublicDict(self):
result = {}
result['email'] = self.username
result['signup_date'] = self.signup_date
return result
class TokenByToken(mapping.MongoCollectionMapping):
__mongo_collection__ = 'tokens'
__mongo_mapping_key__ = 'token'
def addToken(self, email, ip, agent):
u = uuid.uuid4().hex
self[u] = Token(
email=email,
ip=ip,
agent=agent,
token=u
)
transaction.commit()
return u
def validToken(self, token):
if token in self and self[token].active:
return True
else:
return False
def getUserByToken(self, token):
if token in self:
t = self[token]
if t.active:
return UsersByEmail(self._m_jar)[t.email]
else:
return None
|
UTF-8
|
Python
| false | false | 2,014 |
901,943,141,905 |
bd91312b7335759f05a0ae016f7998b8eab6a3cf
|
b03feed4781ddad35026c4fd9f2ad29c681ca5cf
|
/muigi/hardware/easydaq_settings.py
|
f804a8963fb22975f8b81071ec76425fd67e1c4f
|
[
"GPL-3.0-only",
"GPL-1.0-or-later",
"GPL-3.0-or-later"
] |
non_permissive
|
douglas-watson/muigi
|
https://github.com/douglas-watson/muigi
|
f9aac61a53e6f15dcb59065253afd92741533037
|
37cba14b139de15b9cb32b19d1664b356b81e2c6
|
refs/heads/master
| 2020-04-23T14:33:48.192785 | 2011-09-29T14:26:58 | 2011-09-29T14:26:58 | 2,214,392 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# This is a link to the device. Avoids having to change /dev/ttyUSB* all the
# time.
__all__ = [
'DEVICE',
'BAUDRATE',
]
DEVICE = '/dev/serial/by-id/usb-FTDI_USB__-__Serial-if00-port0'
BAUDRATE = 9600
|
UTF-8
|
Python
| false | false | 2,011 |
4,166,118,313,641 |
8f5fb32a91aba4c457204413493de26a1bb0c1b0
|
e3857a9e798b3c58b394c7924cb8d39a01aae369
|
/002/problem2.py
|
6d86444d08a3bf844170637ffc746846d33065f9
|
[] |
no_license
|
toshimaru/ProjectEuler
|
https://github.com/toshimaru/ProjectEuler
|
3b179f7dfa3fd3dddb43e87b3972bc7317e82ce4
|
ad1d6d962a5b14605c402b91071e83f32c789eec
|
refs/heads/master
| 2021-01-25T06:37:12.920469 | 2014-04-28T00:45:22 | 2014-04-28T00:45:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def fib(n):
a, b = 1, 2
while a < n:
yield a
a, b = b, a + b
print sum([i for i in fib(4000000) if i % 2 == 0])
|
UTF-8
|
Python
| false | false | 2,014 |
10,136,122,829,347 |
6d09ca22226b338eb083e3c70bcfcfeed1f6d06f
|
39124a2f298f0234da1038b211fdfd2cc5cebe02
|
/vu/supporters/traversal.py
|
b65b3c77636dc9920815652bd7e91f12636863e3
|
[
"AGPL-3.0-only"
] |
non_permissive
|
schmoll/Voter-Universe
|
https://github.com/schmoll/Voter-Universe
|
13c9ab16caa015e0a9e7ab35704a6f3e03e38d42
|
42a2ce7806088c6fe7973a48ea95295d3b8c026d
|
refs/heads/master
| 2018-01-15T01:29:19.846219 | 2011-12-29T02:25:16 | 2011-12-29T02:26:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Copyright (C) 2009 Voter Universe <http://www.voteruniverse.com>
# Jason Lantz: [email protected]
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the Affero General Public License Version 3 as published
# by the Free Software Foundation. You may not use, modify or distribute
# this program under any other version of the Affero General Public License.
#
# 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 Affero
# General Public License for more details.
#
# You should have received a copy of the Affero General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
from django.utils.datastructures import SortedDict
from django.utils import simplejson
from django import forms
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from vu.core import traversal
#from vu.supporters.compare import SupportersCompare
from vu.supporters.filters import ComboFilter
from vu.supporters.filters import TagFilter
from vu.supporters.grids import SupportersGrid
from vu.supporters.models import Supporter
from vu.supporters.models import UserProfile
from vu.supporters.detail import SupportersDetailView
from vu.supporters.signals import create_user_profile_and_supporter
from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import Layout, Fieldset, Row, HTML
class SupportersList(traversal.GridSubSection):
title = u'List'
description = u'View Supporters as a List'
_path = u'list'
grid_class = SupportersGrid
class UserProfileForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput(render_value=False))
password_confirm = forms.CharField(widget=forms.PasswordInput(render_value=False))
administrator = forms.BooleanField(required=False)
helper = FormHelper()
helper.form_class = 'vu-form-user-profile'
submit = Submit('save', 'Save')
helper.add_input(submit)
def __init__(self, *args, **kwargs):
self.user_profile = None
if kwargs.has_key('user_profile'):
self.user_profile = kwargs['user_profile']
del(kwargs['user_profile'])
if self.user_profile:
initial = kwargs.get('initial', {})
initial['username'] = self.user_profile.user.username
initial['email'] = self.user_profile.user.email
initial['administrator'] = self.user_profile.user.is_superuser and self.user_profile.user.is_staff
kwargs['initial'] = initial
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.user_profile:
self.fields['edit_user_profile'] = forms.CharField(initial=1, widget=forms.HiddenInput)
self.fields['password'].required = False
self.fields['password_confirm'].required = False
else:
self.fields['add_user_profile'] = forms.CharField(initial=1, widget=forms.HiddenInput)
def clean(self):
cleaned_data = self.cleaned_data
if not self.user_profile:
username = cleaned_data['username']
users = User.objects.filter(username = username)
if users.count():
self._errors['username'] = forms.util.ErrorList(['The username %s is already taken' % username,])
email = cleaned_data['email']
users = User.objects.filter(email = email)
if users.count():
self._errors['email'] = forms.util.ErrorList(['The email %s is already used' % email,])
password = self.cleaned_data.get('password')
password_confirm = self.cleaned_data.get('password_confirm')
if password and password != password_confirm:
self._errors['password'] = forms.util.ErrorList(['Passwords do not match'],)
self._errors['password_confirm'] = forms.util.ErrorList(['Passwords do not match'],)
return cleaned_data
def save(self, supporter):
user = None
user_profile = None
if self.user_profile:
user_profile = self.user_profile
user = user_profile.user
username = self.cleaned_data.get('username')
email = self.cleaned_data.get('email')
password = self.cleaned_data.get('password')
administrator = self.cleaned_data.get('administrator')
# Disable automatic Supporter creation when adding user
post_save.disconnect(create_user_profile_and_supporter, sender=User)
if not user:
user = User.objects.create_user(username, email, password)
if administrator:
user.is_staff = True
user.is_superuser = True
user.save()
else:
changed = False
if username != user.username:
user.username = username
changed = True
if email != user.email:
user.email = email
changed = True
if password != user.password:
user.set_password(password)
changed = True
if administrator != user.is_superuser:
user.is_superuser = administrator
user.is_staff = administrator
changed = True
if changed:
user.save()
if not user_profile:
user_profile = UserProfile(user=user)
user_profile.save()
self.user_profile = user_profile
supporter.user_profile = user_profile
supporter.save()
# Re-enable signal
post_save.connect(create_user_profile_and_supporter, sender=User)
return True
class SupportersDetail(traversal.DetailSubSection):
title = u'Detail'
description = u'View an individual supporter in detail'
_path = u'detail'
detail_class = SupportersDetailView
def process_request(self):
response = super(SupportersDetail, self).process_request()
if response:
return response
if self.request.GET.has_key('add_user_profile') or self.request.POST.has_key('add_user_profile'):
return self.process_add_user_profile()
if self.request.GET.has_key('edit_user_profile') or self.request.POST.has_key('edit_user_profile'):
return self.process_edit_user_profile()
if self.request.GET.has_key('show_user_profile') or self.request.POST.has_key('show_user_profile'):
return self.process_show_user_profile()
if self.request.GET.has_key('delete_user_profile') or self.request.POST.has_key('delete_user_profile'):
return self.process_delete_user_profile()
def process_add_user_profile(self):
if self.detail.obj.user_profile:
raise ValueError('Cannot create a user profile for a supporter that already has one')
if self.request.method == 'POST':
form = UserProfileForm(self.request.POST)
if form.is_valid():
response = {}
form.save(supporter=self.detail.obj)
response['success'] = True
response['location'] = self.request.path
encoder = simplejson.JSONEncoder()
json = encoder.encode(response)
return HttpResponse(json)
else:
form = UserProfileForm()
response = {}
t = get_template('core/render_uni_form.html')
context = {}
context['form'] = form
form_html = t.render(Context(context))
response['success'] = False
response['form_html'] = form_html
encoder = simplejson.JSONEncoder()
json = encoder.encode(response)
return HttpResponse(json)
def process_edit_user_profile(self):
if not self.detail.obj.user_profile:
raise ValueError('Cannot edit a user profile that does not exist')
if self.request.method == 'POST':
form = UserProfileForm(self.request.POST, user_profile=self.detail.obj.user_profile)
if form.is_valid():
form.save(supporter=self.detail.obj)
response = {}
response['success'] = True
response['location'] = self.request.path
encoder = simplejson.JSONEncoder()
json = encoder.encode(response)
return HttpResponse(json)
else:
form = UserProfileForm(user_profile=self.detail.obj.user_profile)
response = {}
t = get_template('core/render_uni_form.html')
context = {}
context['form'] = form
form_html = t.render(Context(context))
response['success'] = False
response['form_html'] = form_html
encoder = simplejson.JSONEncoder()
json = encoder.encode(response)
return HttpResponse(json)
def process_show_user_profile(self):
response = {}
t = get_template('supporters/show_user_profile.html')
context = {}
context['supporter'] = self.detail.obj
form_html = t.render(Context(context))
response['success'] = False
response['form_html'] = form_html
encoder = simplejson.JSONEncoder()
json = encoder.encode(response)
return HttpResponse(json)
def process_delete_user_profile(self):
pass
#class SupportersCompare(traversal.CompareSubSection):
# title = u'Compare'
# description = u'Compare the current set of supporters with other sets of supporters'
# _path = u'compare'
# compare_class = SupportersCompare
class SupportersAdd(traversal.SubSection):
title = u'Add Supporter'
description = u'Add a new Supporter'
_path = u'add'
icon_css_class = 'vu-icon-add'
def render_batch_actions(self):
return ''
class SupportersSection(traversal.FilteredSection, traversal.TaggedSection):
title = u'Supporters'
description = u'Browse and compare supporters'
_path = u'supporters'
available_filters = [ComboFilter, TagFilter]
model = Supporter
@property
def subsections(self):
if not hasattr(self, '_subsections'):
self._subsections = []
self._subsections.append(SupportersList(self.request, self))
self._subsections.append(SupportersDetail(self.request, self))
#self._subsections.append(SupportersCompare(self.request, self))
self._subsections.append(SupportersAdd(self.request, self))
return self._subsections
@property
def counts(self):
# Bypass the caching of counts for supporters since there are likely to be fewer of them and performance isn't likely to be a constraint at this point.
return self.get_counts()
def get_counts(self):
counts = SortedDict()
counts['supporters'] = self.get_base_queryset().distinct().count()
return counts
def get_batch_actions(self):
batch_actions = []
batch_actions.append({'id': 'add_tags', 'title': 'Add Tags', 'icon_css_class': 'vu-icon-tags'})
batch_actions.append({'id': 'remove_tags', 'title': 'Remove Tags', 'icon_css_class': 'vu-icon-tags'})
return batch_actions
|
UTF-8
|
Python
| false | false | 2,011 |
7,215,545,058,313 |
a1c585e7799091e9e89b16ae2300753c8bf3299c
|
7118a5750c033950078945c82ee6dfcaf771a6d1
|
/serve.py
|
bee0f4f574d37ae04dbdba6e627c4ea1860e235b
|
[] |
no_license
|
methane/pyconjp2012-gevent-slide
|
https://github.com/methane/pyconjp2012-gevent-slide
|
f477c58d7fbd7e94454a2239109667e59c11fd10
|
2cfc537c7707b5c6c6befe0aacc0d188652cfe10
|
refs/heads/master
| 2020-06-08T04:10:50.431020 | 2012-09-10T09:05:39 | 2012-09-10T09:05:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from gevent.pywsgi import WSGIServer
import render
def app(env, start_response):
content = render.render()
content = content.encode('utf-8')
L = len(content)
start_response('200 OK',
[
('Content-Length', str(L)),
('Content-Type', 'text/html; charset=utf-8'),
])
return [content]
WSGIServer(('127.0.0.1', 8001), app).serve_forever()
|
UTF-8
|
Python
| false | false | 2,012 |
10,703,058,504,133 |
2754002d37ea5524e789d708091b3b2c6edbb423
|
d660c03afd26ac36d40fa25e0e27545b6d1793f6
|
/project/app/base/pagination.py
|
b25cd924084d06341807ef6aefee8f5c634c4075
|
[
"LicenseRef-scancode-other-permissive"
] |
non_permissive
|
feilaoda/FlickBoard
|
https://github.com/feilaoda/FlickBoard
|
04ac306cdc522a182bdea630d86d2dcba69e706c
|
21e6364117e336f4eb60d83f496d9fc1cb2784ae
|
refs/heads/master
| 2023-08-23T03:28:46.155135 | 2012-02-09T08:31:49 | 2012-02-09T08:31:49 | 3,311,988 | 29 | 2 |
NOASSERTION
| false | 2023-08-14T21:35:03 | 2012-01-31T04:49:32 | 2018-10-05T15:46:57 | 2023-08-14T21:34:59 | 375 | 27 | 2 | 2 |
Python
| false | false |
class Pagination(object):
def __init__(self, curr_page, total_pages):
self.curr_page = curr_page
self.total_pages = total_pages
@property
def has_prev(self):
return self.curr_page > 1
@property
def has_next(self):
return self.curr_page < self.total_pages
def iter_pages(self, left_edge=1, left_current=2,
right_current=5, right_edge=1):
last = 0
for num in xrange(1, self.total_pages+1):
if num <= left_edge or \
(num > self.curr_page - left_current - 1 and \
num < self.curr_page + right_current) or \
num > self.total_pages - right_edge:
if last + 1 != num:
yield None
yield num
last = num
|
UTF-8
|
Python
| false | false | 2,012 |
11,751,030,571,967 |
7ba0fae58f5f14a84a6a7ca025e94940b12e545d
|
30bce8ea3826ba17c415f94473ea0f337ea415c1
|
/misc/mysql_python.py
|
c6e85289398b259db9be7b971242f850c2554eed
|
[] |
no_license
|
kwheeler27/insight_datasci
|
https://github.com/kwheeler27/insight_datasci
|
bf4a83c79f90dd60cec13d7a7da2ab684896aaa3
|
4488f60d7b0c3602fad6b6701ce29286265fa903
|
refs/heads/master
| 2016-09-08T15:09:05.345420 | 2013-10-10T00:50:43 | 2013-10-10T00:50:43 | 13,261,154 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
import MySQLdb as mdb
#create DB
def connect():
db = mdb.connect(host='localhost', user='root', db='crashcourse') #local_infile = 1 used if loading from local csv)
db.autocommit(True)
return db, db.cursor()
def main():
db = connect()[0]
cur = connect()[1]
command = "select * from customers"
output = cur.execute(command)
rows = cur.fetchall()
print rows
cur.close()
del cur
db.close()
del db
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,013 |
6,751,688,614,118 |
8fde4e2e36c94d1bbc5edd3ddbd0c06a508d48ed
|
08fda17a966bdb8c78f27d4967a793ad4a00be03
|
/LeetCode/Python/remove_dumplicates_from_sorted_array.py
|
ec033378d57a2589ae32b1fde70948535d4d081b
|
[
"MIT"
] |
permissive
|
wh-acmer/minixalpha-acm
|
https://github.com/wh-acmer/minixalpha-acm
|
6f6624647748a7de8e6b699796a6db68bd99df56
|
cb684ad70eaa61d42a445364cb3ee195b9e9302e
|
refs/heads/master
| 2020-12-11T08:14:40.223286 | 2014-10-28T05:05:47 | 2014-10-28T05:05:47 | 37,763,693 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#coding: utf-8
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if not A: return 0
i, j, la = 0, 1, len(A)
while j < la:
while j < la and A[i] == A[j]:
j += 1
if j < la:
A[i + 1] = A[j]
i, j = i + 1, j + 1
return i + 1
if __name__ == '__main__':
A = [1, 1, 2, 2, 3]
s = Solution()
print(s.removeDuplicates(A))
|
UTF-8
|
Python
| false | false | 2,014 |
18,648,748,038,433 |
0d2130162e6c7006429f9efa0686d5e107f5777f
|
86d09450bcb48c1a2950bce4e2d7d069487a0e69
|
/easytimetable/utils/fields.py
|
1cc65f4f41a00fa58548210891233702950ce477
|
[
"GPL-3.0-or-later"
] |
non_permissive
|
easytimetable/easytimetable
|
https://github.com/easytimetable/easytimetable
|
68cd8d4953e83277bde889b4f4d4b3c30e6e9669
|
2f581949bd9fc1208a9cc02c63bc6039120d8fad
|
refs/heads/master
| 2020-04-06T04:02:40.033902 | 2010-06-13T21:32:27 | 2010-06-13T21:32:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django import forms
class UserChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.get_profile()
|
UTF-8
|
Python
| false | false | 2,010 |
15,290,083,575,932 |
79f01cd182de150e05b7313c46f22a723a0af886
|
ed0f7b176e5cb7a66e191e99b37666870cb792f5
|
/app/main.py
|
c4d4cbe40d9ada4b2b56e74426d88466e638c2aa
|
[] |
no_license
|
joaosoares/secretgifter
|
https://github.com/joaosoares/secretgifter
|
57816adb5331385b7fdfd450ee1fefcd908ea6f9
|
07bb1895475d864675dd0a70568e6a0cedd027f2
|
refs/heads/master
| 2021-01-23T02:58:42.098130 | 2013-04-01T13:34:00 | 2013-04-01T13:34:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# AMIGO SECRETO / SECRET SANTA
# By Joao Soares
# March 24, 2013
#
# This program gets a list of people, phone numbers and what they want.
# Then, it makes a draw and text everyone who their secret friend is.
# Additionaly, it stores this data in binary so that it can be resent
# if necessary.
import csv, copy, random, pickle, datetime
from twilio.rest import TwilioRestClient
account_sid = "AC0d7fbef51ae3db02db38c55182dfbfcc"
auth_token = "3b51b8fb7c050b7d31fec5f75ef2cb29"
client = TwilioRestClient(account_sid, auth_token)
# I chose to use a Person class instead of a database b/c circular
# references are easier this way, so I can add people on the fly
class Person:
def __init__(self, name, number, gift=None):
self.name = name
self.number = number
if gift is not '':
self.gift = gift
else:
self.gift = None
# The friend this person gives the present to is called the recipient
def AddRecipient(self, Person):
if Person.name is not self.name:
self.recipient = Person
return True
else:
return False
class List:
def __init__(self):
self.participants=[]
def FileFromName(self, filename, buffer_="rb"):
return open(filename, buffer_)
def LoadFromCSV(self, filename):
if type(filename) is str:
filename = open(filename, "rb")
reader = csv.reader(filename)
headerline = reader.next()
for row in reader:
person = Person(name=row[0], number=row[1], gift=row[2])
self.participants.append(person)
print "%s added" % person.name
print self.participants
def LoadSaved(self, filename):
self.participants = pickle.load(open(filename,"rb"))
def SaveList(self, filename=None):
if filename is None:
now = datetime.datetime.now()
filename = now.strftime("%Y-%m-%d-%H-%M-%S") + ".p"
print filename
print self.GetParticipants()
pickle.dump(self.GetParticipants(), open(filename,"wb"))
print "Saved Successfully"
def GetParticipants(self):
return self.participants
class Draw:
def __init__(self, participants):
self.names = participants
self.Start()
# Starts the draw
def Start(self):
recipients = copy.copy(self.names)
random.shuffle(recipients)
for person in self.names:
recipient = recipients.pop()
while person.AddRecipient(recipient) is False:
print len(recipients)
if len(recipients) <= 1:
self.Start()
break
recipients.append(recipient)
random.shuffle(recipients)
recipient = recipients.pop()
def RemovePerson(self, participant_name):
for person in self.names:
# Find the person who is going to be removed
if participant_name == person.name:
leaving_person = person
for giver in self.names:
# Find who had drawed the leaving person
if leaving_person.name == giver.recipient.name:
giver.recipient == leaving_person.recipient
def SendSMS(self, person):
message_body = "E ai, %s! Nosso Amigo de Pascoa vai ser quarta-feira aqui na escola. Voce tirou %s" % (person.name, person.recipient.name)
if person.recipient.gift is not None:
message_body += ", que quer o ovo %s" % (person.recipient.gift)
message = client.sms.messages.create(to=person.number,
from_="+19496122442",
body = message_body)
def SendAllSMS(self):
for person in self.names:
self.SendSMS(person)
class Test:
def Draw(self,draw):
for person in draw.names:
print "%s tirou %s (%s) que quer um %s" % (person.name,
"SEGREDO","SEGREDO","SEGREDO")
def List(self,list_):
for person in list_.GetParticipants():
message = "%s tirou SEGREDO (SEGREDO)" % (person.name)
if person.recipient.gift is not None:
message += "que quer SEGREDO"
print message
if __name__ == '__main__':
people = List()
people.LoadFromCSV('info.csv')
draw = Draw(people.GetParticipants())
Test().Draw(draw)
|
UTF-8
|
Python
| false | false | 2,013 |
12,412,455,499,833 |
8230e6661864f03d5c8adf512666deef7e8b61d2
|
103689f393d2e5d573783ac32de824a4ede7f3a6
|
/Quicksort/Quicksort_medianOf3_pivot.py
|
1a36ad3c2a8a95d465dabdafd47527f04b3de28a
|
[] |
no_license
|
parthasm/Useful-Algorithms
|
https://github.com/parthasm/Useful-Algorithms
|
ef70771d342bd80f46218cdddb103900236d1b03
|
8360695febf92c4d029dad5589219901856080ca
|
refs/heads/master
| 2016-09-05T19:00:33.425683 | 2014-09-19T10:54:58 | 2014-09-19T10:54:58 | 21,391,766 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def quicksort_median(li):
length = len(li)
if length < 2:
return li
n1 = li[0]
mid=0
if length%2==1:
n2 = li[length/2]
mid = length/2
else:
n2 = li[(length/2)-1]
mid = (length/2)-1
n3 = li[length-1]
if (n2 <= n1 and n2 >= n3) or (n2 >= n1 and n2 <= n3):
temp = li[0]
li[0]=li[mid]
li[mid]=temp
elif (n3 <= n1 and n3 >= n2) or (n3 >= n1 and n3 <= n2):
temp = li[0]
li[0]=li[length-1]
li[length-1]=temp
pivot = li[0]
i = 1#right cell of the border inside partitioned cells
#dividing numbers less than pivot on the left to the numbers
#greater than pivot on the right
j = 1#right cell of the border separating partitioned cells(left)
#from non-partitioned cells(right)
while j < length:
if li[j]<pivot:
temp = li[i]
li[i]=li[j]
li[j]=temp
i+=1
j+=1
temp = li[0]
li[0]=li[i-1]
li[i-1]=temp
left_list = quicksort_median(li[:i-1])
right_list = quicksort_median(li[i:])
final=[]
final.extend(left_list)
final.append(pivot)
final.extend(right_list)
return final
import time
start_time = time.time()
import sys
sys.setrecursionlimit(10000)
fi = open('Input.txt')
li = []
for line in fi:
li.append(int(line))
li = quicksort_median(li)
fo = open('Output.txt','w')
for num in li:
fo.write(str(num)+"\n")
fi.close()
fo.close()
print "The time taken by the algorithm to run"
print time.time() - start_time, "seconds"
###Tail-Recursion optimizations absent in python,
###therefore , recursive algos in python not advisable
|
UTF-8
|
Python
| false | false | 2,014 |
6,176,162,980,505 |
593f701f645584e59c4f7d34d162fb9ca79b7b57
|
a0b1b8bba803c2d567fa7489347e2e4f1cf563cb
|
/admin.py
|
89d3e6cbdab06205c63e757f144983952664661e
|
[] |
no_license
|
jonemo/skillshelv.es
|
https://github.com/jonemo/skillshelv.es
|
22ec3a3f261321311110a342639425dae521a689
|
5c08a7beb5889536283c4ee1f9edfd7779b0c118
|
refs/heads/master
| 2021-05-26T12:10:29.135342 | 2012-09-15T21:32:06 | 2012-09-15T21:32:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from google.appengine.dist import use_library
use_library('django', '1.2')
import os.path
import re
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import fluidinfo
import skillshelves
class MainPage(webapp.RequestHandler):
def get(self, page):
# this is the dictionary in which we keep all template values
template_values = {
'skillshelves_logo' : '<span class="skillshelves"><span class="blue">S</span><span class="lightblue">K</span><span class="orange">I</span><span class="blue">L</span><span class="lightblue">L</span><span class="orange">S</span><span class="blue">H</span><span class="lightblue">E</span><span class="orange">L</span><span class="blue">V</span><span class="lightblue">E</span><span class="orange">S</span></span>',
'skillshelf_logo' : '<span class="skillshelves"><span class="blue">S</span><span class="lightblue">K</span><span class="orange">I</span><span class="blue">L</span><span class="lightblue">L</span><span class="orange">S</span><span class="blue">H</span><span class="lightblue">E</span><span class="orange">L</span><span class="blue">F</span></span>'
}
# the list of tags is needed in various places, so we make it globally available to any page
template_values["tag_list2"] = []
template_values['taglistasurlparams'] = ''
tag_list = skillshelves.get_tag_list()
for tag in tag_list :
template_values["tag_list2"].append(tag)
template_values['taglistasurlparams'] = template_values['taglistasurlparams'] + '&tag=skillshelves/skills/' + tag['tag']
if re.match("^[A-Za-z0-9_-]*$", page):
# the page displayed if the root url is requested
if not page:
page = "main"
#
# CATEGORIZE
#
if page == 'categorize':
# if we want to store the tags for one object, we'll get this parameter
fluiddbkey = self.request.get("fluiddbkey")
skills = []
template_values["log_list"] = []
# get list of tag names
template_values["tag_list"] = []
query = skillshelves.DBTag.all()
query.order('tag_name')
dbresults = query.fetch(500)
for dbresult in dbresults :
template_values["tag_list"].append(dbresult.fluiddb_tag)
if fluiddbkey:
if self.request.get(dbresult.fluiddb_tag):
skills.append({'key' : dbresult.fluiddb_tag, 'val' : self.request.get(dbresult.fluiddb_tag)})
if fluiddbkey:
fluidinfo.login('skillshelves', 'LSLKrasG12D')
for skill in skills:
headers, content = fluidinfo.call('PUT', '/objects/' + fluiddbkey + '/' + skillshelves.fluidinfoRootNamespace() + '/skills/' + skill['key'], body=skill['val'])
template_values["log_list"].append('/objects/' + fluiddbkey + '/' + skillshelves.fluidinfoRootNamespace() + '/skills/' + skill['key'])
template_values["log_list"].append(headers)
template_values["log_list"].append(content)
template_values["log_list"].append('done')
fluidinfo.logout()
thebook = skillshelves.DBBook.get_by_key_name(fluiddbkey)
thebook.tagged = 1
thebook.put()
query = skillshelves.DBBook.all()
query.filter('tagged = ', 2)
dbresults = query.fetch(1)
next_fluiddbkey = dbresults[0].key().name()
template_values['fluidb_object_key'] = next_fluiddbkey
skillshelves.connectToFluidinfo()
headers, content = fluidinfo.call('GET', '/objects/' + next_fluiddbkey + '/oreilly.com/title')
template_values['title'] = content
headers, content = fluidinfo.call('GET', '/objects/' + next_fluiddbkey + '/oreilly.com/toc')
template_values['toc'] = content
headers, content = fluidinfo.call('GET', '/objects/' + next_fluiddbkey + '/oreilly.com/description')
template_values['description'] = content
headers, content = fluidinfo.call('GET', '/objects/' + next_fluiddbkey + '/oreilly.com/homepage')
template_values['homepage'] = content
#
# MANAGE TAGS
#
if page == 'tags':
template_values["log_list"] = []
# DELETE
deleteentry = self.request.get("delete")
if deleteentry:
query = skillshelves.DBTag.all()
query.filter('tag_name = ', deleteentry)
dbresults = query.fetch(1)
skillshelves.connectToFluidinfo()
result = fluidinfo.call('DELETE', '/tags/' + skillshelves.fluidinfoRootNamespace() + '/skills/' + dbresults[0].fluiddb_tag)
template_values["log_list"].append(result)
db.delete(dbresults)
# RENAME
oldname = self.request.get("oldname")
newname = self.request.get("newname")
if oldname and newname:
query = skillshelves.DBTag.all()
query.filter('tag_name = ', oldname)
dbresults = query.fetch(1)
for dbresult in dbresults:
dbresult.tag_name = newname
dbresult.put()
# ADD
addentry = self.request.get("add")
if addentry:
e = skillshelves.DBTag(tag_name=addentry, fluiddb_tag=addentry.replace(' ', '__'))
e.put()
skillshelves.connectToFluidinfo()
result = fluidinfo.call('POST', '/tags/' + skillshelves.fluidinfoRootNamespace() + '/skills', {'indexed': True, 'description': 'Used for tagging books with skill levels for building personal skill repertoires on www.skillshelv.es', 'name': addentry.replace(' ', '__')})
template_values["log_list"].append(result)
template_values["tag_list"] = []
query = skillshelves.DBTag.all()
query.order('tag_name')
dbresults = query.fetch(500)
for dbresult in dbresults :
template_values["tag_list"].append(dbresult.tag_name)
#
# PULL ALL BOOK IDS INTO LOCAL DATASTORE TO EASILY LOOP THROUGH THEM FOR TAGGING
#
if page == 'pullallbooks':
# fluidinfoquery = 'has oreilly.com/title'
# query = skillshelves.DBTag.all()
# dbresults = query.fetch(500)
# tag_list = ''
# for dbresult in dbresults :
# fluidinfoquery = fluidinfoquery + ' except has skillshelves/skills/' + dbresult.fluiddb_tag
# self.response.out.write('query: ' + fluidinfoquery + "<br />")
fluidids = ["e6c3e235-7c8c-4b0c-9dcb-7baf83465706", "5509a171-232b-4d42-83e4-44cfa6cc7689", "60de7053-8c46-4f62-ab4b-0f406eb6850d", "d27b06eb-3d65-46f8-abd0-f6bef7d7d8ef", "04096554-a74c-4832-92e8-0b8d1e431f3f", "48952d9e-3a88-40a3-b97c-7a837161625c", "6808ddd7-5326-44ae-92a8-56246b3ec526", "d257ce8b-caad-47c3-b1ff-086366f1e917", "5072fb41-15e7-4181-ad10-8f33eb3f21de", "a2222f4b-b63a-4907-bd5c-5ec425f790b5", "1c95dbca-8a0a-4cdc-a382-7dbb8bde81ad", "0619cc81-6f72-4686-a402-6b3ef524691d", "ced108d5-fa9d-462a-abf1-d4f3787ffaaf", "987c0949-c095-48f2-add7-0a44f128a628", "97d54806-e573-4479-b97b-de27397956e0", "d798247e-4510-4491-a90b-5a6088e9f91f", "0a493719-8afa-48d3-98e8-ece091168a97", "c38f8651-899a-423b-979b-5dfbdaf15eca", "de6ecd73-7f83-4579-ac56-4bce486fbb0d", "91044abb-3c9e-47b3-b470-0512543f6d00", "0c83bab6-4885-460d-a57c-a57ec582ebbe", "db78aa10-322f-4689-b53f-35ece7c78fcb", "2b1f3e7b-7c34-4e21-a008-e693c2a854d6", "b15e4d17-024d-4044-b944-f75278641483", "edeedc13-6b67-4818-8656-48046a586146", "710486fa-8d0e-4b93-b9b6-c7fdfa940058", "0a13bdc9-2df2-478d-8963-3fc50f26c2cf", "83e1072a-2519-4a7a-9a20-fd304a3721b7", "eb918c82-b2fa-4a12-be86-0961caf4cef4", "31d0b726-bcbc-41e1-b9b5-eac716424dd2", "1cf6fde3-5f13-4e9d-bdff-84b66cf7439a", "9eee2670-3aef-401e-ae7d-ab9c3e7013f2", "e5264c14-ee96-4f1f-9a07-fa71d1de1768", "39376da9-551d-4d1f-b255-02a1eb91dfa9", "4bc90be9-e348-430d-8084-0fdc3aa6bc13", "49775ef4-3e15-4190-8c65-029a64f44290", "287cc8d9-df43-4d4e-b361-28850f9eb209", "63b4f539-0dce-4f2b-bd39-af221e242a78", "4c47731d-aa55-4234-812e-1ac3e9ec8ae0", "8bb77073-dca9-40f7-97e2-db6103166588", "e5565c0d-e009-4094-97f5-36b6ed00d1b4", "b042f4c6-6787-40f5-be54-21ba5a758063", "d2085d17-e9c0-4b37-b642-a39534fd9ef8", "539dafff-8d24-4ace-b00f-51e02508b7f2", "6d099c33-5846-4b9c-8986-a73a466befb5", "2064b458-feea-411c-a0fb-d158330eb973", "cbf6d9b7-1f03-4361-9b03-dcc5028885e3", "9c600218-0cc1-46e7-9846-e50a41ed94ca", "2f4b6804-f923-42a9-a8d4-a8396e01369c", "4f2b413e-755c-46b1-aa44-b27c05cd3436", "7ae80c2d-4b72-46ff-8b2a-c5d811cf819a", "6c5ff888-f2a9-4a3e-8f4f-a89b71560356", "9dff7f28-9837-4844-995a-dd53524f54b2", "80735fb9-8182-4f8c-8904-999236ba0279", "4a3f0c8f-74fa-479e-89d8-0f9abb5e00f7", "ac914f01-c870-4d1c-a56e-4fa9955e5527", "485a25a2-c03e-4bc7-8e20-f46053ea2ac0", "dc3c0dbe-6bc5-4d36-9b9a-d7c12c1de79e", "a81c649f-4561-4100-aac5-8cc9984f55ab", "d56dde4b-915e-490a-89f5-4e43d3080f17", "3562d5c6-0623-44be-847f-daac4d7ba845", "21327ffc-f104-44da-9db5-824f58d59476", "85a2b98b-d718-4a1b-a560-c8dff6a57644", "848d6a8d-ea7d-481a-95ad-e0c522d870f3", "fa42aa56-074a-475a-aad8-e705bbc024b1", "57c5e02e-eea7-4ede-b7fa-48cbaffc30ab", "2803c354-996e-4e06-88c6-36a3c7fbd026", "b96801dc-56c8-4dd9-9aff-1cbd3586be5a", "5caf85e6-106b-4acf-8142-3dbb1d71e916", "eac39843-1731-4b92-8382-3c0e89d640f5", "f00a4f05-753b-4726-9ace-7bbe9b97bff7", "d6f51218-8dc6-419f-bbb8-6cee59fc8fe1", "a25441d4-36b7-4529-aa93-89ba732ba8c6", "c9679754-5f7d-4afb-8592-f466dcb7789e", "d25ae875-7480-4ef9-8aca-b40dc919b6af", "a6095f5c-4125-462d-88c4-f6ff66ded484", "f9bc8d9c-3d9b-4fde-9e70-16dbb1f42871", "5d6cc3a6-a2a6-49c5-968e-8622efd7ed01", "656167e1-07be-428f-bdee-4db1543a33f0", "fc9cf77c-5c25-46f3-9b3d-65bead2c007c", "5ff8b170-0854-4d19-9579-d2289dc4413b", "2ae69f1a-a623-48f4-a0ad-3bb0b7e16e68", "6bea0e7c-5243-4c3b-a941-061026317989", "b6f73ab7-0aae-4ddd-b2cc-624ee422b694", "200cffb5-9b6c-4508-b05a-6d2697262b51", "79efce53-6e43-47d5-951b-c5d35ea8574d", "6411db77-e726-4660-9153-accc54f8ee82", "aa4a2c51-6540-4f16-ac91-2ca753fb17b0", "c51ae12f-5217-4b58-94c8-9e3a5e880ffe", "14ef9645-6694-47a0-9258-6ba54da69285", "7f11df46-5481-4b12-a58f-4baed3026764", "d456d6e0-a799-4a07-94ba-0ac76844a9c3", "3492106a-d3f7-4562-8c13-3b39d4575fd4", "bd9c91a0-52a5-4a56-b3a2-b2b820fd54a1", "7bc19a3d-88c7-4bb4-b47c-af64b355cf7b", "63e74f9e-efce-466f-87a3-b7808397e3c3", "fb332e8e-da6e-403f-9080-3946c600fc54", "5b31f688-3b95-450e-8be5-8b2a42d07f85", "422a2441-e0a9-4a42-9d71-89881e384665", "867ec9e7-1df2-4dfb-915b-f635b936c29c", "7b1ee133-180e-4922-83f7-cbcd804c0a6d", "1b8ce5d0-ef5b-4e61-af36-1742570eaf37", "421af9a2-4aa3-4f19-988e-ed471efc17bc", "7d3e59f8-964b-4911-a9b0-edd5bdf9da38", "4e64fad0-0f12-498c-b27a-da3a63957104", "2c1731fd-8401-46ac-9853-ccaa554ba2c2", "caf74821-a821-4f32-9167-8c57c663486c", "59f2d2b1-2ae8-41f2-abe4-ac0038576248", "cda26d1e-63f8-4893-acc9-763d48328024", "beb03b93-c9a7-43e5-9a93-9be01817e655", "6751eb0b-ec3a-473f-b3ff-2e1d6a521c67", "be5f6ad8-6669-4630-ace9-f46b6bbbbeb8", "720d19ad-f4b7-4f3d-8293-7aa1092d8b90", "9e3d5c9c-faf5-49fa-982a-528981c9e7a7", "8047273f-8bdc-40a2-a055-d9af451d14b8", "9a46edac-7a7e-4d3c-ae53-8ca7ea54d0a6", "ef5dd9b8-7df6-4b8c-b8b0-128b59370720", "cd5f2229-5ef1-4b2e-9a35-bb0e11dd5277", "a3d17244-8891-4f6b-ad86-3611a24d3347", "5e977d11-c182-491e-9389-990d80b9182b", "69160b06-e2be-4375-a524-6eef956bf1d5", "2b2e12e8-f37e-4200-970d-ce1bbc3422c0", "9defb7bd-664b-4498-9069-01cb75d5c905", "6a3a1a1e-2a7d-4650-803a-15a23715b76c", "e42ad5c1-37d2-4259-9ad6-417dbf70a22c", "5281e568-39b4-4021-9d13-a471511605d3", "7fef3a26-fd70-49be-8bfb-25957489cac0", "6d4a5016-108d-4758-9fc8-dc0023c3f84f", "3e082592-7739-44a2-9dd4-958aa322f3d7", "079c7708-0e50-4d52-b782-1d06b49f4131", "d69075d8-8fb6-417e-9d56-497463ef185a", "90b1edc0-897f-4288-9dfe-e699191a272d", "10228053-fd6b-4f6a-b650-b334f3653b97", "ce6b4182-c95b-4f70-a264-473e4cb6c505", "67c29669-6ed7-4a08-8ac4-200c6c566d10", "f2b8e730-4433-4b45-8346-3aac657463f0", "c2738e3a-780e-4ab7-9ceb-89c5e120b16d", "bb0ef295-7d39-4932-8baa-a1eb5fc1168f", "e446981b-7833-404b-a8af-7ccbfc7cd7b0", "af5d4983-bf3d-442b-bd18-42b767815c8e", "e62710f6-36b6-48f2-a81a-0f236198d8f0", "80f54e80-e69f-4f38-ae33-300c4caa4738", "d5f9a612-2dda-4299-9d99-4b7478f39e60", "90f46ab1-1142-44d4-a309-27c7b3a34547", "ae2f1c14-19b9-44a7-bfab-80dba873529c", "3ac7a704-53f2-4db5-a1c0-4a928786cb8b", "2cd260ab-b19d-4c55-90e0-8ac643a154ae", "c3521a08-17f6-4c07-9208-0090a6d182a4", "70bc65c2-939f-4148-8db3-368eaced2572", "313a748d-c7a5-42b9-a4dc-1ba98d5f434c", "ab2ecf60-9fb7-47e7-9cf4-dc4a25ef24f1", "1fd01751-f5f5-43fc-8c29-c27e1ced48d2", "cba27ace-34aa-40b5-9840-60826dbf54ce", "71d17fef-ec0d-4d49-86f8-e4000533d353", "a9409052-423c-4e49-8556-b657577d94ef", "fc3532ba-f144-47cc-9ea6-9574e2f912d8", "a7b26eaf-6042-443d-8930-fc49c4eeeac1", "cf8375b2-f78e-48f8-9aba-c85ea9e179bc", "a9b9831a-84f7-4399-8edc-9c611994cb56", "6d19a740-f353-485a-a587-15f72a63d012", "6c58df40-5a3a-4e54-9a5a-ba357545a647", "361a47e4-1c47-497f-8694-630b1b3b2545", "2c15efb2-b0cd-4c3c-9882-65ba41cc0152", "a0dbf983-5b78-4ff4-a4a7-f12e6259c30c", "c2b99ecb-58fa-4d6a-b41d-199edf25ca0d", "26f5343e-f238-421d-b3a4-2cac46a32bd9", "d4bd6e94-ae5e-4a8d-b6f3-fe969d4981f8", "eb4ac554-4890-4261-8853-69417e851b2c", "8979e1f5-18d3-42df-a58d-391f0053d4d4", "8d6f241b-46ce-42b8-9254-5a3fc0666e13", "ee5ced4a-04f2-42b3-a9b6-be5ec029c93f", "6dfde2df-ad06-4701-90b9-06bf97dde080", "36027760-d9a3-48ad-abe5-80ffed19b3a3", "09a686d9-07d3-4185-996f-6e6c7e35bac5", "3d863d87-96ba-459a-b0ad-d3d10e72ee47", "0c7c654b-6860-4498-bd81-73aa120603a7", "2ed21243-a44d-4d03-a9b1-b7ddcbfb5321", "3e597ab6-7a43-410d-9986-d7d2d35ce5ec", "54fbadc7-0a9c-4d59-be8f-56fb0dbb2784", "9c31ee65-0916-4673-ad9a-f318a4290517", "c9f329f6-2f78-4748-b0c2-6bedf4d240ce", "d5da5d63-2514-477d-a1d1-b88a61ecbec8", "1d0a2641-20e8-4da2-bfb0-83dd07398a14", "67f99696-cb2d-46a2-b4cf-41e3d79d5034", "8ce61498-5b4e-4445-ae16-939bf8bdf972", "18cca9a4-bbea-49c5-809d-7d44d99483db", "e421d8e6-09db-4251-ac67-07db2004969c", "dec73552-2fdd-4428-bf92-af1906119db8", "55740646-dad5-43c8-a96f-5800d9ac9945", "4cc645b8-76fe-4068-aed9-e3697c89a1d9", "fe4f2dbc-d3fe-4378-8293-78dfbfa517bf", "14e231d6-efe5-4e55-8fc1-2282a9378460", "9113393b-349d-40ec-85ec-c1156bbbc2ec", "531ab18f-f628-4561-b094-c000e219fbab", "e49b49ca-5d17-404a-b3a7-bde3189c4a4d", "490549f7-31ec-47bf-b685-3d3a34bcb51d", "842afcfa-48dd-45fd-89de-6a65149cd09e", "91aace33-61b1-4785-9acd-057f3c6ad9ae", "b80dca57-45fc-4cab-8464-e3b1686f249d", "7262df0d-cd5f-4a38-ab52-ba67fd49469b", "b3086229-0fff-472c-9a81-b9146579e3bc", "04e80043-06a5-487e-85e6-d8567dd5831c", "afaa01b7-9ad6-4d3f-8835-e8aadabb13f6", "493bc93a-c803-48ac-8384-6b51c8011890", "2add24c0-a8ea-4048-861d-c8e62d77fbfd", "873c13b2-0cca-4f5d-8582-3d095286a46a", "451649f5-1583-4681-b84b-770fc89b507b", "348da226-7bb8-4895-aab0-a09499b4c7c7", "d211632c-041f-49eb-a48c-4d37484ffd15", "755f1b8b-83fc-443f-96be-9793377358c9", "41a9cede-1a24-4c0a-b665-b5460864a8f4", "6489696a-5410-440e-bdd2-68a69e79e108", "7b3a1456-59b4-483f-8865-9d378ca7335b", "9f65e896-0cec-425c-b38d-edcab5730975", "35967f5f-7e94-4d28-a4e6-94acce5696f3", "97b2fc60-ab38-4789-a5a8-9a74418fb62e", "15307114-1094-4ad4-a3f7-835c1bef88f1", "759ae118-75ed-427c-9662-3cfbdf0e2fbc", "a2fd29eb-ff2e-444c-af96-5146ae4e6cc2", "825db775-2b43-432a-9122-c4390d13fb11", "86f26218-a788-4d77-8214-bc0e376a14c4", "8ce5ce6c-4193-4074-a29c-54d3fbeff525", "908da30b-231e-4a63-abf6-b7f5311219f3", "762fbe1d-29d4-4bc4-be4e-c8888cb797b3", "1326fa68-9c12-468b-a285-c8b3e48b4ddb", "5acf4ff4-4030-4561-8ed7-bb924c8b29e8", "5d05be8c-5b5d-497e-a1f5-fc1e58e2baab", "ab8bde7b-cbcd-4917-97f1-b329da698568", "3e97c719-7416-4a1b-be56-2c98f9346f98", "c2bd52a5-d205-426a-8b69-234e0f20e50e", "447f7f5e-a76b-4a13-bff2-ec9d0bce84e9", "cdabf5ea-d64c-49fe-ad97-8ce02ac90164", "4ebfba0e-901b-4cdc-849b-3f27fdd9ba73", "37693820-3ebf-45b0-90d3-6f29f6a4fba5", "1800704f-4bb7-4a95-bb01-2c7858dd6b4b", "50727928-5ae4-4042-a599-0f90bf94823d", "b417521e-0386-4e5b-b739-411220d07c2b", "ee7e843f-eca2-4053-a5de-d3fc4d659d7e", "f6a7e401-6389-45b6-9075-f93109d59f07", "0cb59f36-e0d1-4132-a3d4-865be31ccbb4", "d6254327-717d-42bf-937f-83568df1398c", "03a16928-0350-4019-8996-9dcf860ae17a", "a5f915a0-3243-403c-8148-16add3c5bb7a", "15ea3d07-ae76-4e1d-9237-b56be9291950", "2367af75-b2ae-4b3a-999c-4d87474ee2bc", "90777822-614b-4b76-8a7b-bb9e739c0ea4", "87868ee9-4d09-4ef2-8583-1478f7e1b763", "0ffce398-649d-47cf-94da-d26bb0cda8f1", "76ee142c-6f7e-4f48-bb83-3bcd8de2fe42", "34ed3c5b-909a-4799-a954-547b1f058c82", "a0359eeb-6ec6-46b5-8316-8d9c9e86402c", "da619948-2e83-4360-a9c0-9dc5cf7fbec1", "30f43e59-d432-4522-a2a9-b88ec66f906a", "6594091e-efe6-4999-8e04-be31795695e1", "2e3ed8f5-4ab0-439e-996b-2c16de083939", "fd63fd17-c345-4dc0-9d14-c8c7a51f9846", "4e80ffd1-c503-4648-b4c6-c1f2eb959edb", "d6ee9cd4-59a7-4376-a4bb-8a24bd72a380", "eabdfde7-c450-4e7b-8eeb-ab0efb01f6a7", "3770300b-7312-4ac9-9c03-fd1303501513", "1aace076-bca5-44dc-8993-c92af8abcdc0", "4512e043-0354-4596-a17c-4c72f33ddb2d", "fef51066-2ed8-45bf-83fa-a6ff756ca021", "9550f76a-54fa-469a-a8fb-6ef8d27cc1d3", "0072f0c6-46f0-4fd0-8bf1-b5302d5e892c", "72072cb2-56fc-42a7-9e15-009e9f9c73bb", "41fd8e5a-3208-49f2-afec-318cab6f31c6", "326e0124-7228-43ac-a56d-23b00ca5c1bb", "30313177-b40a-49de-9c77-855d55988adf", "8f6b4ff7-d389-4ca5-8e8b-1189951bbc54", "c9fd776f-8104-4c6a-abf3-15596d8f26c5", "e9bc53f2-b19c-429f-a997-8dd7feba0f61", "2862e03d-4381-4754-9ad4-596c91cb30a5", "7287b8e0-3ab5-4a00-a666-4555598de9ef", "79a68161-1177-45a8-a4b7-822c72f57497", "2dff1181-e8d5-411c-a079-fe68d45c2ee0", "9c71982b-35f9-47e3-9c3e-f77fb4d655d3", "82748d1c-170e-4fea-b887-64313af1b3ac", "8cc3db04-8df1-411b-8ca6-2e899a0dacfb", "3e95ecf5-cf52-4c33-aac2-b86ad32c64d6", "546bc323-faee-4f8a-a1b3-8d73fa62faf8", "d1b89a69-dbb2-4ce2-b586-98e49a159ac8", "42b0808d-cb88-4ca6-bd72-eb4f80730525", "63bac689-bc45-4343-8f5f-3c339973e297", "cd34ade1-4ef2-433b-8688-2104f4626f40", "9fe8a675-3419-43fa-a1b2-430c814a0acc", "38e11a03-5334-4c55-a162-a04fd5639162", "44e80f33-32c8-4c1a-8b5b-953002a7d4b4", "7c663226-a46c-4e1d-a714-38acff6de7bc", "6f9ad22a-ebe3-4ef2-b0b0-8fcc3a143523", "6c90104b-0339-420e-acfe-e1a90c52cde5", "f0bd265a-aa46-4975-a9e8-7e7f554ea18b", "fd104c8c-e754-46cd-b883-ed205b6e9f1a", "43f4e6ca-881a-44b4-ac38-93f26f90ce24", "fab5e518-d25e-4a51-a3dd-9d4b126f3473", "64e68bad-a641-46b9-aaed-f6209946be30", "2314ef35-e64f-4276-ae55-183284c43a5d", "db1e0c5c-c432-41c5-acd3-0e338e6df779", "000e3bdd-9c07-4a46-92f6-2ff7c0ed1da3", "4a8cc186-4007-48d8-bfed-f07d969b5ad0", "544c4d76-48f2-4ba9-bd28-ad2833088209", "f614cf1f-ce0f-4ad8-893e-4616a2921547", "af69ac15-0526-4e64-90a4-3d9075b62782", "7fe35174-4f40-4969-ae4c-072bd1248c57", "9852ab45-db89-498e-99e1-98ecf08db791", "6a6be4c0-77b0-4d00-b6c9-caf698104dd5", "7c617ae9-0098-458d-9dc5-2558ff771a9d", "633fd08e-ab22-4e7b-ac68-61b7e20d0b1e", "b99f5638-6ef9-4fef-a6ec-18a76203cb57", "6cc16561-8588-4822-acc5-343c23694158", "a8b6f5c7-c8fc-4966-a1e0-ac702135d43b", "134f0126-ef63-4aec-90b3-0b2c4a261c4d", "416aebbf-41c9-421b-85e3-94feaf42b91b", "89131072-a26f-45c5-872b-5b7d79e01b27", "15c119de-a50b-4146-a2a3-4ee867bc8d12", "67171a5f-4e03-40d4-8e35-ccc1cd092862", "a753e07c-9cbe-49e8-a30c-84fc8f4c73ca", "ad95e37a-5082-4a84-8200-13423d34080e", "da21c657-a3c6-46e5-9572-9503a5fc145e", "0f874a56-773f-4304-b190-515780660b3e", "20a36234-17e3-441c-a21f-be331e046be1", "ec08f198-c397-42b2-bb4b-38a7b5fe3c07", "c92e656f-1276-4d54-811b-643961fd236c", "98a3fc2a-a1e1-4e86-9fdd-c1f56259ebb2", "e2d3cf75-97d9-4b7b-a06c-6f8a828dd8a3", "42816ff2-2709-455e-a440-0811041d3feb", "ece5a29a-0662-4d0b-b579-ce3485f5d69c", "82498c3e-5f59-4e5a-ad2f-c4d7ace2aefe", "aed4b85f-09a0-44b2-bc19-a9d7f1d26ee9", "2c261fa1-06c4-4b1e-ad48-342532a5b978", "44182c62-ad7f-489b-97ee-7e44592518e6", "7371b7fa-189a-4eb0-855e-f39c56422367", "ad026533-64da-4129-be05-6d6602d84ebf", "d2f6a72b-50cc-4f3f-b887-f5376f220de8", "72bd180d-aa36-4130-a182-fee506455ed3", "af846b73-019f-4cff-90c3-69b45f17541f", "1bfd603d-3a5a-428f-a0f5-5c892fe719b3", "990ae762-6142-48ab-b42f-1d10952c9917", "847c21f2-9f20-422a-994e-b2bf579b2b20", "b5a70bde-9805-47b5-a9e2-eabe366ca4d2", "2ea835ae-d115-4f7c-872c-3edde165d87b", "7c30f215-0a87-46cb-bd51-4ff1034a5e1d", "ecce17d2-47a2-4f8d-92e4-db210c3552df", "c4897686-0875-499c-baee-a2b960bb66ba", "9d488271-8d38-4f65-a541-f49611969ec4", "64a533b1-c151-4f27-ba56-53b81c66a966", "14376d9b-9f77-49d8-9ecc-72fcf92d2aae", "fbe1a846-b235-42bb-8249-30e9abda8fed", "7842f4de-a911-46de-ae5e-2af039b383fb", "7793fe6e-70b4-45a7-ba55-4bf7f4578c55", "49e63197-8e80-4f95-b09c-d6c994e59304", "828dbca6-998e-4464-863d-4e9214884a5c", "7883c640-f15f-4c6d-9679-bc8f8d28d820", "3e6ea8f5-ad31-4025-8a5f-93699ea6d126", "1f83a5db-59cc-45fc-b91b-fcb5018721ca", "988b4630-f7c7-46be-919b-a81bbb606dd8", "1d0c47ce-2dec-4cd8-986e-ec280fbe7cb5", "60e9cf10-608c-4a0a-9c44-5a201b584283", "6fddd37b-6258-4bdd-8cb4-8dc8781b83b4", "4c6386b6-6603-476a-8b2a-8d24428e2b4f", "e807f67a-8550-46eb-80c9-f1d205ce38d2", "45330d17-27bd-4836-8560-844c23dbde7d", "ecd6e328-63be-4439-bac1-9cec08088af3", "9d4c203b-5c95-44f5-b550-686d9562a3d5", "74be08d7-1bb6-4d9f-a607-c5c2815a350c", "a6423e2c-b678-4844-8e30-cfa27ddd539f", "a321439b-2e52-4464-ae5a-b17efe6e555e", "a2bcf30b-f17b-4e6d-8659-9359cac65a64", "68193918-45e4-47c9-9e90-b44bab21976e", "b3f00213-44fe-47a3-a7b3-77fad832ec66", "abd5bc4c-cd21-4ad3-9b46-8d658dd11493", "c1bbe045-5952-4610-b98d-3baae8fdc125", "1b03b6fe-094c-40a3-bc9c-4ca92f77628b", "078ddce6-b442-4079-bd37-171d645b7681", "828ab2c3-e904-4d0e-9c5b-1034bd86e91f", "cd0838db-96ae-42ae-98c9-248a1507e2bb", "3d138096-bd2a-4b48-92b9-efda51888b7d", "48ddcbdf-6fd0-4984-924c-3a62e7d19ab0", "c8733de5-00a3-42aa-9213-9c3b2a1035a9", "0285c08c-2e5d-4d61-8024-a39c0fe859e5", "b4402eeb-eb58-4890-bded-9cc9f4cb9fbb", "df197504-9920-4b8f-abc9-4b3bd11d6cc5", "82b44471-6dba-4a86-b666-e7555fc4b000", "55218b9a-9c04-4083-8ebf-dd4a55170a7a", "39b709c4-b120-4cb4-951b-5dccb01b0b5a", "923cbe96-7118-4089-8d4e-4bee291622e5", "64878c63-ed43-41ef-b242-58b709ce0f30", "c2143980-8709-4930-a732-12abbaa16f8c", "efe86142-6aed-41ec-b6e3-bc38deda54ac", "f84d2978-c505-42c0-b783-c6517a0103d3", "1bf6027b-b8b4-43fb-92c5-37ced5172f05", "8a9a9d87-edb5-4e09-bf80-754a094a1265", "a79491b0-4482-4a23-8d5b-473180d361f9", "67a20e67-ab28-4b7d-a302-8b8abe09af6e", "b46b4b2c-62f0-4bc9-8325-405caadb6af4", "81ee8bc1-67cc-43bc-99a7-da4fbd47ccb3", "7f205ed0-8fad-470b-95c2-85ada5d2dca8", "c03a529e-8078-4e0d-9fce-8a23a620e369", "8e8ffedf-65e9-4d77-b6f6-16a105c3288e", "9bcb837a-4887-46b5-9979-1cc4eac01a15", "5ab85e52-cad8-4f58-a6b9-91c1537cb2e1", "9a3103d6-566a-4bf5-867a-6fcd6cae6d09", "697ee20b-a24d-4d4a-8b2e-e8fb1eb2a7c8", "d81e488d-1e84-4831-a6de-4636bc05acad", "438454ea-b933-4967-8250-3b0da32242bb", "ca7ca114-5b17-4461-b5bb-5042f5d8af0f", "5da4efca-6b89-47ce-bb61-567748b0443b", "4b5834f5-1f20-4e85-9c89-c4782ac4e598", "73ed1e25-461b-4e97-bf94-d1f8bdf26cd0", "96c7c088-2f0f-4ef5-8df2-96a8c2528707", "5741b9bc-6234-4370-8681-6e15d79ec415", "0c50a08a-deda-4113-8eec-d0c12bf3c71a", "ba064eea-0cb6-48cd-bcd0-5aa9c46b7ae1", "67e2ecfc-e206-4b69-b9ee-b902a889feeb", "598a60ee-fce0-4e62-b4db-41d43b1f067d", "1a3cb865-7249-40e8-84f3-7f62b2d0191e", "5c79ea0c-63f9-431e-8128-1ee79056fa34", "4ae4a37b-c0cc-45c2-ab9d-21a350a97d54", "e15438c4-c9e0-4a11-a216-bc36a1071579", "8fe3e823-4773-443a-96ec-0ee8f7e6c2bd", "f223c469-34ba-43e8-9adc-7165e5e863ce", "811d4d47-34ef-4a75-a069-f6afe9f4c1ed", "8a98f4d3-4246-4dea-b5ea-ffb4a803ad95", "5e15ab0d-e6ce-491b-8c73-477e3daeed0f", "b98e6637-a793-4669-9baa-b6d094c09f0a", "6c845b1e-8a99-41f5-91cc-d35aee064da9", "4512b10d-98cc-42ad-8bbd-987e0389d67d", "288271c1-6a5c-46bf-a1a6-7143f8716854", "3eff4228-734e-46ed-953b-cfc1c0087c75", "9ee53c0c-1761-4bab-89b4-2abae22cf56b", "2ee59968-7057-4719-9467-3c4272fbba21", "6d21d9e0-fe94-45eb-a465-39ada773cb3d", "08ccbc1a-de72-475b-9115-09b6b1e2dfb3", "27f40004-4e72-46a3-a33b-adb5bcd77bfc", "10803a27-7e3b-467a-8322-a1d015035353", "55c10c93-06df-45bb-8cd9-394153b904bb", "083d4658-c328-40ee-802f-ee24a7538039", "33df83f3-b9bc-4c74-807a-30df8b8735dd", "b20362a7-1ea7-44f1-87fc-285fe2db9825", "93cf61ec-6c67-49cc-9b57-ac5beb57b8e2", "3ec20119-c6b0-4c7f-8dcf-bcc3dc544ce5", "50430ddb-0f94-458f-ad3c-3a5104a32ede", "0b531ddd-8fa1-4d6a-a65a-aa76d8d3abfc", "82802229-d3d1-451b-829d-58bee44c8b3e", "a3420246-230c-4d37-8ce9-0e70ffdf2835", "a670c5a4-1e5c-42db-9d57-bdf9f548abf5", "9e048b1e-2b1e-4f6a-b5ed-041581382ce2", "32560184-543f-4637-ac6c-b8ed8ad17af4", "208eb970-6b2f-41be-bbe0-5ae3d5d82aa8", "656700e4-a72f-42a9-adfd-af1ac59aa71e", "bbeff549-17f6-481d-8b61-f7322301f9cb", "71c7bd3a-6505-404b-ac71-f4a98c4fec5b", "3acb1630-d636-46e0-8d7a-f5dcce0c9d26", "1c39404b-b51a-474d-82e4-5f1e25126d38", "c7125188-f053-4b48-acf3-db7cd3f64e57", "77c0ab75-077f-4ebd-bf6a-1758ec823c51", "51978a85-c2a5-44c6-be18-cae2c8016371", "da3cd590-f84e-4fdd-8d1a-44874f8057f6", "01b2aae6-fd52-4f44-a859-02197654fd4f", "ee44138b-9271-4068-a8e9-436190236522", "f5834225-32d8-4390-b71b-9109a90d826e", "a0e0fcfd-7a4b-4123-b2af-d26c36377821", "c049f202-28da-46b6-a86b-83080030a070", "6bee8959-26de-4b43-921a-f1f90e05b7bd", "b1ad055c-dc31-4175-a32f-e021eb692b7e", "0f462da8-50c8-4b17-bd2f-ce7fc02e956b", "cde29145-83ec-4b9e-b403-fb8ddb49c39b", "f4ecc3e3-fa16-4ca0-b165-88dfcbd021a9", "1aa06698-a870-4cff-b7e3-bd51fd06565e", "66fe5441-61e5-49f8-955c-fe9d311036be", "3c875d4a-e562-42c5-a84f-b130709d0bfc", "4eac6993-e406-420d-b6e0-4c5fd0f012f1", "41963287-d982-4220-a953-01f009f8ebea", "033aaa7c-4a22-475f-8804-54dc62e888d0", "9e91bd77-3914-4d73-ab8f-9c6c80b690c3", "bf5f7e44-623d-45ec-be10-c9543fa3c757", "439495e4-1f46-4dd7-b9ef-6039383866e3", "ed001dee-c7ae-4efa-aebf-93dcb490597b", "c797f597-fdb3-4f7b-a824-8bc31f147722", "503c5920-0a69-400f-83a5-fc13f30a676d", "6df1b46e-b7e4-4f70-bb78-edbe78fe6817", "ecadfb5f-1d1f-4a1b-88af-3bdc933981ce", "cc13e735-44a0-4e24-874f-1f6769ba0abf", "ea447043-a737-4d11-a81a-3791953abf32", "8aa7bbda-5999-4d90-9ba8-5cf9eecf4fc2", "27166359-dd3d-4408-ae6b-ebb6c77d5571", "d0b749d7-c0cd-432f-b20a-c6b81532f830", "76c11a2f-4bdd-42a1-8208-f745895666e3", "f0484942-e6bb-4316-82f3-f13fe20e8eae", "4a89cb63-8210-475e-b84b-ab6b06991612", "095b467c-5598-45c4-aec5-5739e47bc657", "dc48326e-5ef3-44e2-ac24-19bbd6e46c53", "80529eea-fef7-4f12-9552-92823cc23afe", "6c4fbcbe-2932-40b3-a51a-1d3acc470c11", "8896ec62-37b1-4d2e-8c8b-d6194efabf40", "f3ed1dfc-d4cc-4a03-a1ae-32732af3b0b5", "723cfcdf-60a7-4ebf-8bdd-4e67fe4c0e85", "d0caca29-2017-48f8-acee-a52ce745b34c", "8aab2b7b-13e8-42ba-afde-a5f2874e2274", "c49ed55e-e391-4737-8a29-fc700876a13a", "b15b495f-fa33-4b06-929c-6053736bfd55", "f595038f-9ae5-4e32-89f2-38d642ae4b83", "86cf38de-e86b-464f-81d6-4d30b26d01a9", "e799fe1d-2d39-42ba-9558-919b2e96b5f9", "1ce9ec00-3891-48f3-aa67-a9e9f89d33f2", "cc7f2c20-ff35-450e-8524-7ba1f813c022", "eea7e190-20e3-4b74-999b-2aaea2e300c4", "67e6e8aa-d0b5-40ba-817e-3f9db2cbec9d", "b927764f-7da4-43b3-a97b-e57c61b209a3", "362f1124-70ac-4464-886d-9480cbec6900", "51aa2820-4a38-4d18-8090-2bbd04ae7679", "70a5d771-9980-40c8-a64e-c57679b4c056", "f4e4d8a3-c5f2-4c3f-9db3-44466be5b07c", "6b1dab2e-9c86-45a4-ad27-9307b3761c28", "aca879ee-9f88-4bb3-9465-f74e5832ebb0", "562be19b-f1b5-4b5a-8363-d5616f5ee82b", "6c9eb946-b697-498b-a405-cac1d06997f3", "bedc5091-19c0-4609-b96d-7d47190ca6c5", "1f57113e-990c-4b37-bd7d-857de406eeca", "2271d5d2-5a14-42c7-82a2-842cd80e6831", "1357203f-d2c7-41af-bf82-86efbb878f9b", "2be4fe07-90a8-47e9-ac5c-ea0b7f6aa63c", "5fab7b34-efbd-4f3c-a834-608f7c8b92e4", "a373b839-5ced-4bdb-839c-7f19e8388c77", "2f27405f-552f-494f-a0e2-906644f7391e", "a97b33f3-e25d-4ccc-a9f4-91c21f2a9a4d", "25e45f24-6bcc-4abc-a7db-686e130330ea", "e5305f2e-738c-48ed-8f50-04cd106cf974", "2fc526fb-c783-4c34-b31a-24b1eb078414", "943c24be-c86b-4ea6-af07-45cef870dfbb", "8d3da0d0-3edf-4c0c-8649-e2a7dee91d65", "0b7fbcc0-9bab-4c45-bb96-49f2eeeaebce", "73cad08c-b03b-4ff6-b81f-74bfcf7209f0", "38ac36c4-a168-4f78-99eb-8cd1c88f7447", "f2079fb6-a401-484c-85c3-329e47b04419", "458856b5-fc51-40ec-8c47-1a6758faf095", "bd04c475-b00f-41ef-a89f-6d45365a2cf8", "535f4c05-24f6-42cd-b272-0aabc79aa1fb", "ee753d2b-c324-455a-8969-70709d4ee045", "1f8c194e-3d7b-40ec-b039-eb6698957212", "3374e8bf-83a8-46d2-9246-4e3640222f14", "79e2ec91-429d-4cf0-bce2-3bdfb15c45aa", "171f0c45-131a-4d42-bd90-632136a3ff3b", "05a3cfd7-d5d8-480d-a2f7-9f755a17ec5e", "682d82d7-205b-441a-9cef-40ec45f3c45a", "3164d243-93d0-4a69-88ee-6dde6c63f6f1", "0691c30c-95b3-4203-bdb3-cc5c6fb6f00f", "28f21459-3212-41d9-b879-1cf0b3f7ab96", "d49d4f2f-ca52-4740-8df3-ac16b86d2bfa", "f7245040-eb52-4b78-b399-6c31957742a3", "f9780dc1-f251-4efe-813c-07a695c7a118", "8855b981-6eff-4f54-824c-b000dc487ef8", "7ab464bb-7574-48ac-8129-6c31e9ecb554", "47cad3b4-b59a-47e3-b384-6d46f7d9e706", "28c0bd2c-2ac0-4d99-934e-da3d0bdb047f", "2fec69f1-5d4a-4af3-b50b-9e95209e097a", "3a63dc92-be05-46c6-87a1-052e4f700d72", "393ece64-3566-4a6b-9d71-e0b31d9edb50", "a43b114e-60e9-44b3-b01c-9cb71c6619ca", "5bdb8134-1189-4fd9-ace9-4c32c90f0044", "367772b7-7843-4af5-94af-be6f08af742b", "b8e204ee-7a11-419a-a770-d26550a02105", "e8bce000-4036-424e-96e1-7430babd26bc", "f76a8054-0bc8-4976-98f8-ebcc1f9a3356", "76bd43d7-03f2-425d-ad8a-5f56212619ea", "ca1ea0c3-3583-4b72-bae7-8f610c77d7cd", "88ea11bb-ae2c-43dd-8801-43a77f860573", "01864e06-f229-4bca-b5e7-3e8820e8cce5", "83bc9bd3-2fb5-4bda-8f90-d919f0f9f353", "0e6b0915-d413-4266-8670-6a59747fadea", "c968b2b2-12b2-455d-b70d-f5da11fcd65c", "271d2c35-3663-49f2-ad13-a4111606c334", "bd64c7d2-f619-4419-a612-edb164eb77d8", "3009e97c-3ba3-4cf1-940e-f3ef0f4fe7ab", "3eb0acad-759f-4566-a684-16d0fd6fe34d", "ed0344f0-5f32-4bf7-9acf-05a81a342cb9", "9b89f126-d906-4bda-b4a7-80223513671d", "53481106-ece4-42ca-ac35-ef28761772ff", "6786854d-d3cb-4fdc-8245-a6d4e5300b65", "d3df1e6f-80e9-4b4c-b5ad-4c0a4de54521", "18d56fb0-c0e9-4fa5-906d-56869711597f", "204d18a6-0f28-45a7-9c4b-64eaa31c269d", "0cf6fb91-76e9-48ed-954c-21ef9778b0de", "e556df65-93af-48ce-bbcd-81d88b156ad1", "fbaae634-8b8f-480c-bbc7-c61d6daeaf15", "ae099537-68b6-4a52-b7e5-ef59b625dda7", "49e5f524-0b69-401e-9a97-0217e45c438e", "da9e4c6b-441a-4471-b6bb-4ee546cc1e65", "66b5b0f9-31ca-468a-919f-6b24870b9368", "f5a54022-1ac3-40b6-9446-dedc08d96145", "6bb7b639-af51-4e83-94bb-906bd60ca891", "727fa02e-f6d9-4923-9db7-8df5b35ec4d6", "814dd5ac-e172-42c2-8afa-3d9d7d1b7c89", "19951842-e8f0-461f-a6aa-632f4027b31a", "c02742ea-15d4-429a-a583-c4e467a9ad61", "341194ff-3b2e-4b98-9911-2d43cd2415aa", "76e2ac78-9ad4-4bc9-8216-484ca1965cad", "a8664057-0641-4cfa-a3c7-da7218ebbe96", "4e01573b-4999-4b83-810c-c2ae872db83e", "5be57362-1403-4f4e-a02c-1082cd195641", "399c127c-1ff9-4a35-909f-066db1841cda", "65f5eb18-4c2b-4e6a-adcd-992b76f8a676", "ebf14602-7225-48ae-b12d-90f7145ba190", "ffad54c8-fec9-41bc-8140-58b5ece862d9", "2837641a-9dea-4a7e-8122-102d324f66c1", "0e9639b3-9c5c-46d3-9476-1b634d24a984", "483af9bf-99b6-45fe-a0cf-d9cf5c42f5d9", "b087f930-5e98-4d64-a47c-965bddfb3796", "84b745e5-1b5f-492a-86a1-9e7c8c89a518", "ad27e735-3a84-4910-a2a0-dd7614211a14", "204ca806-0b37-497a-b5c9-330daffcc7f8", "2059207a-d2f4-4c45-89b9-018b4efc63a4", "e4465718-dba1-40fb-a6ee-e4abf1150508", "69df595e-c392-4e1d-af46-28e753fa8242", "29442b41-8288-43e2-91bf-81ced8974553", "de823eb6-a65e-4958-ab8d-16b842d329be", "fe2c62be-e3e8-4242-9e02-1abe8d99ddef", "b87bf358-5ba4-475e-b145-c3085436924a", "fabe8bf7-7409-4ea9-a83f-691c646bb4b0", "11ff9fd0-8a60-40b1-bf5d-5f47008d2cda", "2ee94aba-1bc5-4201-9888-3685dd8da3db", "fac86ecf-e9c1-4c0b-8971-e3757f4c21ce", "7a08779f-1ed1-4ddd-a94d-869f663dc27f", "4c5c914a-fb5a-4e0b-b4e0-8107049bf545", "f7c184db-4729-4109-a5f1-eb5dd8a717ee", "a8808110-a865-4c5a-b2c1-6451f16f8a69", "b2618009-b6b1-4a45-b97a-82e1fe1c2d4e", "3e6a030d-9058-40ce-8725-bbadf04b68dd", "6fb1c9ec-aa42-4f70-b476-56eb58ce7075", "8b5d6ce3-6171-4659-a16c-179196d6fabb", "1a91e021-7bce-4693-bfa5-0dc437fe1817", "1738e12b-daaa-44bf-a5ae-3be017ce002d", "4ab192e9-4c2f-4486-8215-924980391255", "f07b435d-1be7-4aae-a1de-bccd1c3cdb97", "c4439c09-2274-4f47-a41d-48c83376c40e", "ff4bc00d-12eb-476c-8185-8038885dffa6", "a885b283-f82f-4655-b9c8-dcf85f7db51c", "73dbc8aa-5c65-4e0f-ab14-6773109fa31b", "5e6501b1-db07-48a1-b01d-74181d04cde4", "832ae0fc-3fb2-4ef0-8637-894d1c29d32d", "d38bb705-0601-4c14-9a84-fb9f08cbc9fc", "4814a5e7-dd3f-422c-88a2-602c3df50f23", "401715f0-a6b2-4b5c-8534-ec4c02b5064f", "88bc98a1-5875-484a-85bb-26b2bac7e434", "d1d6d857-3e54-4f01-a15c-0ac16edbcb2b", "a8ca66f1-271f-4c0b-a11f-9976c33c7ca3", "bdde1e8f-c33e-4a80-90be-32777daea64d", "aac01ebd-e891-42a8-b1f3-71554308243e", "e3250803-053b-4d41-973d-cc0e32276e43", "693f59c2-037b-4d41-973d-a5a7a85c3b37", "0cf813fb-7325-4656-91ec-abc7aafeba10", "b315cb8d-cc5c-4c23-aef1-bbf2f85a8f0b", "9f5805bd-213f-4ab3-8175-b7977f5603c6", "d793a7d8-8ef5-45c5-a90b-47f982615861", "e40bbb04-e390-47b5-b4c5-d983182a91fe", "d2ad19fc-0717-4afd-8f69-e37a6186b20f", "3051dd7f-20b8-4eb2-a800-c509ec001c4d", "0da922fe-6e0b-4982-8110-d24f5ebc77c9", "8b072cfb-e7f6-4de3-8a67-24d87360cc7b", "277aafeb-b051-4cee-9550-0d63ff7e6792", "653dc2d3-abd0-437f-a919-5af210b7cddf", "d20daf1c-ef11-4c95-b5ee-292dbaededfd", "aff9bad3-f356-495a-b0dd-032281af79c9", "9c30a775-4c5f-4518-b06f-c6ae01a37141", "4ac0786b-5321-4140-99bb-d673b9a0b740", "e985a6e6-51fc-4887-a0b9-8ebd578dfeb7", "863f0ebb-23a5-490f-818e-bc86cc130a1c", "bc4f2c72-8c64-460e-b105-648dedf8a34b", "e2c81150-2a6d-4eca-9e3e-a75e7fd42137", "b95a7fe7-2076-474a-aef8-ab00bce3963b", "55a755d2-4c39-4325-a07b-ec108e9204d4", "56dd9278-12bd-4b16-baaf-5736b943c953", "d5e3c22d-fbd8-42cb-bfd3-af7ff943ef1f", "c894a79b-fb68-4e49-a1ac-2145b4af3c85", "6261cd20-a951-4321-96dd-c3d5062e4263", "becc51c8-feee-4673-81e0-1cdfdc8bc67d", "5faccb5b-b115-436b-aa33-1d69bd7e56bd", "ad447d9a-fc65-412c-ab60-135aea9e62e5", "2b485a7f-2647-4c1e-9b90-f6e6f0395b92", "9f63a00f-6c98-4cd4-b8d1-35fafd53b869", "3911479a-fc1b-4aa8-b16d-e2b0fbfd22ec", "8cf28301-a6b0-42e2-980e-435b2d6e259b", "01f22a39-1634-41d3-866c-026162b2e427", "b5148fb6-3cdd-4308-a349-9db305516ce7", "7574c5fc-867d-484c-bc36-142a87442ac6", "f6c11f24-c3a9-4233-a32b-80122d13fac6", "11a75160-b741-49fc-9703-01d1095b9e22", "d1daedca-afeb-435b-8c9e-effb8dc4eda4", "8fcf106b-ecfd-488b-ae46-eeb2ae93c52d", "52055d3b-523a-4456-abf4-540fb4b95c38", "487cb0f6-f4f3-401f-8096-90ee29f115c2", "63181a91-66a4-440f-af62-4274d61731cf", "aab55a02-37b7-488d-b335-8698f2ea33e8", "92cd33f0-595e-46f1-9e2a-163105955e04", "035d7f46-076f-40a0-9cc8-5537d6d67c09", "c0437b24-5bed-4830-b7a2-3ed09cd001b7", "5b3194aa-58a9-477b-bb00-5136131b4a59", "788beb5a-6d58-4697-afba-412c57b61802", "88d02482-362e-44ac-b491-059e8c42eb01", "2e21dfe6-da7b-4d83-9e29-f4a5eadb735a", "59af45ee-1da1-4595-a275-063418070c68", "4fa59d84-3daf-4644-9f44-13063451204c", "065ca82b-57d5-4a38-b713-f025cadfd913", "90df8872-5dcf-4fc4-a729-8ea1ad86a3db", "d1d8c56e-24ad-4384-a8dc-66073aa85df1", "cf2619a6-ea76-4549-8815-62e7d2bc51fa", "02b7ea23-7270-46ab-99af-aa4addfdb671", "a2f4a568-f0fb-4bd6-b9e8-aa3b81590c74", "7c4ecbd5-8842-4134-9edd-d5cca03fe30d", "16a35fae-df37-45e8-8e01-31a6ffeb5db6", "12382694-70dd-46ed-a8a9-5fd07073b851", "c243be28-479f-471a-9fd6-285ff2ab1224", "7eac6da8-023a-4afe-9a9c-d396a1222ccb", "500d6d46-b643-4ec2-8047-0a81af282c79", "780dc6de-f5af-4c7f-b458-bf46337ebdda", "fced07e1-93ba-4700-b03b-171e1becb282", "ab47c07a-19d6-4819-be22-ffc17b6557af", "e4d67208-c8a4-4900-ba0f-50236e06bd38", "1d25baae-b977-4ff4-bb77-01c52bd1d339", "9e2f26ee-46dc-4899-a7b1-49fa4f4b9d0d", "782072ce-90d7-480a-a6b5-d4352991878f", "bdb5d278-502e-459b-812f-1c8662e536f8", "a15858a9-8891-4a2f-b7d2-980aedd8c90b", "1ae2cc4a-f2c9-466e-af4e-9368f5dce836", "2433d104-7140-4ff3-a11c-dfd3e98d394c", "a7496540-6218-4134-869e-d78d686a0189", "f9aa1147-b6ce-4a21-994b-6d49a2371902", "51b45a24-e7c0-4414-8508-9f52332dd07e", "05792656-224d-4aaf-9ecf-fc6151c4a6ec", "828d5ce7-8fb1-4b26-9d62-df668f7a2b4f", "457f874f-7dfb-4520-8916-179db506b5c9", "81e98482-a9db-49f9-b5a9-28d763d81ca5", "3ef80347-a8d0-4543-ae5f-316379dee258", "791ab313-2fcd-4196-a630-843a5cdd5563", "53814a91-4c80-4f6c-a025-54f09af0771b", "eec12c7d-f200-4987-8a60-0dde1ac4eecc", "523ce2b2-ae5d-4693-8bbd-2e67381c8c8f", "63ab9c56-cc24-4788-9f2f-7edf6ea9f8fd", "ed85b59b-c51a-455f-ac46-27e830224a36", "42f146f4-881a-4fef-9b69-271fed12cc11", "3fc3cb90-6948-43fa-bedf-05a186a66ac0", "69b1f4d8-a6cf-4d16-9dd3-bcf8c8ec2b40", "6af8a169-4034-44d4-92da-eadd5386f575", "5176dd4b-6c80-4ce1-a1fb-6da62be21b30", "cb2b71d5-932b-430e-8d93-e827049cf1f7", "058e9839-6801-47ff-ace3-87e91fabab55", "4136f5a5-f8fe-464c-8731-9c6ff373f7b0", "75614005-6b0f-4f4f-9013-06018081163f", "c1a7f998-7859-4545-a75b-1d7f7fd9d1e1", "33ba665c-3d6a-4703-8e4c-213934bb4721", "7f4a3de2-0250-4936-be89-526fba1d5eee", "233ef2c7-0d0e-41e5-a2cd-efa21e510fe7", "fc1f801f-d67f-4be7-89e6-4838407278cf", "b48a5280-e2ae-45a3-9f2f-d2c68e8f4632", "b16cac38-9fb6-44a3-be36-5ddfec974004", "b302df50-9452-4dfd-9a5d-7f66a7ab6980", "6e7cf56b-bb47-496a-aa72-f2d739d6e39e", "f4e1a55f-e42a-4cf5-9bc1-6c4d49f19e42", "c5dc30df-3c64-45a1-9ba1-c3a64541f5ed", "d8476529-a893-49c5-9014-67bf52b1abd6", "59adf2d5-2b35-40d3-b8c7-5bae2fbc7b68", "7047f17c-e40d-4fc9-83c6-d80fee346b84", "f5cf45a7-6c0a-4a44-8efe-a45e6ac398a0", "a75d586f-56f0-4051-97dd-ad10aa6590a2", "e9a148b1-ccae-496b-9b4c-fc59df48003e", "b5f5de04-f497-4a14-b612-c3a73b967ac0", "e461daa2-414a-4cb7-a0fa-e5fa980609ab", "1a60c925-ba0c-428c-8812-dff5b709213d", "74f18579-dff9-4a8f-b792-99e85af5e9a1", "893c73be-c55c-4831-b01c-410b300b5778", "c9b2ca8a-4230-42b2-aecc-e8bb976ce1ce", "5bc80b5a-2ceb-403a-9e2a-91fad49ea6e1", "0a241322-02ba-49bf-abc3-8bb3c1eaf0df", "988f87df-a6e3-4903-93ef-342d5a79bb74", "adafc1cc-ad5a-4b85-bcaf-ac3982035ae5", "4cd5fecc-32c6-4d8e-b046-6937649e5afe", "f9c52f77-0e18-4d50-9c51-8b258c8a7a01", "80edd1d5-6478-43a9-a485-5151682cfcd1", "21c9daa9-faf2-4d52-8645-5909fbd9f352", "874212b0-2aa2-4916-a2e5-015cd663eeff", "9461c341-99ac-4de4-a31f-8bff22a9d497", "f7cc93d4-3652-4c19-af76-f3982c074f48", "728a0660-0f68-4222-8e71-3dfa1d700203", "80ce5b67-16c4-4b29-bd78-8db46084bae2", "71768e8b-3723-4811-90f5-1aac2d249bc2", "6eff1d27-88e3-4a18-bda8-36ac6c3b363c", "aa7fa7e4-bd86-40d3-b5f2-142b924e9c68", "2ad874a1-4f09-49fd-b732-04447128bfc1", "df1d3441-b955-4d08-9801-b579e83297f4", "c21732f7-6792-4563-922b-53bc8794543e", "df4de426-8d1e-4737-8c5c-6776cb1b18bc", "20c65afb-1879-41ba-ac3f-0960d7be65cf", "181fafca-fe8d-4e9d-a08d-7edbce8f4e6b", "e4d810a3-4f2f-4319-b3f1-1374c5cf1305", "1bf0993b-4aa8-46bf-a142-384cf9743197", "a1cf1907-0106-4d50-9b40-db35b1f717af", "c5818bc6-17d4-4062-9227-9d75a2ebb17f", "6aa8ecee-ba9d-40f1-b21f-bbf1b15f8326", "61a97ea4-430d-4dc4-828d-03afab9916f6", "0f19f078-b9c5-4a82-b1bc-f531128e4147", "74c82627-6a36-4038-8a22-eac4ca899571", "418f6d47-04cd-4f4c-b544-e782a0a482e8", "293c97b9-184c-42d7-b9b1-23965c1c17ed", "6939c6ba-8887-4867-8255-b90769d632ec", "5165b082-0fcb-4b94-9749-a2f03b81fe44", "76c41241-0f4d-4530-8f13-59e43b26051f", "9397fc24-78df-4981-a838-bdd0d5208934", "b19cce74-bd9b-42f6-aa4b-40fe8b87dd6d", "8db876be-6336-46d4-a03f-25f479575a85", "55ec8a9f-ce17-4cce-9159-69eb6dc286fb", "19c0ba19-b676-4179-b02d-dee1bf662a5b", "cfe0ef13-f37d-455d-9ff3-5ceb52a7f5ec", "69bcf141-df1f-4c47-bb87-6697613c16f5", "e404ef6a-6bbe-4520-94d9-0528da1a6498", "761b7192-5eb4-42cb-93de-98e0fbdf3e84", "957f288e-11dc-4d19-807e-c2af95f83721", "7ff04ac6-27fb-4c38-9779-044264cf3ac5", "80297f48-75d7-4a96-8f95-2f80a018d357", "8234f464-92f1-4ab7-9f13-dd6b217a9c8e", "b9ad408a-510a-4f36-b269-2baf6d56afd9", "94cb7bac-4c6e-461c-aae9-71570b5fbb5c", "ae097a64-d8bf-45be-93c4-209fd189255d", "a11632cb-dc28-48c4-bfd0-a027cb8290a2", "1a9dc1b4-055b-4aad-9a28-9e1f13108ff0", "a5eafc5f-020e-4af5-a787-ba969dbfbba7", "b6278041-e8d1-48e7-a747-3916d2ec6e77", "91783a52-7ec7-4105-b081-d5c2ee5dfc3c", "dadc6ada-bfd6-4ad8-aac6-1948fada01b5", "c04f6346-16dc-465c-9c28-20b08a113407", "3029480c-2208-45ae-894b-fccbf6909782", "51f66d3f-2827-4049-a689-df79d3b8936e", "8286bbfb-e8d3-4f84-b9ba-d64009e6c096", "9a413646-7cc7-4cdf-8b9c-934358e2bed2", "33ea14d7-f016-475c-9cde-8e622fa1e267", "1e0d949b-4b9b-4ddd-8652-e45316121afd", "77ff6af5-c421-49ae-9117-94e32a04e0ba", "e7ba5e44-dcd7-4084-881e-d7da8ae33bc8", "38dbe0ba-af00-481c-a117-07aa731e8c72", "3dd9505f-040f-4c02-8abd-e97a0c9ed041", "ccaa5d04-9c4b-4687-ba0e-abb17d8384d9", "114dd676-e206-4663-9980-0a42b02a9dbe", "9ead5278-9e15-4a1d-9ceb-3f61ed87179e", "f2a79f95-63bb-45f9-90ab-2510b6a0be8c", "5cedea94-db98-4446-a14a-4c33ba059aed", "1b76488c-27f7-43e4-aa49-76b0e20aaa9a", "db3abcbe-6c91-4f01-ac12-3a240788fb88", "c6f65a9e-632e-4dc4-bdf4-c93c996d0080", "a24c097d-bd39-4c43-86db-3582433ecea6", "42c544c8-f687-4483-ad00-7b239758ff8b", "c747bebf-64ab-4071-bd09-adb61c654808", "b53263ac-8959-486a-ab2c-1394dfbd2c9e", "59199929-1a2f-4737-b167-4d8b271e4daf", "279877c1-ae4a-4420-9d00-488709c5a467", "5161d37f-059e-45e8-af51-cd05d5f0b42c", "89a0441e-aaa4-4184-936f-a6044aed1c7b", "12144c6b-7f3e-44ac-ace8-8ae2ad733019", "b6976e9a-933b-474c-a762-49088acaa89d", "00711b5a-8a79-409b-b2b8-f2feac730753", "7f5b6bbb-0787-4d81-a7f3-acd6d0154d9e", "c6ba78b3-3721-4806-a99b-81cb6a84c0fe", "313ce417-002e-4bfc-a0d3-51a02db954ae", "b846c281-5f09-48bf-bff6-b1c17bded5de", "26d2a7ed-6463-405b-a7ed-2ad534c5a2c9", "f8767869-dec8-4560-815a-594d802199bb", "a3d894cd-9d6d-44b7-a6db-51f19f7c49ea", "81e29f0c-5e9f-4330-9d95-305e99b11d89", "e7a2d4cc-c68c-4578-900a-9100e1354572", "b1a011d9-eae2-49ad-9f6e-da3a23742a4e", "1af94933-42d8-4e5d-9795-c244721d3af7", "8823006c-bfd1-4bf5-afff-0431bfe76b0e", "ba8b7b15-36bf-48ef-8b73-088b7dead062", "7941ed1b-8be9-4a25-a0e2-6ba5aece203a", "2b6cb126-d299-41c2-a4dd-cec9f158a1f2", "2bbb6d63-7585-4c75-a7c5-55fadb72485d", "4e68984a-cdab-444d-b51b-f9c7943590d7", "fd55e3da-7ce1-496a-bdf4-6c748308f963", "98bc233b-64a7-408d-9e24-2b2c5b5292a0", "bd4ee697-e693-4179-89bc-77661aa7f921", "7569d513-d401-404c-9cb2-28a0709da14b", "57afd401-de7d-4ea7-bb5e-f5359b39d5df", "b9eea90d-8da0-4539-ad2a-d0ac94564676", "1d660e59-daf3-4f83-ae09-87bbaad8d13e", "48372347-73ff-4f70-9e1d-b2b52ccb2f8d", "f6be7061-1020-4c05-bf8a-328506fb6e53", "3c8b324a-54ea-4623-b865-ca6c5f756dde", "3a7e9b9f-5638-402c-8eda-148d5bee14a2", "5eb1a769-f344-4979-a861-7ada3b85d2cd", "7dd4be84-f288-4714-9a74-3eb3dc68df88", "c56bcaae-6099-48a5-9157-367ba560fac1", "79406a04-0a14-4397-9bb8-5957301eae7a", "dd0a4ac3-eb5e-4e03-9279-9307dc56cbe2", "ef1bcd54-aa6e-4b05-82af-5f141e378df1", "0e24a6d5-cd1d-445c-a0a6-f6c29c5ded40", "b7ff00db-053d-4282-88d4-b236287e6210", "d6c29198-79e5-4a45-82ab-7de470e8130a", "bd0e70cf-76fb-4397-b8e7-dcedd640903e", "bad75c69-1341-45dc-a1db-1856f079e33b", "72e7555f-a6a2-46b4-9391-7ee3435baa7a", "5d33f1fc-f66b-4a0f-92c8-6cbc277da978", "2c6c0c5e-fec2-47cb-a376-3e61841e6af8", "29135231-e0d7-4db8-bdca-b7ec6b7814cb", "c052a4e5-42ed-48ce-96da-7f6ea101c0fb", "62c22026-1758-4c06-b87e-84b58673646e", "4f6cf95a-ea46-4067-85c4-52b92605314d", "ddfec6ff-9725-48ed-b3ed-60d00cdff519", "029e51a6-02b5-47c2-bfb9-27f3490a1097", "fc5b882b-be8a-4f89-ac8d-8110ea660bbe", "86e4fe72-21ba-458c-85af-c915655eca9c", "4c5043e5-827f-4f6c-97e2-9a126c73ab78", "aa432014-547d-4079-81fb-a26ce29d2510", "c61cacd0-01c5-41b2-83f1-c218d3c17b8a", "3d0eddc4-33f3-42fe-a7d4-41671cf88709", "c2f35e8e-6188-4615-b9ef-f4fae853fba9", "df04bb42-db14-4c97-be74-4b14af8ad8b0", "25a0750a-5332-4e1b-ab7f-e73cd7684546", "49860e32-75b9-47f6-8e5e-3d3ba7152ecf", "31b8b84f-91e5-42a3-a602-0f851b0adb44", "15b8c327-dcf0-46bb-9db9-18f9e3674c99", "d44f43a4-9f68-4c44-a2ee-164fef09ae55", "02578c29-a150-4f60-b5cd-4185cf213728", "84b5b663-cc55-4688-8f2f-70fa7c14c916", "fffa1402-2500-405f-b6f0-6c4f5ccec3d0", "214629e0-86f2-4aaa-bf39-e44b15d3c53c", "b0f1f3a9-7c2b-42c0-a87d-54eb36cd5607", "68ee8eb4-2209-4714-ab1d-9402a63307e4", "4ce13385-788d-445f-bb41-d0b1f1848074", "3ef0de7d-ce11-4908-a99a-f4db80ba58ce", "0da26eb9-4639-46db-9c24-8af0ecb4bec8", "f57ec8f5-572d-44ba-bf3d-bc7b773e5df5", "1d204955-c30d-4343-a01c-6f11d7c5dd91", "21670bb9-208b-486f-ae06-e7a63efec897", "4b535a10-61a3-489e-8c4d-9108abc8d3a2", "62913102-15b8-41a2-b7cb-1dcb8b176cd3", "b68ce93c-858b-4698-accf-b49964a8640a", "f7872af4-12a0-498d-8143-43082a917e6b", "7178af26-5b52-42b4-9b92-1ce28acd4627", "68963434-8b57-42d6-861f-e9b05d29e567", "ec6137c3-e2fd-4ca8-b15c-fd2c9a69fa21", "c2a4600c-28a7-4918-8d76-3e22545873e7", "5d05b615-4294-414d-b296-d137196a020a", "9aef41f5-d423-4c9c-9c87-04c0bca71cdc", "bac0eedc-e666-4f3d-b3c3-d25fcf2feec1", "db592644-3211-4e8b-81a7-2be1264b3f2e", "bde7847a-ffe8-4f91-9e47-1e442b738804", "fe975783-1003-4777-9088-aaab7ccc88aa", "cc851871-7877-4faa-a73e-808ac397a5a9", "4202f1ef-a804-4624-b683-a12c369cfb30", "4c32e2f5-0741-4150-bdb4-082d328fe349", "df240f1e-462a-46ac-947f-1f9214f23d42", "cfb4f8f6-0b74-4ca6-b240-14a72d7850e2", "2bd6d55e-f1fa-4706-a6e9-5376b946418a", "8e8ff6c9-8ba3-4875-bf42-4aa6b02ccdd5", "42ba2c40-b1f9-49db-99f7-2608629056ff", "65fdecf5-65bb-4b0d-bdd8-c4c4337a09a9", "3fe90e72-302f-461f-a1b3-625324f60aa9", "862028db-4302-44bc-b8f4-a885be6b6e28", "b06232e5-a35e-4514-9904-fb2e219a0fa8", "8d18391f-08fa-4ed5-951a-37d41849f761", "8944d7ef-c382-4c3c-abcd-01e50b88f445", "c7e6a3ff-4906-4257-b6ef-6d17c45c577d", "3d61e0a5-f870-4c6e-b404-8a66184b6c70", "89d2787c-f1ee-45f8-b072-41500f5f78f4", "f2fe7e01-3569-4e75-ad75-edb438a5119f", "420dd2d1-1302-488f-9472-b0674f04fa10", "281c53f4-9235-4384-9acb-8814b8a363e4", "51b1512f-90a3-48eb-a8a6-e9383d5a9f72", "20c415be-8d7f-4926-9db8-0d041fc3524a", "a95ee634-eb36-406e-8573-caeae3eb112a", "d4e01ad8-0808-45ec-8f36-51a141d460a8", "14e95537-0184-4156-8852-ee2ecef7deec", "fc48b8df-053d-484b-9e59-a6515bb1d3f2", "409984b3-87f8-4ca3-998c-79532b60cb9a", "8f37f90d-a6f2-4bd1-be39-96cf9c50b4dd", "a6069845-0e6c-450f-ae21-871ffa4a6a18", "d3d25c07-3ac0-43c5-a59a-12346bca9276", "19262cee-b80e-4477-9e3c-de9100750cdb", "3ddff211-90e6-4526-88b0-211499fea06f", "0a0262de-14a2-4267-8c15-4d6a261f693d", "a7b5144e-8997-49c0-b5dd-c2257d614c98", "a763ac22-24e3-4762-93a9-dcac5b7934f5", "b112483f-e4c1-41a4-8aa9-08731a727b2b", "d08cd7f1-4b44-43fb-a6ae-256eb560d6b6", "432249e5-44cb-4746-8023-55b8abda508f", "b01688fd-d6b6-4686-9387-d020de39579e", "b1a90fe5-6bde-4a89-8aa3-652579f43626", "9038a200-536d-44ba-bf7b-4dae94f0fb9d", "c7d371a4-2a37-4b43-8fb0-f50df7e19af2", "59a43b80-3ae9-46fd-b4d3-3b66e5a58ea0", "77928fd9-734d-450f-b48b-919518602c20", "c7c1a425-ac2f-4164-a52c-8093cd2e7e1a", "9a95e9e5-9679-4f2e-9e6b-01fd5f59ddda", "c9f8b7cf-8250-480e-80fe-61913cee6452", "8a1673ac-28ae-4403-aae1-2351f8a26252", "955b2134-eb87-4862-abfd-4e5a56dead3b", "c4d781ab-a9dd-40f3-90a0-055db34b1d96", "89d3a8ba-f5ab-4d23-89a4-ce2d5a0a3eb3", "7e72e307-3499-4c38-8136-d5dfb0bb1c4e", "b11c96ef-c4b0-4411-b9df-b5518ccdf3ed", "cd6efdf3-5f30-4e5a-94ac-03490bc5452a", "53cf99da-cf14-4119-8e6a-40704376c368", "5fb9dd52-3111-4c0a-ba16-cf699683e63a", "47bd9dbc-c2a9-4954-9b1d-7e2783edf3d7", "24bda306-5a08-417d-8486-3958796c69c2", "828a42aa-6a4b-4504-b8a3-64abd8c68028", "8f6b3f27-f47e-4cc9-bd93-a17cf3171968", "e9f1089b-762b-4a38-9f09-e07398ca6434", "b0d78cb4-cb6a-4614-83c3-9bf44b83a98c", "c926b8cd-8cf4-4ba0-9623-767627b26b20", "132074f2-ed74-4cbf-84ef-f1a96378e9b3", "625ad114-dbd2-46ab-bcfc-33723fd8a49b", "67305d12-decc-4d07-9b1f-992d9d7f5231", "642da41e-867d-4694-a2c8-466c41a27dac", "77db3918-7f14-4935-b3bc-8b44d839fd7c", "8a3823f0-3759-43cd-8194-696daba92370", "07ee3c8e-243b-46ce-998a-441513c35158", "02c8b381-b312-403d-8909-c9da25a3acdd", "2e7a0502-cac5-41d8-89d4-1979be7a7909", "d84c1e84-9e3e-404f-a723-10fd71c65522", "4916a4ef-0fba-4d4f-8291-7277b2e0d743", "1118720e-617b-4804-93ef-ec451a064a7c", "76fece4f-aee5-425d-aae0-24f002d2e0d2", "0e7ae961-c0a3-44ad-a1a2-8a4e5cd8f033", "8774be5e-0dca-4334-8014-4b3e8f7d43c9", "9492c730-1b8c-4c95-964d-9713268f915a", "8b1e8303-0a89-4aa4-acde-106dca5de7f5", "dbbcefaa-d74e-4f5d-8578-b5fa134797e2", "b45ec416-9238-4669-be01-0367f1a4a8a2", "d11404f2-1395-420c-9b9d-6c2cdf4aaa4b", "33fbd89c-6711-4323-95e1-0ded06e9ecd6", "6931d179-d062-4cd3-a00c-bbfef3ec1f81", "500963ef-e125-4259-bc1b-08a378a8ce38", "5d9cd1fd-2d42-47d5-9fa9-5a4b67418bae", "0619d480-9552-427c-bd83-ff6e5d398d4f", "e974a298-1f1f-43de-b306-b88b1ad6a297", "941b5b4e-d244-48f2-b29d-09a818637f2d", "85d1dbf7-3646-4802-9a00-c3a83576ec0e", "d73b8408-2e82-4b02-8ca1-e7ad2fa53a0b", "4ab2410d-f66b-4457-9698-ac501cec7a52", "c7c13409-a26f-4e16-93cd-7026bc7becf5", "b77c8e35-c9fe-4cd1-8dd3-8fbab2f0f680", "026015cf-9b2b-4ab1-a92c-dfe183098c8d", "78c64a3e-219a-47f2-b9d7-6d99415e0cd6", "772e8bb5-6f16-4dc4-86a6-464463a86735", "1a50e1b4-b37e-4e70-a31b-189c52dcfa4f", "a530c33d-9b30-40b9-93be-8872e06460a5", "68b42065-7625-4ebd-9aa8-e10953d55c6c", "2e5a4f4d-178a-458b-b55f-1e8dd3cb382e", "68f94932-6966-4d3a-b66e-01769e973b33", "53457520-a858-45aa-a3e4-d0e5b32eae77", "8d691c27-28db-4066-a9ff-e1c122c14223", "23f2316c-3548-4f2a-bcbf-7426c3b7a747", "8060a5fc-b629-42c4-9c37-a3ed220501b4", "0b75cb36-5d00-4de5-806e-8d92743bff15", "22278ed0-9884-4323-8b0d-0cb9d1f981e5", "7637b299-2f81-455d-8ac9-03d866f70529", "1e7eeeb1-f842-4d52-938e-c4b45a99cd4b", "0fd90dbe-a489-4c64-b6c6-82ae6386d455", "7a2df7b7-8d0b-4c93-ae35-ee11e7cd8764", "72886154-c749-45d8-a74d-5a3380138a02", "68eb4945-0e0a-4444-80e1-0894e926edf9", "9eb722fb-2ade-419d-9ba4-f5c1208b9a7b", "a070ab82-5ac1-4be5-abed-8b1621e7932e", "63183571-7aa8-4b88-9332-7883af8597d0", "81cf86d6-3816-4b44-962d-5e4f4b9f328d", "283b7fd6-b3bb-4349-b185-9dbf97816382", "e5cc63a5-2f57-418c-88c9-db25da81dc7e", "216245e0-0613-4747-ab9d-898badd2aa4d", "5d4e0092-7169-48f8-9841-8d43c8d7202e", "e849344c-3bff-47dd-af4b-cd6794f28f01", "80449740-d241-45e3-b652-aa34e9cef703", "92588bac-0f33-4017-b98b-6cb830362cca", "80553a15-dae6-411b-a8b0-99bd03516794", "dec4aa3a-1526-4240-84e2-49d2c1b63b97", "d1084548-3dce-414c-9b32-bc24208d2011", "9c11759f-c06e-4dc4-8d3e-0b7ef0f681fd", "7bdf3b3c-62e2-48b3-ae32-3f488409e301", "bafeea54-ac0d-4bea-b27a-4dfa63962a33", "2d706eb1-c042-4c10-9e83-d754c45d7177", "75915bb5-8c56-4590-a1f9-a6636ec0557a", "b00b355a-ac8d-446e-9962-e9e0977a3f6c", "728f4ef3-1164-4156-9712-2a452c29b07d", "ec8f0f5e-1cb6-4c51-8485-f300fe6241eb", "ab43e155-ee83-45a6-806f-6f4d10b90451", "d8562495-da4c-425e-97aa-d65e7e597914", "5c5b3213-e8af-4acc-b5cc-201f5ca3566a", "faecb0ee-5caf-48c9-b8fd-a5e68fc37546", "dddefca7-27c3-4199-9aca-eea26a21e9bf", "ba071a3d-77ae-4034-8f2e-047808b9a5f4", "15e5c5b7-e33c-4559-8905-a333ab16ba29", "9aa84889-c700-42c0-9997-e91d6d8e303a", "a9c70c04-b64c-4d59-bd23-abbb76763257", "5f730b71-dc90-49fa-abfb-cb38fd319099", "e115a3fa-73f4-487a-87c3-38bc150fb9f7", "951935b3-f986-471a-968d-1b1ae50560b3", "aa4582a8-243b-4b76-89ec-8022fb738579", "d3d5167d-8b61-491a-b714-368c4a10b97a", "d93d04f3-842b-443a-af45-82b1d6795dbb", "13f7adff-168f-4ba1-98d1-39d091e3bc7f", "9b5b2751-0737-4fcf-960d-a566c0bddc1b", "4f7a5ba4-5dcf-4449-87a7-b3424497f704", "376a83ab-7a15-4575-9291-ec43a7888e97", "33d176ee-42cd-4585-9844-eddeaaaafb84", "811c24e0-acec-4415-ba29-7bd657e9506a", "b076f067-6869-48d3-9fc2-4f32cc0bafe4", "c4e4d379-67ac-433c-9179-141b4a03e102", "0f23d927-da34-4a5b-ada7-6a4eb3cb4b7f", "7c1a4187-2ae5-44ba-a29d-290d5abaf66a", "d28f635f-65b5-42f1-88c2-bc7c47c2d0af", "7a4574db-1bd3-434d-b3ca-1af8d5a51fcd", "387ee47a-918e-4398-bf32-78516883c526", "88821a8e-77ee-4902-b47a-fe5d0d259096", "f66c95b3-5e96-4b7d-95d6-933316981a4a", "c928a92f-6b02-4125-b219-d290aa5a2805", "fad6082f-43c3-4c77-a0d2-ef88cf2c4acb", "0c9eb08d-5548-4462-ae03-53c1a7c985c9", "8d3bfdfa-95a3-4faf-96e4-206a3e13ece2", "59879fcf-8119-448c-a67e-4104e54e30c2", "302571f7-9a0d-4056-9c74-353b217aeba7", "a8de15b0-f545-4066-a86b-da20e4f355f5", "2ae880f1-e9c8-4682-b4f5-623b0963f837", "bbc6114a-4ee6-40e7-8e5c-83ef19e5d82f", "dc7b5fbf-d115-4637-aff9-f526e0eefc11", "ec0fe97f-0d92-4c20-ac37-9ddb97440047", "239fe6e1-c62d-4057-bae0-8649f19d9c0e", "b4b4580e-e1a0-4231-96ad-8acf3ff34eb4", "0fbcdc9c-868d-4ff4-b415-c09985b34955", "59528db6-d718-4a9e-af35-cb3950a850fa", "38c70aec-2955-43db-90c7-e75292d170d1", "90d18395-6aa3-4da4-aabf-b8086e16e545", "57c33edb-891a-470a-9463-9ef0bf86bc4c", "5283069b-cd60-40b3-a2bd-1d67bb799d38", "87132194-f8d8-43ca-a881-0102a7a93f14", "d2ea53a4-c2e5-456e-a438-9dcc82e859f2", "a274e9a8-9008-4227-bcd6-ab5480d4a3fd", "6a923a30-ef5d-4356-b96e-c4c7a1920e95", "773be472-6b78-432f-a22d-f53d718c9acc", "c71c7318-91ff-4ef0-8caa-32fadaf0f6da", "4c9c3711-f666-4a64-8d97-0336a35b5965", "70b3f9c9-3983-4856-8e94-2b02b752d4c7", "9b31a9c1-55bb-4fc8-a5e8-cd63add899a2", "441ac1a0-b5c6-4a98-a467-9634ec89b23c", "0f7b6603-cdaa-43d1-aff3-e5619e8a9342", "5f8d4d34-0d25-477e-bd16-7affde2d39c3", "57c8e81b-ace6-4653-9dbe-3cc5cf7e228e", "a75d213e-0686-4d0a-8b76-7a22c6b5a50b", "714e17b5-0a8c-485f-8037-9be056808618", "6fccc2eb-c233-4095-a668-fb10f8a4d8e5", "814e8384-4b91-4494-bb75-01e58610af8f", "0ba7f108-ce58-4c3d-afe1-1d989728d92e", "9d8bcde3-2479-4e6d-9e2b-892b898f7063", "d3ba431e-2efb-463c-8d87-0d7394ff37f3", "c714847f-da72-4d8e-b25d-25944d7cad20", "6a532577-6780-450b-a8ad-0babdc15ff4d", "1628df89-1822-4e23-8f26-44d609adab43", "0c55c46e-bc71-43c1-b640-7b29c5223e27", "03e92840-6dc1-4e09-b766-9acf9d0ecdf9", "3bc699d5-1571-46f6-b2e0-13e444d4f3c1", "c9bd4422-79cc-449b-b10b-f27a4658b08c", "3873b25a-afe9-46ba-959d-9ebeb038d05e", "bf52f5c9-3039-4ffe-9b41-4c93883162f5", "8abb53c7-02ed-4020-901c-9d0ca1e8801a", "e9cf1820-4d74-4683-b41f-eae7acaa6f85", "ebba746a-37da-46e4-b8a8-413c3aee6a4b", "93e98798-5397-4754-91fb-5c3782bc093d", "d0a0a527-6175-48e5-b9f0-dc3bd0fa2032", "1876d0fe-be79-49ce-ae1e-f09d8a425e6f", "7f2a9a9c-7478-4894-aab7-2935a512d8ff", "0edb9eb0-8918-4adf-96d6-be2b13246e72", "3958b434-1d71-48d4-8a59-36f8ac8f69c2", "834e24ec-7376-4d48-82ac-4add2728414d", "e7e9db9d-0bac-471b-9c49-c872d8c8ae1f", "c3f0a341-02b0-4345-916e-8bc6161b47ef", "43934c2b-9dfa-48c6-90d5-0864cdc3f1ea", "b2e0db00-9a8e-444e-b3f0-ee99ca11e2f3", "9f1bcdb3-a05b-4c3d-9573-bcb258b6c956", "0167a514-0e1b-4dfb-9e58-790c1060c2cf", "2c77d42e-65f3-49a4-bb65-503abdf9c281", "221fa989-dd1b-4b45-bc17-07618f5628cc", "cd7e60d6-c4e7-40cb-8390-3fa412dd353e", "4f63efc9-2ca9-4aa3-af19-eed9f19578eb", "d293d544-a5c3-4403-9c44-21c2d688e1e6", "73dc607c-30fb-4568-9e8e-6918a89e0179", "cf1300c8-4a7c-4728-901c-a179e2fc574d", "8527efee-8b3e-44d2-8891-14bea2173caf"]
for book in fluidids:
e = skillshelves.DBBook.get_or_insert(key_name=book)
e.tagged=2
e.put()
self.response.out.write('put ' + book + "<br />")
# skillshelves.connectToFluidinfo()
# headers, content = fluidinfo.call('GET', '/objects', query=fluidinfoquery)
# for book in content['ids']:
#
# SETS UP NAMESPACES AND THE LIKE IN FLUIDB
#
if page == 'initfluiddb':
template_values["log_list"]= ['starting']
# set up my namespace
skillshelves.connectToFluidinfo()
# result = fluidinfo.call('POST', '/namespaces/' + skillshelves.fluidinfoRootNamespace(), {'description': 'Skills are used for tagging books with topics. The information is then used to build personal skill repertoires on www.skillshelv.es', 'name': 'skills'})
# template_values["log_list"].append(result)
# result = fluidinfo.call('POST', '/tags/' + skillshelves.fluidinfoRootNamespace() + '/skills', {'indexed': True, 'description': 'Used for tagging books with skill levels for building personal skill repertoires on www.skillshelv.es', 'name': 'PHP'})
# template_values["log_list"].append(result)
# result = fluidinfo.call('POST', '/tags/' + skillshelves.fluidinfoRootNamespace() + '/skills', {'indexed': True, 'description': 'Used for tagging books with skill levels for building personal skill repertoires on www.skillshelv.es', 'name': 'jQuery'})
# template_values["log_list"].append(result)
# result = fluidinfo.call('POST', '/tags/' + skillshelves.fluidinfoRootNamespace() + '/skills', {'indexed': True, 'description': 'Used for tagging books with skill levels for building personal skill repertoires on www.skillshelv.es', 'name': 'Data__Science'})
# template_values["log_list"].append(result)
# result = fluidinfo.call('DELETE', '/tags/' + skillshelves.fluidinfoRootNamespace() + '/skills/PHP')
# template_values["log_list"].append(result)
# result = fluidinfo.call('DELETE', '/namespaces/' + skillshelves.fluidinfoRootNamespace() + '/skills')
# template_values["log_list"].append(result)
#
# 404
#
if not os.path.exists('admin/' + page + '.html'):
page = "404"
else:
page = "404"
template_values["page"] = page
template_values["page_filename"] = 'admin/' + page + '.html'
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication([('/administrativa/(.*)', MainPage)],debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,012 |
3,178,275,836,084 |
a7cecb0326928cb382626b390b2aa96fd23701d3
|
fb17d7a0754af8037f93382ffa90fb5374ba467e
|
/maboss/models/label/printer_config.py
|
daa70fdeb19a4e28056ebbda0be2f85441c2ab32
|
[
"MIT"
] |
permissive
|
mabotech/maboss.py
|
https://github.com/mabotech/maboss.py
|
becfd68c05c70ea214ce381d2d3b0e89fac8bb24
|
30c919d09c0a290772dde2f913c51843f0f88e26
|
refs/heads/master
| 2016-09-10T10:53:00.910707 | 2014-07-05T12:18:20 | 2014-07-05T12:18:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Sequence
from sqlalchemy import Column, DateTime, Integer, String, Unicode
from datetime import datetime
from mabolab.database.dbsession import Base
from mabolab.database.model import ColumnMixin
class PrinterConfig(Base, ColumnMixin):
__tablename__ = 'mt_t_printer_config'
id = Column(Integer, primary_key=True) # Sequence('BP_SEQ_MT_T_PRINTER_CONFIG'),
workstation = Column(Unicode(40)) # NVARCHAR2
printer_name = Column(Unicode(40)) # NVARCHAR2
ip_address = Column(Unicode(80)) # NVARCHAR2
spool_address = Column(Unicode(60)) # NVARCHAR2
template_path = Column(Unicode(80)) # NVARCHAR2
def __init__(self, workstation, printer_name, ip_address, spool_address, template_path):
self.workstation = workstation
self.printer_name = printer_name
self.ip_address = ip_address
self.spool_address = spool_address
self.template_path = template_path
self.lastupdatedby = 'MT'
self.createdon = datetime.now()
self.active = 1
self.rowversionstamp = 1
def __repr__(self):
return '<PrinterConfig(%s, "%s","%s","%s")>' % (self.id, self.workstation, self.printer_name, self.ip_address)
|
UTF-8
|
Python
| false | false | 2,014 |
15,461,882,279,556 |
5a1cc539f463ceaacfa3a52162752559e4ede2ba
|
146e4794f224375a1e25ad30a6870e100b72ae1a
|
/tastypie_user_session/__init__.py
|
7582312d66b6a9de1ca6cdbfc8c88593d8b759e3
|
[
"MIT"
] |
permissive
|
bingimar/tastypie_user_session
|
https://github.com/bingimar/tastypie_user_session
|
cffb31afee68869305cf44559a6dfa78bedf5c37
|
f628818acb32c124d6f793884f46cf7bd377fd00
|
refs/heads/master
| 2017-04-21T04:31:26.365827 | 2013-01-07T13:13:09 | 2013-01-07T13:13:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__version__ = "0.4"
from resources import UserSessionResource
from resources import DjangoAuthUserSessionResource
from resources import FacebookAuthUserSessionResource
# Quiet lint warnings
if None:
UserSessionResource
DjangoAuthUserSessionResource
FacebookAuthUserSessionResource
|
UTF-8
|
Python
| false | false | 2,013 |
9,990,093,938,100 |
fc69e9f04d50d8a46f05a492e681e7c4f6637281
|
3474b315da3cc5cb3f7823f19a18b63a8da6a526
|
/scratch/KRAMS/src/apps/scratch/rch/trait_lab/coord.py
|
cc4da5a6c1cbfe9f807a2d7b90733835eb9ed4e5
|
[] |
no_license
|
h4ck3rm1k3/scratch
|
https://github.com/h4ck3rm1k3/scratch
|
8df97462f696bc2be00f1e58232e1cd915f0fafd
|
0a114a41b0d1e9b2d68dbe7af7cf34db11512539
|
refs/heads/master
| 2021-01-21T15:31:38.718039 | 2013-09-19T10:48:24 | 2013-09-19T10:48:24 | 29,173,525 | 0 | 0 | null | true | 2015-01-13T04:58:57 | 2015-01-13T04:58:56 | 2014-02-25T20:48:34 | 2013-09-19T10:48:33 | 42,316 | 0 | 0 | 0 | null | null | null |
#-------------------------------------------------------------------------------
#
# Copyright (c) 2009, IMB, RWTH Aachen.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in simvisage/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.simvisage.com/licenses/BSD.txt
#
# Thanks for using Simvisage open source!
#
# Created on Jan 29, 2010 by: rch
from math import sqrt
from enthought.traits.api import HasTraits, Float, Property
class Coord( HasTraits ):
x = Float( 0.0 )
y = Float( 0.0 )
length = Property( Float, depends_on = 'x,y' )
def _get_length(self):
return sqrt( self.x**2 + self.y**2 )
def __init__(self, **kw):
print kw
super( HasTraits, self ).__init__(**kw)
c = Coord( x = 1.0, y = 2.0 )
c.configure_traits()
|
UTF-8
|
Python
| false | false | 2,013 |
6,399,501,289,767 |
322c30e05799046be4c18f31964311ec689f111e
|
1a56834984180b24a096a8dc8a18e44781a7a7e9
|
/sad.py
|
19b0d44adc66b96d4cf3383efd8f80fc2fd7abbb
|
[
"GPL-3.0-only"
] |
non_permissive
|
SevereOverfl0w/sevabot-modules
|
https://github.com/SevereOverfl0w/sevabot-modules
|
c2dba6c121e269b24e4a5c984107a1db50a4f912
|
22519143a79a10e835fd21899ee9a5217042e925
|
refs/heads/master
| 2021-01-18T17:58:53.959784 | 2014-05-22T05:50:05 | 2014-05-22T05:50:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A simple sample module with Skype smileys
"""
import os
print "/me recommends %s to go kill themself." % os.environ["SKYPE_FULLNAME"]
|
UTF-8
|
Python
| false | false | 2,014 |
77,309,422,633 |
3365356b10235223e2206240096ac284927a37e6
|
bb1444aecad947d18163175a1f7a403fc797ccf8
|
/src/toolbox/sparse_kernel.py
|
f7c99b501b8ff637759a5bed587d0ff996bb37a6
|
[] |
no_license
|
eladnoor/milo-lab
|
https://github.com/eladnoor/milo-lab
|
6e6e5653af7ac79eba38680bb20f88748d4e6e5f
|
b755e90f89abfb330d5e0bcc5c025015e519e8ad
|
refs/heads/master
| 2022-10-29T15:48:23.554977 | 2014-02-05T10:46:21 | 2014-02-05T10:46:21 | 32,138,160 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
from matplotlib import mlab
from toolbox.linear_regression import LinearRegression
try:
from cplex import Cplex
from cplex.exceptions import CplexSolverError
from cplex.callbacks import SolveCallback
except ImportError:
pass
class CplexNotInstalledError(Exception):
pass
class SparseKernel(object):
"""
Finds a sparse representation of the kernel matrix, using MILP
to iterate the Fundamental Modes of the matrix.
Input:
a (n x m) matrix A, whose rank is r.
Return:
a (m x m-r) matrix K that will span the kernel of A, i.e.:
span(K) = {x | Ax = 0}
"""
class LinearProgrammingException(Exception):
pass
def __init__(self, A):
self.upper_bound = 1000
self.eps = 1e-10
self.dimension = 0
try:
self.cpl = Cplex()
except NameError, CplexSolverError:
raise CplexNotInstalledError()
self.cpl.set_problem_name('find_kernel')
self.cpl.set_log_stream(None)
self.cpl.set_results_stream(None)
self.cpl.set_warning_stream(None)
self.n_variables = A.shape[1]
self.CreateAllVariables()
self.constraint_counter = 0
for r in xrange(A.shape[0]):
self.AddLinearConstraint(A[r, :])
self.kernel_rank = self.n_variables - LinearRegression.MatrixRank(A)
def CreateAllVariables(self):
"""
create 4 variables for each column:
positive & negative real values and positive & negative indicators
"""
for col in xrange(self.n_variables):
self.cpl.variables.add(names=['c%d_plus' % col],
lb=[0], ub=[self.upper_bound])
self.cpl.variables.add(names=['g%d_plus' % col], types='B')
# c_plus - M*g_plus <= 0
constraint_name = 'g%d_plus_bound_upper' % col
self.cpl.linear_constraints.add(names=[constraint_name], senses='L', rhs=[0])
self.cpl.linear_constraints.set_coefficients(constraint_name, 'c%d_plus' % col, 1)
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_plus' % col, -self.upper_bound)
# c_plus - g_plus >= 0
constraint_name = 'g%d_plus_bound_lower' % col
self.cpl.linear_constraints.add(names=[constraint_name], senses='G', rhs=[0])
self.cpl.linear_constraints.set_coefficients(constraint_name, 'c%d_plus' % col, 1)
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_plus' % col, -1)
self.cpl.variables.add(names=['c%d_minus' % col], lb=[0], ub=[self.upper_bound])
self.cpl.variables.add(names=['g%d_minus' % col], types='B')
# c_minus - M*g_minus <= 0
constraint_name = 'g%d_minus_bound_upper' % col
self.cpl.linear_constraints.add(names=[constraint_name], senses='L', rhs=[0])
self.cpl.linear_constraints.set_coefficients(constraint_name, 'c%d_minus' % col, 1)
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_minus' % col, -self.upper_bound)
# c_minus - g_minus >= 0
constraint_name = 'g%d_minus_bound_lower' % col
self.cpl.linear_constraints.add(names=[constraint_name], senses='G', rhs=[0])
self.cpl.linear_constraints.set_coefficients(constraint_name, 'c%d_minus' % col, 1)
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_minus' % col, -1)
# g_plus + g_minus <= 1
constraint_name = 'g%d_bound' % col
self.cpl.linear_constraints.add(names=[constraint_name], senses='L', rhs=[1])
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_plus' % col, 1)
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_minus' % col, 1)
all_gammas = ['g%d_plus' % col for col in xrange(self.n_variables)] + \
['g%d_minus' % col for col in xrange(self.n_variables)]
# Set the objective function: minimizing the sum of gammas
self.cpl.objective.set_linear([(g, 1) for g in all_gammas])
# Exclude the trivial solution (all-zeros)
self.cpl.linear_constraints.add(names=['avoid_0'], senses='G', rhs=[1])
for g in all_gammas:
self.cpl.linear_constraints.set_coefficients('avoid_0', g, 1)
def AddLinearConstraint(self, v, rhs=0):
v = np.reshape(v, (1, self.n_variables))
# add the linear constraint v*x = rhs
constraint_name = 'r%d' % self.constraint_counter
self.constraint_counter += 1
self.cpl.linear_constraints.add(names=[constraint_name], senses='E', rhs=[rhs])
for col in xrange(self.n_variables):
if v[0, col] != 0:
self.cpl.linear_constraints.set_coefficients(constraint_name,
'c%d_plus' % col, v[0, col])
self.cpl.linear_constraints.set_coefficients(constraint_name,
'c%d_minus' % col, -v[0, col])
def GetSolution(self):
try:
self.cpl.solve()
except CplexSolverError as e:
raise SparseKernel.LinearProgrammingException(str(e))
sol = self.cpl.solution
if self.cpl.solution.get_status() != SolveCallback.status.MIP_optimal:
raise SparseKernel.LinearProgrammingException("No more EMFs")
g_plus = np.array(sol.get_values(['g%d_plus' % col for col in xrange(self.n_variables)]))
g_minus = np.array(sol.get_values(['g%d_minus' % col for col in xrange(self.n_variables)]))
coeffs = np.array(sol.get_values(['c%d_plus' % col for col in xrange(self.n_variables)])) - \
np.array(sol.get_values(['c%d_minus' % col for col in xrange(self.n_variables)]))
return g_plus, g_minus, coeffs
def ExcludeSolutionVector(self, g_plus, g_minus, constraint_name):
self.cpl.linear_constraints.add(names=[constraint_name], senses='L')
nonzero_counter = 0
for col in xrange(self.n_variables):
if g_plus[col] > 0.5:
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_plus' % col, 1)
nonzero_counter += 1
elif g_minus[col] > 0.5:
self.cpl.linear_constraints.set_coefficients(constraint_name, 'g%d_minus' % col, 1)
nonzero_counter += 1
self.cpl.linear_constraints.set_rhs(constraint_name, nonzero_counter-1)
def __len__(self):
return self.kernel_rank
def __iter__(self):
self.dimension = 0
self.emf_counter = 0
self.K = np.zeros((len(self), self.n_variables))
return self
def next(self):
if self.dimension == len(self):
raise StopIteration
while True:
self.emf_counter += 1
g_plus, g_minus, coeffs = self.GetSolution()
self.ExcludeSolutionVector(g_plus, g_minus, 'avoid_%d_plus' % self.emf_counter)
self.ExcludeSolutionVector(g_minus, g_plus, 'avoid_%d_minus' % self.emf_counter)
nonzero_indices = np.nonzero(g_plus > 0.5)[0].tolist() + np.nonzero(g_minus > 0.5)[0].tolist()
self.K[self.dimension, nonzero_indices] = coeffs[nonzero_indices]
if LinearRegression.MatrixRank(self.K) < self.dimension+1:
self.K[self.dimension, :] = 0
else:
# normalize the kernel vector so that it will have nice coefficients
g = min(abs(coeffs[nonzero_indices]))
self.K[self.dimension, :] /= g
#if sum(self.K[:, self.dimension] < 0.0):
# self.K[:, self.dimension] *= -1.0
v = self.K[self.dimension, :]
self.AddLinearConstraint(v)
self.dimension += 1
return v
def Solve(self):
if self.dimension == 0:
for _ in self:
pass
return self.K
if __name__ == '__main__':
A = np.array([[1, 0, 1, 1, 2, 1, 1],[0, 1, 1, 1, 2, 1, 1],[1, 1, 2, 2, 4, 2, 2]])
K = SparseKernel(A)
print A
for v in K:
print "nullvector: ", ', '.join(['%g' % x for x in v])
print "RMS(A*K.T) =", mlab.rms_flat(np.dot(A, K.Solve().T))
|
UTF-8
|
Python
| false | false | 2,014 |
18,940,805,788,961 |
533219b4130e24605ebc0e3b76eb88dc6168bd45
|
b5d2895678cb380fe5816f42eec02a5060c71376
|
/myadd.py
|
2970de0b702e1ee272d47e3024a456b86093dbe0
|
[] |
no_license
|
cbitra/tmpo
|
https://github.com/cbitra/tmpo
|
08aabed4c15f16a25516f9097f7c6ee1ae149783
|
0311203042f0e21281790e2d2fb0104c565712cf
|
refs/heads/master
| 2020-06-02T01:37:10.017712 | 2013-11-22T14:20:12 | 2013-11-22T14:20:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/local/bin/python
print("Enter a number: ")
num1 = int(raw_input())
print("Enter the 2nd number: ")
num2 = int(raw_input())
print("Sum of numbers " + str(num1+num2))
print("Program executed successfully.")
|
UTF-8
|
Python
| false | false | 2,013 |
10,720,238,383,607 |
aed850bd30cf099fd8c8eed6a53005f7680f0f34
|
6ddcb131e5f2806acde46a525ff8d46bfbe0990e
|
/enaml/core/operators.py
|
186c879c7fe741b12640da04052ac91f05c5e1a1
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
non_permissive
|
agrawalprash/enaml
|
https://github.com/agrawalprash/enaml
|
5ce1823188eb51e5b83117ebee6c3655f53e5157
|
96828b254ac9fdfa2e5b6b31eff93a4933cbc0aa
|
refs/heads/master
| 2021-01-15T23:35:21.351626 | 2012-09-05T03:40:07 | 2012-09-05T03:40:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#------------------------------------------------------------------------------
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from .expressions import (
SimpleExpression, NotificationExpression, SubscriptionExpression,
DelegationExpression, UpdateExpression,
)
from .inverters import (
GenericAttributeInverter, GetattrInverter, ImplicitAttrInverter,
)
from .monitors import TraitAttributeMonitor, TraitGetattrMonitor
#------------------------------------------------------------------------------
# Builtin Enaml Operators
#------------------------------------------------------------------------------
#: Operators are passed a number of arguments from the Enaml runtime
#: engine in order to perform their work. The arguments are, in order:
#:
#: cmpnt : BaseComponent
#: The BaseComponent instance which owns the expression which
#: is being bound.
#:
#: attr : string
#: The name of the attribute on the component which is being
#: bound.
#:
#: code : types.CodeType
#: The compiled code object for the Python expression given
#: given by the user. It is compiled with mode='eval'.
#:
#: identifiers : dict
#: The dictionary of identifiers available to the expression.
#: This dictionary is shared amongs all expressions within
#: a given lexical scope. It should therefore not be modified
#: or copied since identifiers may continue to be added to
#: this dict as runtime execution continues.
#:
#: f_globals : dict
#: The dictionary of globals available to the expression.
#: The same rules about sharing and copying that apply to
#: the identifiers dict, apply here as well.
#:
#: toolkit : Toolkit
#: The toolkit instance that is in scope for the expression.
#: The same rules about sharing and copying that apply to
#: the identifiers dict, apply here as well.
#:
#: Operators may do whatever they please with the information provided
#: to them. The default operators in Enaml use this information to
#: create and bind Enaml expression objects to the component. However,
#: this is not a requirement and developers who are extending enaml
#: are free to get creative with the operators.
def op_simple(cmpnt, attr, code, identifiers, f_globals, toolkit):
""" The default Enaml operator for '=' expressions. It binds an
instance of SimpleExpression to the component.
"""
expr = SimpleExpression(cmpnt, attr, code, identifiers, f_globals, toolkit)
cmpnt.bind_expression(attr, expr)
def op_notify(cmpnt, attr, code, identifiers, f_globals, toolkit):
""" The default Enaml operator for '::' expressions. It binds an
instance of NotificationExpression to the component.
"""
expr = NotificationExpression(cmpnt, attr, code, identifiers, f_globals, toolkit)
cmpnt.bind_expression(attr, expr, notify_only=True)
def op_update(cmpnt, attr, code, identifiers, f_globals, toolkit):
""" The default Enaml operator for '>>' expressions. It binds an
instance of UpdateExpression to the component.
"""
inverters = [GenericAttributeInverter, GetattrInverter, ImplicitAttrInverter]
expr = UpdateExpression(inverters, cmpnt, attr, code, identifiers, f_globals, toolkit)
cmpnt.bind_expression(attr, expr, notify_only=True)
def op_subscribe(cmpnt, attr, code, identifiers, f_globals, toolkit):
""" The default Enaml operator for '<<' expressions. It binds an
instance of SubscriptionExpression to the component using monitors
which understand traits attribute access via dotted notation and
the builtin getattr function.
"""
monitors = [TraitAttributeMonitor, TraitGetattrMonitor]
expr = SubscriptionExpression(monitors, cmpnt, attr, code, identifiers, f_globals, toolkit)
cmpnt.bind_expression(attr, expr)
def op_delegate(cmpnt, attr, code, identifiers, f_globals, toolkit):
""" The default Enaml operator for ':=' expressions. It binds an
instance of DelegationExpression to the component using monitors
which understand traits attribute access via dotted notation and
the builtin getattr function, and inverters which understand the
dotted attribute access, implicit attribute access, and also the
builtin getattr function.
"""
inverters = [GenericAttributeInverter, GetattrInverter, ImplicitAttrInverter]
monitors = [TraitAttributeMonitor, TraitGetattrMonitor]
expr = DelegationExpression(inverters, monitors, cmpnt, attr, code, identifiers, f_globals, toolkit)
cmpnt.bind_expression(attr, expr)
OPERATORS = {
'__operator_Equal__': op_simple,
'__operator_LessLess__': op_subscribe,
'__operator_ColonEqual__': op_delegate,
'__operator_ColonColon__': op_notify,
'__operator_GreaterGreater__': op_update,
}
|
UTF-8
|
Python
| false | false | 2,012 |
13,357,348,308,408 |
8304866d8cd5fcf2400358b47cb96c1bdd973e9f
|
b4428434d76e2db58c165e6caaf3cd92b569cf5f
|
/branches/horaciobranch/test/testGrid.py
|
133bddc7f96b050301fb8fef8fc1765beebca66c
|
[
"GPL-2.0-only",
"GPL-2.0-or-later"
] |
non_permissive
|
BackupTheBerlios/cimarron-svn
|
https://github.com/BackupTheBerlios/cimarron-svn
|
50d0e21cfdfc6f68d39aca8f2086461aa87971e1
|
2f2aadfc8c75bcb1963055a74d9fa504938d85f9
|
refs/heads/master
| 2020-07-01T02:46:00.364417 | 2005-08-19T18:58:49 | 2005-08-19T18:58:49 | 40,607,561 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
#
# Copyright 2005 Fundación Via Libre
#
# This file is part of PAPO.
#
# PAPO 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.
#
# PAPO 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
# PAPO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA 02111-1307 USA
import unittest
from fvl import cimarron
from model.person import Person
from fvl.cimarron.model.base import Model
from testCommon import abstractTestControl
__all__= ('TestSelectionGrid', 'TestGrid')
class DummyTarget (Model):
def __init__ (self, dummy):
self.dummy= dummy
class TestGrid (abstractTestControl):
def setUp (self):
super (TestGrid, self).setUp ()
self.list= [
Person ('jose', 'perez'),
Person ('marcos', 'dione'),
Person ('john', 'lenton'),
]
columns= (
cimarron.skin.Column (name='Nombre', read=Person.getName, write=Person.setName),
cimarron.skin.Column (name='Apellido', read=Person.getSurname, write=Person.setSurname),
)
self.parent = self.win = cimarron.skin.Window(title='Test', parent=self.app)
self.widget= self.grid= cimarron.skin.Grid (
parent= self.parent,
columns= columns,
klass= Person,
)
target= DummyTarget (self.list)
self.setUpControl (target=target, attr='dummy')
def testIndex (self):
for i in xrange (len (self.widget.value)):
self.widget.index= i
self.assertEqual (self.widget.index, i)
self.assertEqual (self.value[i], self.widget.value[i])
def testWrite (self):
self.widget._cell_edited (None, 0, 'juan', 0)
self.widget.index= 0
try:
self.assertEqual (self.widget.value[0].name, 'juan')
except (TypeError, IndexError):
self.assertEqual (self.widget.new.name, 'juan')
def testValueIsTargetWhenNoAttr (self):
self.target= self.list
super (TestGrid, self).testValueIsTargetWhenNoAttr ()
class TestSelectionGrid (abstractTestControl):
def setUp (self):
super (TestSelectionGrid, self).setUp ()
self.list= [
Person ('jose', 'perez'),
Person ('marcos', 'dione'),
Person ('john', 'lenton'),
]
columns= (
cimarron.skin.Column (name='Nombre', read=Person.getName, write=Person.setName),
cimarron.skin.Column (name='Apellido', read=Person.getSurname, write=Person.setSurname),
)
self.parent = self.win = cimarron.skin.Window(title='Test', parent=self.app)
self.widget= self.grid= cimarron.skin.SelectionGrid (
parent= self.parent,
columns= columns,
data= self.list,
)
target= DummyTarget (self.list[0])
self.setUpControl (target=target, attr='dummy')
def testIndex (self):
for i in xrange (len (self.list)):
self.widget.index= i
self.assertEqual (self.list[i], self.widget.value)
def testValue (self):
for i in xrange (len (self.list)):
self.widget.value= self.list[i]
self.assertEqual (self.list[i], self.widget.value)
def testNoValue (self):
self.widget.data = []
self.widget.value= None
self.assert_ (self.widget.value is None)
def testValueIsTargetWhenNoAttr (self):
self.setUpControl (target=self.list[0], attr=None)
self.widget.index= 0
super (TestSelectionGrid, self).testValueIsTargetWhenNoAttr ()
def testNoTarget (self):
self.setUpControl (target=None, attr=None)
self.testIndex ()
self.testValue ()
|
UTF-8
|
Python
| false | false | 2,005 |
429,496,753,312 |
d29b2bd83ac1927b5e3d31af538100160272f272
|
60032246cd71274d3443b058d4bede1d67498610
|
/pollxblock/__init__.py
|
d89ee50964ea068c2b52890974131228a2dfeb2f
|
[
"AGPL-3.0-only"
] |
non_permissive
|
nttks/pollxblock
|
https://github.com/nttks/pollxblock
|
e3d63166e80487153e82c0bfb144c1a5e02ae02d
|
d6addee361056db84037c64dbd1081386c98f706
|
refs/heads/master
| 2022-05-04T21:34:55.974521 | 2014-08-27T06:36:36 | 2014-09-10T04:08:59 | 23,607,630 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from .pollxblock import PollXBlock
|
UTF-8
|
Python
| false | false | 2,014 |
1,486,058,688,136 |
2c7c8b95808439bbbca0cf1d2e76232c32bbf464
|
5f566b468ad4beed13f78a6b3c670075bc5007df
|
/euler_p2.py
|
e32c11434446aa1c020ce0b10272eacc397f5c22
|
[] |
no_license
|
paulknepper/project_euler
|
https://github.com/paulknepper/project_euler
|
ed72c24021682c7fa5cacb0ec7d94948cbf43789
|
c310970d314225542522d70c0c7242b3c7526941
|
refs/heads/master
| 2021-01-01T16:13:12.658191 | 2013-03-28T03:12:00 | 2013-03-28T03:12:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# euler_p2.py
"""
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, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
"""
def main():
sums, num, ct = 0, 0, 0
while num <= 4000000:
num = fib2(ct)
sums += num if num % 2 == 0 else 0
ct += 1
print(sums)
def fib(num): # takes too long to compute...
a, b = 1, 2
for i in range(num):
a, b = b, a + b
return a
def fib2(num):
if num < 1: return 1 # Make this num < 2 to get real fibo sequence
else: # for loop pointless here because of use of return in loop;
# probably true for a lot of recursive functions
return fib2(num - 1) + fib2(num - 2)
if __name__ == '__main__': main()
|
UTF-8
|
Python
| false | false | 2,013 |
15,315,853,405,466 |
53ed3b2af5dc52538ddc796e2b586dc988d47d04
|
a1a406099ca56280e89e7154bcd47653c69841fa
|
/euler34.py
|
8c8e7580351d07dc795610dba3a28bd1cb64c35c
|
[] |
no_license
|
rudasi/euler
|
https://github.com/rudasi/euler
|
004464784196f7a568e9db2d851ab8dad73710fe
|
33327c34804701ee98a3b066c65ee5205d99d406
|
refs/heads/master
| 2016-09-06T04:18:14.950159 | 2014-11-21T23:31:04 | 2014-11-21T23:31:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
factorial = {"0":1,"1":1,"2":2,"3":6,"4":24,"5":120,"6":720,"7":5040,"8":40320,"9":362880}
def factorial_digit():
total = 0
for val in range(10,10000000):
val = str(val)
temp = 0
for digit in val:
temp += factorial[digit]
if (str(temp) == val):
print temp
total += int(temp)
return total
if __name__ == "__main__":
answer = factorial_digit()
print answer
|
UTF-8
|
Python
| false | false | 2,014 |
5,927,054,921,596 |
d4e81cd408e68251537cd7e90cad28d01999260d
|
8b98d44c78b06f64f1b9aecb5f067aff5a9fe198
|
/visualizer/csvReader1.py
|
cbfa853bed8c681467d51be8e183c0610b6f089a
|
[] |
no_license
|
arcolife/datahack
|
https://github.com/arcolife/datahack
|
a1f4ac8c37fd8e7f05566335673a23597abc71f5
|
a31203c73d2b63c93eba4b70f085589694996191
|
refs/heads/master
| 2021-01-19T14:09:52.788962 | 2014-07-01T08:08:14 | 2014-07-01T08:08:14 | 17,537,187 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import csv
#import geonamescache
#gc = geonamescache.GeonamesCache()
a=[]
#dt={'state':('year','number')}
with open('Neo-Natal_Mortality_Rate.csv', 'rb') as myFile:
reader = csv.reader(myFile, delimiter=',', quotechar='|')
for row in reader:
print row[0] + '\t' + row[1] + '\t' + row[2] + ' \t' + row[3] + ' \t' + row[4] + '\t' + row[5] + ' \t' + row[6]+ ' \t' + row[7] + '\n'
a.append(row[1])
print a
|
UTF-8
|
Python
| false | false | 2,014 |
12,799,002,573,589 |
eb6e369eec6fe51c747017d56f55b3a430091980
|
d7aca4d282afec8ae0e118a51aa7e7b06a32f7ff
|
/bark-web.py
|
67490283e0d8d1c7b21273b1635869be3ad77f40
|
[] |
no_license
|
rzhw/bark-web
|
https://github.com/rzhw/bark-web
|
9c1b0f9b5d5a3fcc6055d64993c3ada363561a8a
|
f09126263056cd557af29c4a38dff2246cd1a5ed
|
refs/heads/master
| 2021-01-18T00:47:30.114814 | 2013-02-24T06:42:51 | 2013-02-24T06:42:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import requests, json,pprint
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
#Auth
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
url = app.config['api_url'] + 'login'
request_headers = {
'Content-Type': 'application/json',
'xhrFields' : {
'withCredentials': True,
}
}
request_data = {
'username' : request.form['username'],
'password' : request.form['password'],
}
response = requests.post(url,data=json.dumps(request_data),headers=request_headers)
r = response.json()
if r['status'] != 'OK':
error = r['error_detail']
else:
session['auth_token'] = r['auth_token']
flash('You were logged in')
return redirect(url_for('events'))
return render_template('login.html', error=error)
@app.route('/logout', methods=['GET'])
def logout():
url = app.config['api_url'] + 'logout'
request_headers = {
'Content-Type': 'application/json',
'xhrFields' : {
'withCredentials': True,
}
}
request_data = {
'auth_token' : session['auth_token'],
}
response = requests.post(url,data=json.dumps(request_data),headers=request_headers)
session.pop('auth_token', None)
flash('You were logged out')
return redirect(url_for('login'))
#Events
@app.route('/events/<int:event_id>/edit', methods=['GET', 'POST'])
def edit_event(event_id):
return 'edit'
@app.route('/events/<int:event_id>/delete', methods=['GET'])
def delete_event(event_id):
url = app.config['api_url'] + 'events/'+ str(event_id)
request_headers = {
'Content-Type': 'application/json',
'xhrFields' : {
'withCredentials': True,
},
'auth_token' : session['auth_token'],
}
response = requests.delete(url,headers=request_headers)
r = response.json()
if r['status']!= 'OK':
flash('Not deleted')
else:
flash('Deleted')
return redirect(url_for('events'))
@app.route('/events/<int:event_id>', methods=['GET'])
def show_event(event_id):
url = app.config['api_url'] + 'events/'+ str(event_id)
request_headers = {
'Content-Type': 'application/json',
'xhrFields' : {
'withCredentials': True,
},
'auth_token' : session['auth_token'],
}
response = requests.get(url,headers=request_headers)
r = response.json()
if r['status']!= 'OK':
error = r['error_detail']
return render_template('events_not_found.html', error=error)
else:
event = r['event']
return render_template('events_view.html', event=event)
@app.route('/events/')
def events():
url = app.config['api_url'] + 'events'
request_headers = {
'Content-Type': 'application/json',
'xhrFields' : {
'withCredentials': True,
},
'auth_token' : session['auth_token'],
}
response = requests.get(url,headers=request_headers)
r = response.json()
events = r['events']
return render_template('events.html', events=events)
@app.route('/events/add', methods=['GET', 'POST'])
def add_event():
error = None
if request.method == 'POST':
url = app.config['api_url'] + 'events'
request_headers = {
'Content-Type': 'application/json',
'xhrFields' : {
'withCredentials': True,
},
'auth_token' : session['auth_token'],
}
request_data = {
'description' : request.form['description'],
'name' : request.form['name'],
'start_time' : request.form['start_time'],
'end_time' : request.form['end_time'],
'group_id' : int(request.form['group_id']),
}
response = requests.post(url,data=json.dumps(request_data),headers=request_headers)
r = response.json()
if r['status'] != 'OK':
error = r['error_detail']
else:
return redirect('/events/' + str(r['event_id']))
return render_template('events_add.html', error=error)
#Groups
if __name__ == '__main__':
app.debug = True
app.secret_key = 'aslkdjf;lsakdjf;alksdjf;lkj'
app.config['api_url'] = 'http://localhost:5000/'
app.run(port=4444)
|
UTF-8
|
Python
| false | false | 2,013 |
18,253,611,010,071 |
a1baa9e70721c9a627fb36bd93de8b9ad7c332b0
|
4b5fd3298d979bc7c1aa68ec4dfeb2250d2462d6
|
/track.py
|
9d845a71e8354aafdec519bf11c0b73e2d0ecd3b
|
[] |
no_license
|
StochSS/iptracker
|
https://github.com/StochSS/iptracker
|
eb9cfae2326c15f4635f783439f9f2fd1d3f596b
|
93d0ec8eacad63743ef86394ee1f370b6472e2f4
|
refs/heads/master
| 2018-05-03T01:15:37.908979 | 2013-06-26T16:06:09 | 2013-06-26T16:06:09 | 9,180,198 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import sys,os
class MainPage(webapp.RequestHandler):
USERNAME = '[email protected]' # enter the username of Google Doc Account
PASSWORD = '' # password of Google Doc Account
DOCKEY = '0AkxD-4ZfvuOAdE9NaV9pbjhvU3ZWY3REaUxaNXRuU3c' #docid of the shared google doc sheet
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
def post(self):
ip = self.request.get('ip')
time = self.request.get('time')
region = self.request.get('region')
import gspread
# Login with your Google account
gc = gspread.login(self.USERNAME, self.PASSWORD)
# Open a worksheet from spreadsheet with one shot
wks = gc.open_by_key(self.DOCKEY).sheet1
row_count = wks.row_count;
wks.add_rows(1)
wks.update_cell(row_count+1,1,time)
wks.update_cell(row_count+1,2,ip)
wks.update_cell(row_count+1,3,region)
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
sys.path.append(os.path.join(os.path.dirname(__file__), 'gspread'))
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,013 |
2,353,642,089,892 |
eb493a1bba17a9b361a44a1e6e8c494c48c3afd9
|
9cf30a484ceb04f5c30ca689f5f4bc3fba379075
|
/files/tests/test_file.py
|
bb4831bc8796c5eaf9ea0b7d3c916284a2133326
|
[] |
no_license
|
simplistix/files
|
https://github.com/simplistix/files
|
cd1b1a3dbb746bd50463279226148e84c87fd8d0
|
743a7da4cfbce3692ebfd80d733f3c2340cb1031
|
refs/heads/master
| 2021-09-27T14:42:31.779709 | 2013-03-26T13:55:45 | 2013-03-26T13:55:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from unittest import TestCase
from ..file import File
class Tests(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_read_bytes(self):
pass
def test_read_string(self):
pass
def test_write_bytes(self):
pass
def test_write_string(self):
pass
def test_size(self):
pass
def test_open(self):
f = File('foo')
with open(f.path) as file:
file.read()
pass
|
UTF-8
|
Python
| false | false | 2,013 |
12,214,887,004,340 |
19c60548f1e91b1cba8f8b5dbee470f879e0af53
|
9a86468d6bbdd693fcec43223465dc2c93069600
|
/Python/euler415.py
|
03b7cbb5cd5ad9b4a3afbd4c3a4a6bc69ce5119a
|
[
"GPL-2.0-only"
] |
non_permissive
|
garykrige/project_euler
|
https://github.com/garykrige/project_euler
|
fdcf909ed43c26ff3e4f853b018ccea5723a326b
|
ea5e9c8d63317d5132b2c836fd1562b700084234
|
refs/heads/master
| 2016-09-10T23:18:49.821048 | 2014-03-18T21:19:08 | 2014-03-18T21:19:08 | 17,881,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
n = 100000
s = n + 1
p = s**2
sf = 10000000
def colines(d):
d1 = d % sf
e = 1
t = 2
while e < d:
t *= 2
t = t % sf
e += 1
return (t - d1*(1+d1)/2 - 1) % sf
t = 2
e = 1
while e < p:
t *= 2
t = t % sf
e += 1
sets = (t - (p % sf) - 1) % sf
print"sets ",sets
hv = 2 * (s%sf) * colines(s)
print"Hor/Ver ",hv
d = 2*colines(s)
for i in range(3,s):
d += 4*colines(i)
d = d % sf
print"Diagonals ",d
d1 = 0
for i in range (1 , int((s+1)/2)):
for j in range (i + 1 , int((s+1)/2)):
relPrime = True
for m in range (2, min(i,j) + 1):
if(i%m == 0) and (j%m == 0):
relPrime = False
break
if relPrime == True:
dots = float(n)/j+1
m = n*(j-i) + 1
if int(dots) == dots:
m1 = int(n*(1-float(i)/j)) + 1
m -= m1
half = int(m/2)
d1 += m1*colines(int(dots))
d1 += m*colines(int(dots)-1)
#print i,j,m1,dots,m,dots-1
else:
d1+= m*colines(int(dots))
#print i,j,m,dots
d1 = d1 % sf
k = n-1
while k > 0:
dots = int(k/j) + 1
if dots < 3:break
#print(i,j,k,dots)
d1 += 2*colines(dots)
d1 = d1 % sf
k -= 1
d1 = 4*d1 % sf
print"Slants ",d1
total = sets - hv - d - d1
total = total % sf
print (total)
|
UTF-8
|
Python
| false | false | 2,014 |
17,471,926,994,944 |
ce2c23fcfd2bcb8ea4af520dd57bc09429625906
|
2c8135d50e5a8238563f0689b646204acaaccf6c
|
/scripts/select_nets.py
|
5b2f092ee23e3dbc130b451593dcf10f7c73c12c
|
[] |
no_license
|
alexksikes/shotgunX
|
https://github.com/alexksikes/shotgunX
|
d712bcc070ac5a067b49a65340c77d2a2ce92db1
|
15ec979ce29b08d82ea1fe59c51a96b32c738e21
|
refs/heads/master
| 2016-09-05T16:31:40.851676 | 2012-10-27T17:07:50 | 2012-10-27T17:07:50 | 6,419,267 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys, re, os
p = re.compile('''Ranker_No_Doubles
Ranker_No_Body
Ranker_No_Number
Ranker_Only_Number
Ranker_No_Click
Ranker_Only_Boost
Ranker_Only_ExperimentalClickBoost
Ranker_Only_NumberOfOccurrences
Ranker_Only_Segment
Ranker_Only_First
Ranker_Only_Url
Ranker_Only_GlobalToolbarClickBoost
Ranker_Only_Query
Ranker_Only_Anchor
Ranker_Only_Top
Ranker_Only_Body
Ranker_Only_Near
Ranker_Only_Span
Ranker_Only_Spans
Ranker_Only_Title
Ranker_Only_Doubles
Ranker_Only_Order
Ranker_Only_Short
Ranker_Only_Attribute'''.replace('\n', '\.|'))
def run(dir, out_dir):
for f in os.listdir(dir):
if p.match(f):
print 'copying %s' % f
os.system('cp %s %s' % (os.path.join(dir, f),
os.path.join(out_dir, f)))
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage: python select_nets.py dir in_dir out_dir"
else:
run(sys.argv[1], sys.argv[2])
|
UTF-8
|
Python
| false | false | 2,012 |
19,121,194,405,619 |
441133843b8cf425cbbc7a15b6948a9a19d21b57
|
9b3746a012c20b78dadbd0e612204701c3a482ed
|
/scripts/fv_dbcontrol.py
|
9f358aff221cff228ce89bfe43ff52ebbf46ddf8
|
[
"MIT"
] |
permissive
|
wddq/subzero
|
https://github.com/wddq/subzero
|
096e4e4bb8a425aa26ba365df26b1e8717ce3f72
|
12c706c6da28736e7d80a2097b92e2b78d8bad01
|
refs/heads/master
| 2021-05-07T01:19:44.612341 | 2014-05-17T02:51:01 | 2014-05-17T02:51:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import argparse, json, os, sys, time
import base64
import copy
import gc
import subprocess
import hashlib
import pydeep
import magic
import pefile
import rethinkdb as r
from utils import red, blue
# Testing
from fv_fileoutput import file_compare
def _dump_data(name, data):
try:
with open(name, 'wb') as fh: fh.write(data)
print "Wrote: %s" % (red(name))
except Exception, e:
print "Error: could not write (%s), (%s)." % (name, str(e))
def _object_compare(obj1, obj2):
content1 = base64.b64decode(obj1)
content2 = base64.b64decode(obj2)
min_size = min(len(content1), len(content2))
max_size = max(len(content1), len(content2))
change_score = max_size - min_size
for i in xrange(min_size):
if content1[i] != content2[i]:
change_score += 1
return change_score
class Controller(object):
def command_list_fv(self, db, args):
ids = db.table("files").pluck("firmware_id").distinct().run()
for _id in ids:
info = db.table("updates").filter({"firmware_id": _id["firmware_id"]}).pluck("date", "machine", "name", "version").run()
print "%s:" % _id["firmware_id"],
for _machine in info:
print "%s, %s, %s, %s" % (_machine["date"], _machine["machine"], _machine["name"], _machine["version"])
pass
def command_list_files(self, db, args):
files = db.table("files").filter({"firmware_id": args.fv_id}).pluck("guid", "name", "attrs", "description").order_by(r.row["attrs"]["size"]).run()
for _file in files: print "%s %s %s (%s)" % (_file["guid"], _file["attrs"]["size"], _file["name"], _file["description"])
pass
def _compare_children(self, db, list1, list2, save= False):
change_score = 0
added_objects = []
added_objects_score = 0
### Assemble GUID pairs
children1, children2 = {}, {}
child_cursor = db.table("objects").get_all(*(list1 + list2)).\
pluck("id", "size", "object_id", "guid", "children", "order").\
order_by("order").order_by("size").run()
has_child = False
for i, child in enumerate(child_cursor):
if child["id"] == "4ae16769-cef1-44ec-97d7-13d6d59fdd21":
has_child = True
if "guid" not in child:
#print i, child["size"]
child["guid"] = min(len(children1.keys()), len(children2.keys()))
#print child["guid"], child["size"]
#print i, child["size"], child["guid"]
if child["id"] in list1:
if child["guid"] not in children1.keys():
children1[child["guid"]] = []
children1[child["guid"]].append(child)
if child["id"] in list2:
if child["guid"] not in children2:
children2[child["guid"]] = []
children2[child["guid"]].append(child)
#print children1.keys()
#print children2.keys()
objects1, objects2 = [], []
for guid in children2.keys():
if guid not in children1:
print "added guid %s" % guid
### This guid/object was added in the update
added_objects += [c["object_id"] for c in children2[guid]]
added_objects_score += sum([int(c["size"]) for c in children2[guid]])
### Todo: this does not account for nested children in a new update
continue
for i in xrange(len(children2[guid])):
if "children" in children2[guid][i] and len(children2[guid][i]["children"]) > 0:
### There are nested children, compare them individually.
if len(children1[guid]) <= i or "children" not in children1[guid][i]:
### There are less grandchildren in the previous update (for this child guid)
child_ids = db.table("objects").get_all(*children2[guid][i]["children"]).pluck("object_id").run()
nested_change = [
int(children2[guid][i]["size"]),
[child["object_id"] for child in child_ids],
int(children2[guid][i]["size"])
]
else:
#print red("will compare grandchildren lengths %d %d for guid %s, index %d" % (
# len(children1[guid][i]["children"]), len(children2[guid][i]["children"]), guid, i
# ))
nested_change = self._compare_children(db, children1[guid][i]["children"], children2[guid][i]["children"], save= save)
change_score += nested_change[0]
added_objects += nested_change[1]
added_objects_score += nested_change[2]
if save:
db.table("objects").get(children2[guid][i]["id"]).update({
"load_change": {
"change_score": nested_change[0],
"new_files": nested_change[1],
"new_files_score": nested_change[2]
}
}).run()
continue
elif len(children1[guid]) <= i:
added_objects.append(children2[guid][i]["object_id"])
added_objects_score += int(children2[guid][i]["size"])
change_score += int(children2[guid][i]["size"])
else:
objects1.append(children1[guid][i]) # ["object_id"]
objects2.append(children2[guid][i]) # ["object_id"]
### If there are objects, compare the content
content1, content2 = [], []
if len(objects1) + len(objects2) > 0:
content_cursor = db.table("content").\
get_all(*([o["object_id"] for o in objects1] + [o["object_id"] for o in objects2]),
index= "object_id").order_by("size").pluck("object_id", "content", "size", "children").run()
for content in content_cursor:
if content["object_id"] in [o["object_id"] for o in objects1]:
content1.append(content)
if content["object_id"] in [o["object_id"] for o in objects2]:
content2.append(content)
#print len(objects1), len(objects2), len(content1), len(content2)
ids1, ids2 = {o["object_id"]: o["id"] for o in objects1}, {o["object_id"]: o["id"] for o in objects2}
for i in xrange(len(content2)):
if len(content1) <= i:
content_change_score = int(content2[i]["size"])
content_added_objects = [content2[i]["object_id"]]
content_added_objects_score = int(content2[i]["size"])
else:
change = _object_compare(content1[i]["content"], content2[i]["content"])
content_added_objects = []
content_added_objects_score = 0
content_change_score = change
change_score += content_change_score
added_objects += content_added_objects
added_objects_score += content_added_objects_score
if save and ("children" not in content2[i] or len(content2[i]["children"]) == 0):
db.table("objects").get(ids2[content2[i]["object_id"]]).update({
"load_change": {
"change_score": content_change_score,
"new_files": content_added_objects,
"new_files_score": content_added_objects_score
}
}).run()
#print guid, change_score, len(added_objects)
return (change_score, added_objects, added_objects_score)
pass
def _compare_firmware(self, db, firmware1, firmware2, save= False):
### Query firmware objects
if len(firmware1[2]) == 0 or len(firmware2[2]) == 0:
print "Cannot compare versions (%d -> %d) without loaded firmware objects." % (firmware1[0], firmware2[0])
return
### This could be bad without guided-objects
if len(firmware1[2]) != len(firmware2[2]):
print "Firmware object count has changed between versions (%s -> %s)." % (firmware1[0], firmware2[0])
change = self._compare_children(db, firmware1[2], firmware2[2], save= True)
### Save changes to update
if save:
db.table("updates").get_all(firmware2[1], index= "firmware_id").update({
"load_change": {
"change_score": change[0],
"new_files": change[1],
"new_files_score": change[2],
"delta": firmware2[4] - firmware1[4]
}
}).run()
db.table("objects").get_all(firmware2[1], index= "object_id").update({
"load_change": {
"change_score": change[0],
"new_files": change[1],
"new_files_score": change[2],
"delta": firmware2[4] - firmware1[4]
}
}).run()
print "Firmware %s change: %s" % (firmware2[1], str(change))
pass
def _load_meta(self, db, _object):
content = base64.b64decode(_object["content"])
entry = {
"magic": magic.from_buffer(content),
"ssdeep": pydeep.hash_buf(content),
"md5": hashlib.md5(content).hexdigest(),
"sha1": hashlib.sha1(content).hexdigest(),
"sha256": hashlib.sha256(content).hexdigest()
}
if entry["magic"] == "MS-DOS executable":
### This is a weak application of magic
try:
pe_data = self._get_pe(content)
for k, v in pe_data.iteritems(): entry[k] = v
except Exception, e: print e; pass
pass
#entry_copy = copy.deepcopy(entry)
#del entry
#del content
#gc.collect()
db.table("content").get(_object["id"]).update({"load_meta": entry}).run()
print "Loaded meta for object (%s) %s." % (_object["firmware_id"], _object["id"])
pass
def _get_pe(self, content):
def section_name(s): return s.Name.replace("\x00", "").strip()
pe_entry = {}
pe = pefile.PE(data= content)
pe_entry["machine_type"] = pe.FILE_HEADER.Machine
pe_entry["compile_time"] = pe.FILE_HEADER.TimeDateStamp
pe_entry["sections"] = [section_name(s) for s in pe.sections if len(section_name(s)) > 0]
pe_entry["linker"] = "%d,%d" % (pe.OPTIONAL_HEADER.MajorLinkerVersion, pe.OPTIONAL_HEADER.MinorLinkerVersion)
pe_entry["os_version"] = "%d,%d" % (pe.OPTIONAL_HEADER.MajorOperatingSystemVersion, pe.OPTIONAL_HEADER.MinorOperatingSystemVersion)
pe_entry["image_version"] = "%d,%d" % (pe.OPTIONAL_HEADER.MajorImageVersion, pe.OPTIONAL_HEADER.MinorImageVersion)
pe_entry["subsystem"] = pe.OPTIONAL_HEADER.Subsystem
pe_entry["subsystem_version"] = "%d,%d" % (pe.OPTIONAL_HEADER.MajorSubsystemVersion, pe.OPTIONAL_HEADER.MinorSubsystemVersion)
del pe
return pe_entry
pass
def _load_children(self, db, children):
child_objects = db.table("objects").get_all(*children).pluck("id", "object_id", "load_meta", "children").run()
for child in child_objects:
if "children" in child and len(child["children"]) > 0:
self._load_children(db, child["children"])
continue
contents = db.table("content").get_all(child["object_id"], index= "object_id").\
filter(not r.row.contains("load_meta")).run()
num = 0
for content in contents:
print "%d/??" % (num),
num += 1
self._load_meta(db, content)
break
del contents
pass
def _get_product_updates(self, db, product):
updates = db.table("updates").order_by("date").filter(lambda update:
update["products"].contains(product) & update.has_fields("firmware_id")
).map(r.row.merge({ "object_id": r.row["firmware_id"] })).eq_join("object_id",
db.table("objects"), index= "object_id"
).zip().run()
return updates
pass
def command_load_meta(self, db, args):
if args.vendor:
vendor_products = []
products = db.table("updates").order_by("date").filter(lambda update:
update["vendor"].eq(args.vendor)
).pluck("products").run()
for product_list in products:
for product in product_list["products"]:
if product not in vendor_products:
vendor_products.append(product)
products = vendor_products
### In an effort to avoid memory exhaustion
for product in products:
print "Recalling load_meta for product %s" % product
subprocess.call("python %s load_meta --product \"%s\"" % (sys.argv[0], product), shell=True)
return
products = [args.product]
for product in products:
updates = self._get_product_updates(db, product)
for update in updates:
if "children" not in update or len(update["children"]) == 0:
continue
self._load_children(db, update["children"])
def command_load_change(self, db, args):
if args.vendor:
vendor_products = []
products = db.table("updates").order_by("date").filter(lambda update:
update["vendor"].eq(args.vendor)
).pluck("products").run()
for product_list in products:
for product in product_list["products"]:
if product not in vendor_products:
vendor_products.append(product)
products = vendor_products
else:
products = [args.product]
for product in products:
updates = self._get_product_updates(db, product)
firmware_objects = []
for update in updates:
firmware_objects.append((update["version"], update["firmware_id"], update["children"], "load_change" in update, update["date"]))
for i in xrange(len(firmware_objects)-1):
if not args.force and firmware_objects[i+1][3]:
print "Skipping change comparison (%s -> %s), already completed." % (firmware_objects[i][0], firmware_objects[i+1][0])
continue
self._compare_firmware(db, firmware_objects[i], firmware_objects[i+1], True)
def _add_lookup(self, db, guid, name, value, force= False):
if db.table("objects").get_all(guid, index= "guid").is_empty().run():
if force is False:
print "Cannot find any files matching GUID (%s), please use the force option." % guid
return
pass
if db.table("lookup").get_all(guid, index= "guid").is_empty().run():
db.table("lookup").insert({
"guid": guid,
"%s" % name: value
}).run()
print "Added lookup for GUID (%s), with (%s) = (%s)." % (guid, name, value)
else:
db.table("lookup").get_all(guid, index= "guid").update({"%s" % name: value}).run()
print "Updated lookup for GUID (%s), set (%s) = (%s)." % (guid, name, value)
pass
def command_add_lookup(self, db, args):
self._add_lookup(db, args.guid, args.name, args.value, force= args.force)
def command_load_guids(self, db, args):
from uefi_firmware.guids import GUID_TABLES
from uefi_firmware.utils import rfguid
for table in GUID_TABLES:
for name, r_guid in table.iteritems():
#print name, rfguid(r_guid)
self._add_lookup(db, rfguid(r_guid), "guid_name", name, True)
pass
def parse_extra (parser, namespace):
namespaces = []
extra = namespace.extra
while extra:
n = parser.parse_args(extra)
extra = n.extra
namespaces.append(n)
return namespaces
def main():
argparser = argparse.ArgumentParser()
subparsers = argparser.add_subparsers(help='Firmware Controls', dest='command')
parser_list_fv = subparsers.add_parser("list_fv", help= "List all FV IDs which have files in the DB")
parser_list_files = subparsers.add_parser("list_files", help= "List all files GUIDs for a given FV ID")
parser_list_files.add_argument("fv_id", help="Firmware ID.")
'''Simple loading/parsing commands.'''
parser_load_change = subparsers.add_parser("load_change", help= "Load change scores for objects and firmware.")
parser_load_change.add_argument("-f", "--force", action="store_true", default= False, help="Force recalculation.")
group = parser_load_change.add_mutually_exclusive_group(required= True)
group.add_argument("--product", help="Product to load.")
group.add_argument("--vendor", help="Vendor to load.")
parser_load_meta = subparsers.add_parser("load_meta", help= "Extract meta, hashes for a machine's firmware.")
parser_load_meta.add_argument("-f", "--force", action="store_true", default= False, help="Force recalculation.")
group = parser_load_meta.add_mutually_exclusive_group(required= True)
group.add_argument("--product", help="Product to load.")
group.add_argument("--vendor", help="Vendor to load.")
parser_add_lookup = subparsers.add_parser("add_lookup", help= "Add metadata about a file GUID.")
parser_add_lookup.add_argument("-f", "--force", default=False, action= "store_true", help= "Force the lookup insert.")
parser_add_lookup.add_argument("guid", help= "File GUID")
parser_add_lookup.add_argument("name", help="Key to add to the GUID.")
parser_add_lookup.add_argument("value", help= "Value")
parser_load_guids = subparsers.add_parser("load_guids", help= "Read in EFI GUID definitions.")
parser_load_guids.add_argument("-f", "--force", default= False, action= "store_true", help= "Override existing DB GUID definitions.")
args = argparser.parse_args()
controller = Controller()
command = "command_%s" % args.command
r.connect("localhost", 28015).repl()
db = r.db("uefi")
#objects_table = db.table("objects")
#updates_table = db.table("updates")
#content_table = db.table("content")
#lookup_table = db.table("lookup")
#stats_table = db.table("stats")
command_ptr = getattr(controller, command, None)
if command_ptr is not None:
command_ptr(db, args)
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,014 |
6,158,983,133,951 |
80c56053f6455f5e4f7658ba06ded1dbff81e06f
|
7d2e39c07e7e4996b4d1dc1d91c73a5b94872310
|
/project/api/ticketsapi/handlers.py
|
7ac45ca764aad978a5f5d61fe25fbe1fa4f17727
|
[] |
no_license
|
frecar/focus
|
https://github.com/frecar/focus
|
6bd1d70d2ca0bc5da9d80e12f43eeb19550b2cab
|
aab0006041a8b475a48691e91afb1f0ca52aa516
|
refs/heads/master
| 2020-12-30T10:37:29.981578 | 2012-02-16T07:27:27 | 2012-02-16T07:27:27 | 2,194,075 | 1 | 1 | null | false | 2020-07-25T19:53:22 | 2011-08-11T22:10:56 | 2014-10-27T23:57:12 | 2012-02-16T07:27:46 | 10,880 | 1 | 1 | 1 |
Python
| false | false |
from piston.handler import BaseHandler
from piston.utils import rc
from app.tickets.models import Ticket, TicketType, TicketStatus
from core import Core
from django.core import urlresolvers
from core.auth.user.models import User
class TicketHandler(BaseHandler):
model = Ticket
allowed_methods = ('GET', )
fields = (
'id', 'ticket_creator', 'title', 'mark_as_unread_for_current_user', ('user',('id','get_full_name')),'get_recipients', ('priority', ('name',)), 'update_count',
('status', ('name',)),
('type', ('name',)), 'date_edited', ('assigned_to', ('username', 'get_full_name')), 'ticket_url' )
@classmethod
def update_count(cls, ticket):
return len(ticket.updates.all())
@classmethod
def ticket_creator(cls, ticket):
try:
return ticket.creator.username
except AttributeError:
return ticket.creator.email
@classmethod
def ticket_url(cls, ticket):
return urlresolvers.reverse('app.tickets.views.view', args=(ticket.id, ))
@classmethod
def date_edited(cls, ticket):
return ticket.date_edited.strftime("%d.%m.%Y %H:%S")
def read(self, request, id=None):
all = Core.current_user().get_permitted_objects("VIEW", Ticket)
if id:
try:
return all.get(id=id)
except Ticket.DoesNotExist:
return rc.NOT_FOUND
else:
all = TicketHandler.filter_tickets(all, request.GET)
return all
@staticmethod
def filter_tickets(tickets, filter):
trashed = bool(int(filter.get('trashed', False)))
tickets = tickets.filter(trashed=trashed)
type_id = int(filter.get('type_id', False))
if type_id:
type = TicketType.objects.get(id=type_id)
tickets = tickets.filter(type=type)
status_id = int(filter.get('status_id', False))
if status_id:
status = TicketStatus.objects.get(id=status_id)
tickets = tickets.filter(status=status)
assigned_to = int(filter.get('assigned_to', False))
if assigned_to:
assigned_to = User.objects.get(id=assigned_to)
tickets = tickets.filter(assigned_to=assigned_to)
range = int(filter.get('range', -1))
if range >= 0:
tickets = tickets[range: range+12] # returns 12 tickets, some other number might be better...
# the number is also hardcoded in the javascript code
return tickets
|
UTF-8
|
Python
| false | false | 2,012 |
1,013,612,319,327 |
1d9570dae2f39cbac40ce4cb61a77b3ecda3e22e
|
5551b96d58369c554e096e249af2ba42f8213c23
|
/airead/timer_task/__init__.py
|
a7e4e0609526e6c594d98609ca745a9a8c110fe1
|
[] |
no_license
|
greenhill520/Airead-Server
|
https://github.com/greenhill520/Airead-Server
|
6430b7ac4be0b55919d3d5cbd33ca5b47c1cfb9c
|
7100187f88c4891838c09f6e8a8df867f97a1e42
|
refs/heads/master
| 2020-05-30T11:34:58.123991 | 2013-04-11T11:39:40 | 2013-04-11T11:39:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from update_feed import update_feed
|
UTF-8
|
Python
| false | false | 2,013 |
1,357,209,683,853 |
c144f8b3599a1feb71e29954d47c5226298b9570
|
5546af6a32998a7cc6cc5ee24f85e95e13e83bbb
|
/django-common/exam/scripts/import_exams.py
|
c6c4a5c3b7fccaa404909fbbf3b8a48b3badac62
|
[] |
no_license
|
wylliec/old-hkn
|
https://github.com/wylliec/old-hkn
|
051c83caf2e2157a2c39f9c230db716c8a42c2b9
|
4ebaa69f82421260ab397bd381d5bd66aa82a23f
|
refs/heads/master
| 2021-01-19T12:15:00.347326 | 2010-11-01T21:09:36 | 2010-11-01T21:09:36 | 69,656,957 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import setup_settings
from course.models import *
from exam.models import *
from exam.constants import *
from find_klass import *
from django.core.files.base import File
from os import listdir
from os.path import isdir, join, split
import re
import shutil
import sys
from settings import MEDIA_ROOT, SERVER_ROOT
VALID_EXTENSIONS = ["html", "pdf", "ps", "txt"]
EE_DIR = join(SERVER_ROOT, "old_exams/ee")
CS_DIR = join(SERVER_ROOT, "old_exams/cs")
#EE_DIR = "/web/student/online/exams_import/ee"
#CS_DIR = "/web/student/online/exams_import/cs"
file_pattern = re.compile('^(sp|fa|su)-(1|2|3|f)(-sol)?\.')
course_pattern = re.compile('^\d+[A-Z]*$')
course_map = {
"COMPSCI" : CS_DIR,
"EL ENG" : EE_DIR,
}
season_map = {
"sp" : "Spring",
"fa" : "Fall",
"su" : "Summer",
}
def parse_filename(filename):
info = filename.split('.')[0].split('-')
if info[1] == "f":
num = "1"
type = EXAM_TYPE_FINAL
else:
num = info[1]
type = EXAM_TYPE_MIDTERM
return (season_map[info[0]], num, type, len(info) > 2)
def list_folders(path):
return filter(lambda x: isdir(join(path, x)), listdir(path))
def is_valid_file(filename):
try:
if not file_pattern.match(filename):
return False
parse_filename(filename)
return filename.split(".")[1] in VALID_EXTENSIONS
except:
return False
def is_instructor_file(filename):
try:
return filename.split(".")[1] == "txt"
except:
return False
def list_files(path):
return filter(lambda x: not isdir(join(path, x)), listdir(path))
def parse_instructor_file(path):
try:
f = open(path, "r")
except:
return {}
d = {}
for line in f:
try:
line = re.split("[\t\n\r ]+", line)
d[" ".join( [line[0], line[1]] ) ] = line[2]
except:
print "Bad line in instructor file: %s" % line
f.close()
return d
descriptions = {EXAM_TYPE.FINAL : 'f', EXAM_TYPE.MIDTERM : 'mt', EXAM_TYPE.QUIZ : 'qz', EXAM_TYPE.REVIEW : "r"}
def make_newfile(old_name, klass, type, number, solution, extension):
if type != EXAM_TYPE_FINAL:
type_string = descriptions[type] + str(number)
else:
type_string = descriptions[type]
if solution:
sol_string = "_sol"
else:
sol_string = ""
file = open(old_name, "r")
filename = "%s_%s_%s%s.%s" % (klass.course.short_name(), klass.semester.abbr(), type_string, sol_string, extension)
if os.path.exists(join(SERVER_ROOT, MEDIA_ROOT, File_UPLOAD_DIR, filename)):
raise Exception("File already exists: " + filename)
return (filename, file)
def convert_file(path):
path_without_extension = path.split('.')[0]
extension = path.split('.')[1]
if extension == 'html':
if os.path.exists(path_without_extension + ".pdf"):
os.system("rm " + path)
print "PDF exists, deleting file: " + path
return
os.system("htmldoc -f " + path_without_extension + ".pdf --webpage " + path)
os.system("rm " + path)
print "Converting html to pdf: " + path
elif extension == 'ps':
if os.path.exists(path_without_extension + ".pdf"):
os.system("rm " + path)
print "PDF exists, deleting file: " + path
return
os.system("ps2pdf " + path + " " + path_without_extension + ".pdf")
os.system("rm " + path)
print "Converting ps to pdf: " + path
def convert_exams():
for dept, root in course_map.items():
classes = filter(lambda x: course_pattern.match(x), list_folders(root))
for c in classes:
for year in list_folders(join(root, c)):
for filename in filter(is_valid_file, list_files(join(root, c, year))):
convert_file(join(root, c, year, filename))
def load_exams():
"""
import exam.scripts.import_exams as exam_loader
exam_loader.load_exams()
"""
missing_instructor_file = []
missing_instructors = set()
missing_courses = set()
missing_semesters = set()
missing_klasses = set()
instructor_mismatches = set()
failed_imports = []
for dept, root in course_map.items():
try:
os.mkdir(join(root, "completed"))
except:
pass
classes = filter(lambda x: course_pattern.match(x), list_folders(root))
for c in classes:
try:
instructor_filename = join(root, c, filter(is_instructor_file, list_files(join(root, c)))[0])
instructor_map = parse_instructor_file(instructor_filename)
except:
print "NO INSTRUCTOR FILE FOUND"
missing_instructor_file.append(dept + " " + c)
instructor_map = {}
for year in list_folders(join(root, c)):
for filename in filter(is_valid_file, list_files(join(root, c, year))):
season, number, type, solution = parse_filename(filename)
try:
instructor = instructor_map[season + " " + year]
instructors = instructor.replace("_", " ").split("/")
except:
print "semester not found in instructor file or instructor file doesn't exist"
instructors = []
try:
klass = get_klass(dept, c, instructors, season=season.lower(), year=year)
klass = klass[0]
e = Exam()
e.klass = klass
e.number = number
e.is_solution = solution
e.version = 0
e.paper_only = False
e.publishable = True
e.exam_type = type
e.topics = ""
e.submitter = None
new_filename, f = make_newfile(join(root, c, year, filename),klass, type, number, solution, filename.split('.')[-1])
e.file.save(new_filename, File(f))
e.save()
f.close()
shutil.move(join(root, c, year, filename), join(root, "completed", new_filename))
except MissingInstructorException, e:
print e[0]
missing_instructors.add(e[1])
except MissingCourseException:
print "Course not found: %s %s:" % (dept, c)
missing_courses.add("%s %s" % (dept, c))
except InstructorMismatch, e:
print e
instructor_mismatches.add("%s" % (e))
except NoKlasses, e:
print "No Klasses found for %s %s - %s %s" % (dept, c, season, year)
missing_klasses.add("%s %s - %s %s" % (dept, c, season, year))
except Exception, e:
print "Failed on %s %s %s" % (season, year, instructor )
failed_imports.append("%s: %s %s %s %s" % (e, c, season, year, instructor) )
print "Import completed!"
print "Unexpected errors (%d): " % len(failed_imports)
for msg in failed_imports:
print msg
print ""
print "No Klass for the following: "
print "\n".join(sorted(missing_klasses))
print ""
print "Semester not in instructor file: "
print "\n".join(sorted(missing_semesters))
print ""
print "Courses with missing instructor files: "
print "\n".join(sorted(missing_instructor_file))
print ""
print "Instructors that are missing: "
print "\n".join(sorted(missing_instructors))
print ""
print "Instructor mismatch: "
print "\n".join(sorted(instructor_mismatches))
print ""
print "Courses that are missing: " + ", ".join(sorted(missing_courses))
#return (missing_instructors, missing_courses, instructor_mismatches)
def main():
convert_exams()
load_exams()
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,010 |
5,729,486,390,169 |
34eb2d59a9a239f1172bcac115a8ca2fe303186e
|
b2c4ab262e45f56eeb427386d77ff3a5e9a508cf
|
/mootiro_maps/apps/search/urls.py
|
e36b32969349e9bc434d648486ca1bce012321b1
|
[
"MIT",
"AGPL-1.0-only"
] |
non_permissive
|
davigomesflorencio/mootiro-maps
|
https://github.com/davigomesflorencio/mootiro-maps
|
0017d4ea32d339b77a2aeb3db46bb13aa5c1b506
|
56f8ca508785d7d1b1203e7280d29bdfc72351b4
|
refs/heads/master
| 2018-01-17T12:14:57.721095 | 2014-12-12T19:33:02 | 2014-12-12T19:33:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals # unicode by default
from django.conf.urls.defaults import url, patterns
from django.conf import settings
urlpatterns = patterns('search.views',
url(r'^search/?$', 'search', name='komoo_search'),
url(r'^search/all/?$', 'search_all', name='komoo_search_all'),
)
|
UTF-8
|
Python
| false | false | 2,014 |
6,399,501,292,677 |
e02e1e81a6ccbbec28dd6527b826cf4cf06fd405
|
5058401352fd2b80bf33bd4a0c0acc77b0e05231
|
/python/pythons/lierotest/lierotest.py
|
acaa6e51ec5036a564ef513063dc7332b409064a
|
[] |
no_license
|
pgl/mcandre
|
https://github.com/pgl/mcandre
|
3b81ee64bf10ccaf02b9a1d44ed73e20cbcad4b6
|
81055895d872e2f93cd055f5a832c6d89848e3a3
|
refs/heads/master
| 2021-01-24T20:25:24.672765 | 2013-10-24T09:06:25 | 2013-10-24T09:06:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import pygame
import sys, time
def main():
pygame.init()
width, height=320, 240
size=width, height
screen=pygame.display.set_mode(size)
icon=pygame.image.load("single.png")
pygame.display.set_icon(icon)
black=0, 0, 0
worm=pygame.image.load("single.png").convert()
wormrect=worm.get_rect()
wormrect.bottom=screen.get_rect().bottom
speed=[1, 0]
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
screen.fill(black, wormrect)
wormrect=wormrect.move(speed)
if wormrect.left<0 or wormrect.right>width:
speed[0]=-speed[0]
time.sleep(0.000002)
screen.fill(black, wormrect)
screen.blit(worm, wormrect)
pygame.display.flip()
if __name__=="__main__":
main()
|
UTF-8
|
Python
| false | false | 2,013 |
13,486,197,312,351 |
b6b33e21ab40f2f30865de593f43e6d5eaa78a3d
|
b9f0b93035c3f1f8d407a59cbd8f80c549222c34
|
/gitpapers/cmds.py
|
0389678bf0a8175b74c76db3be08c42d069930c5
|
[] |
no_license
|
warrd/git-papers
|
https://github.com/warrd/git-papers
|
993a1ba899bfa320f2097d9eaed00a1a9d1879ef
|
490cc11ec0ba9ea6549ee0049b2357e295706100
|
refs/heads/master
| 2016-09-05T20:05:47.505575 | 2013-10-16T15:49:23 | 2013-10-16T15:49:23 | 3,210,562 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from __future__ import print_function
import os
import os.path as osp
from functools import wraps, update_wrapper
from .backend import GitPapersApp, ADD, RM
from .display import format_error, prettypaper, color, COL_KEY, COL_PATH
from .errors import *
PAPERS_DIR = '~/work/papers/'
VIEWER = 'evince'
EDITOR = os.environ.get('EDITOR', 'vim')
#------------------------------------------------------------------------------
# Decorators
def cmd(**kwargs):
gets_app = kwargs.pop('gets_app', True)
requires_args = kwargs.pop('requires_args', False)
single_arg = kwargs.pop('single_arg', False)
path_args = kwargs.pop('path_args', False)
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
if path_args:
args = map(osp.abspath, args)
os.chdir(osp.expanduser(PAPERS_DIR))
if single_arg and len(args)>1:
raise SingleArgumentRequired()
if requires_args and not len(args):
raise NoArguments()
if gets_app:
kwargs['app'] = GitPapersApp()
return func(*args, **kwargs)
except GitPapersError as e:
import sys
sys.stderr.write(format_error(e))
sys.exit(1)
wrapper.cmd = True
return wrapper
return decorator
#------------------------------------------------------------------------------
@cmd(gets_app=False)
def init(*args, **kwargs):
GitPapersApp.init()
print("git-papers initialised.")
#------------------------------------------------------------------------------
@cmd(requires_args=False, path_args=True)
def add(*args, **kwargs):
app = kwargs.pop('app')
def bibfunc():
from subprocess import Popen, PIPE
key = None
raw_input('Copy bibtex to clipboard%s, and press enter:\n'
%('' if not len(args) else 'for ' + color(path, COL_PATH)))
return Popen('xsel', stdout=PIPE).communicate()[0]
if not len(args):
paper = app.add(None, bibfunc)
print("Reference added for %s." %color(paper.key, COL_KEY))
for path in args:
with open(path, 'rb') as paperfile:
paper = app.add(paperfile, bibfunc)
print("Paper added as %s. Original file will be removed."
%color(paper.key, COL_KEY))
os.remove(path)
#-----------------------------------------------------------------------------
@cmd(requires_args=True)
def rm(*args, **kwargs):
app = kwargs.pop('app')
for paper in args:
app.rm(paper)
#-----------------------------------------------------------------------------
@cmd(single_arg=True)
def tail(n=10, **kwargs):
# TODO: Add argument checking to decorator
try:
n = int(n)
except:
raise InvalidArgType(n, int, True)
app = kwargs.pop('app')
papers = []
for i, paper in enumerate(app.history()):
if i==n:
break
papers.append(prettypaper(paper))
if not len(papers):
print("No papers in repo.")
else:
print('\n' + '\n\n'.join(papers))
#-----------------------------------------------------------------------------
@cmd()
def stat(*args, **kwargs):
app = kwargs.pop('app')
if not len(args):
print("Number of papers: %s" %len(app))
#TODO: more stats (size in MB etc)
for key in args:
print('\n'+prettypaper(app[key]))
#-----------------------------------------------------------------------------
@cmd(requires_args=True)
def view(*args, **kwargs):
from subprocess import Popen, PIPE
app = kwargs.pop('app')
for key in args:
paper = app[key]
if not paper.ext:
raise NoPaperFile(paper.key)
# TODO: shouldn't be piping stderr: this is hack so I don't see my glib
# errors!
Popen([VIEWER, paper.filepath], stderr=PIPE, stdout=PIPE)
#-----------------------------------------------------------------------------
@cmd(requires_args=True)
def search(*args, **kwargs):
app = kwargs.pop('app')
search_domains = {key: kwargs.pop(key, False) for key in
['key', 'title', 'author', 'year', 'publication']}
search_domains = [key for key in search_domains if search_domains[key] or
not True in search_domains]
for paper in app:
found_all_terms = True
text = ' '.join([(getattr(paper.ref,d) or '') for d in search_domains])
text = text.lower()
for term in args:
if not term.lower() in text:
found_all_terms = False
break
if found_all_terms:
print('\n'+prettypaper(paper))
#-----------------------------------------------------------------------------
@cmd(requires_args=True)
def tag(*args, **kwargs):
import subprocess
app = kwargs.pop('app')
for key in args:
paper = app[key]
if not osp.exists(paper.tags_path):
with open(paper.tags_path, 'w'):
pass
with open(paper.tags_path, 'r+') as f:
subprocess.call([EDITOR, f.name])
#-----------------------------------------------------------------------------
@cmd()
def ref(*args, **kwargs):
app = kwargs.pop('app')
papers = []
if len(args):
for key in args:
paper = app[key]
if not paper in papers:
papers.append(paper)
else:
papers = app
for paper in papers:
print(paper.ref)
#-----------------------------------------------------------------------------
@cmd()
def toread(*args, **kwargs):
app = kwargs.pop('app')
toread_path = osp.join(app.repo.path, '.toread')
if not len(args):
with open(toread_path) as f:
toread = f.read().split()
for key in toread:
paper = app[key]
print('\n'+prettypaper(paper))
else:
toread = ''
for i, key in enumerate(args):
paper = app[key]
toread += paper.key if i==0 else '\n'+ paper.key
toread += '\n'
with open(toread_path, 'a') as f:
f.write(toread)
app.commit([toread_path], 'TOREAD %s papers' %len(args))
|
UTF-8
|
Python
| false | false | 2,013 |
14,886,356,655,341 |
41673a3e998acf2e39faa409d9fd9d13a68847b9
|
9482884866e700cc1b216f5bf8a4b3ed56c295db
|
/suffixes.py
|
9c50f6f8b1f97f5b3c67b9d0dc0611cf763c53f3
|
[] |
no_license
|
minhlab/vietnamese-statistics
|
https://github.com/minhlab/vietnamese-statistics
|
f971cb2e0744d01685be0b109a69fc5e70ddd87b
|
ce8c834346c22e7312967f03dd365cb5ed677468
|
refs/heads/master
| 2020-06-08T15:53:05.850870 | 2014-06-04T07:44:52 | 2014-06-04T07:44:52 | 20,473,211 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
import fileinput
if __name__ == '__main__':
for line in fileinput.input():
words = line.strip().split(' ')
for word in words:
syllables = word.split('_')
if len(syllables) >= 2:
suffix = "_".join(syllables[1:])
print suffix
|
UTF-8
|
Python
| false | false | 2,014 |
5,093,831,214,066 |
5c0ae0530a791aa8a68775c1699fd2034b3b7d91
|
708b6bc22f9b40d4b5c989967951ea0af006fcb9
|
/gui.py
|
914d72a235af827f64c9b67c6f5ccb8210ea45a1
|
[] |
no_license
|
AndreMiras/repartiteur-de-mises
|
https://github.com/AndreMiras/repartiteur-de-mises
|
cb473e29c7c441c6bd33d5bb35924339baaaa060
|
33e7ea6d6311e477bf97d364b2377c15d1f0c71d
|
refs/heads/master
| 2020-04-18T21:50:53.329373 | 2011-12-28T01:07:33 | 2011-12-28T01:07:33 | 33,007,640 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created: Tue Dec 27 20:37:33 2011
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(472, 298)
self.gridLayout_2 = QtGui.QGridLayout(Form)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.targetedProfitSpinBox = QtGui.QSpinBox(Form)
self.targetedProfitSpinBox.setMaximum(999)
self.targetedProfitSpinBox.setProperty(_fromUtf8("value"), 10)
self.targetedProfitSpinBox.setObjectName(_fromUtf8("targetedProfitSpinBox"))
self.gridLayout.addWidget(self.targetedProfitSpinBox, 0, 1, 1, 1)
self.label_2 = QtGui.QLabel(Form)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
self.totalBetLabel = QtGui.QLabel(Form)
self.totalBetLabel.setObjectName(_fromUtf8("totalBetLabel"))
self.gridLayout.addWidget(self.totalBetLabel, 1, 1, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem, 0, 1, 1, 1)
spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.gridLayout_2.addItem(spacerItem1, 1, 0, 1, 1)
self.tableWidget = QtGui.QTableWidget(Form)
self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
self.tableWidget.setColumnCount(6)
self.tableWidget.setRowCount(4)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(4, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(5, item)
self.tableWidget.horizontalHeader().setVisible(False)
self.gridLayout_2.addWidget(self.tableWidget, 3, 0, 1, 5)
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem2, 5, 0, 1, 3)
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem3, 5, 4, 1, 2)
spacerItem4 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.gridLayout_2.addItem(spacerItem4, 4, 0, 1, 1)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.addColumnPushButton = QtGui.QPushButton(Form)
self.addColumnPushButton.setObjectName(_fromUtf8("addColumnPushButton"))
self.verticalLayout.addWidget(self.addColumnPushButton)
self.removeColumnPushButton = QtGui.QPushButton(Form)
self.removeColumnPushButton.setObjectName(_fromUtf8("removeColumnPushButton"))
self.verticalLayout.addWidget(self.removeColumnPushButton)
spacerItem5 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem5)
self.gridLayout_2.addLayout(self.verticalLayout, 3, 5, 1, 1)
self.okCancelButtonBox = QtGui.QDialogButtonBox(Form)
self.okCancelButtonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Reset)
self.okCancelButtonBox.setObjectName(_fromUtf8("okCancelButtonBox"))
self.gridLayout_2.addWidget(self.okCancelButtonBox, 5, 3, 1, 1)
self.integerBetCheckBox = QtGui.QCheckBox(Form)
self.integerBetCheckBox.setObjectName(_fromUtf8("integerBetCheckBox"))
self.gridLayout_2.addWidget(self.integerBetCheckBox, 0, 3, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Repartiteur de mises", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Form", "Gain vise", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Form", "Mise totale effective:", None, QtGui.QApplication.UnicodeUTF8))
self.totalBetLabel.setText(QtGui.QApplication.translate("Form", "0", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.verticalHeaderItem(0).setText(QtGui.QApplication.translate("Form", "N° PMU", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.verticalHeaderItem(1).setText(QtGui.QApplication.translate("Form", "Cote", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.verticalHeaderItem(2).setText(QtGui.QApplication.translate("Form", "Mise", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.verticalHeaderItem(3).setText(QtGui.QApplication.translate("Form", "Gain effectifs", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.horizontalHeaderItem(0).setText(QtGui.QApplication.translate("Form", "Col", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.horizontalHeaderItem(1).setText(QtGui.QApplication.translate("Form", "Col", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.horizontalHeaderItem(2).setText(QtGui.QApplication.translate("Form", "Col", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.horizontalHeaderItem(3).setText(QtGui.QApplication.translate("Form", "Col", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.horizontalHeaderItem(4).setText(QtGui.QApplication.translate("Form", "Col", None, QtGui.QApplication.UnicodeUTF8))
self.tableWidget.horizontalHeaderItem(5).setText(QtGui.QApplication.translate("Form", "Col", None, QtGui.QApplication.UnicodeUTF8))
self.addColumnPushButton.setText(QtGui.QApplication.translate("Form", "+", None, QtGui.QApplication.UnicodeUTF8))
self.removeColumnPushButton.setText(QtGui.QApplication.translate("Form", "-", None, QtGui.QApplication.UnicodeUTF8))
self.integerBetCheckBox.setText(QtGui.QApplication.translate("Form", "Mises entieres", None, QtGui.QApplication.UnicodeUTF8))
|
UTF-8
|
Python
| false | false | 2,011 |
13,073,880,498,468 |
3e58f27d7f98040eaf8d3db3276304dd154f30c3
|
35f17edee2926b176f4b0148e313d4d95e5232e8
|
/experiments/learn_semantic_network.py
|
9a98141f49d1b2dd284affd1b33a8421a207c697
|
[] |
no_license
|
e2crawfo/cleanup-learning
|
https://github.com/e2crawfo/cleanup-learning
|
7dc3e29385daf98c1a565ec186fb295fc78bb339
|
ca7f92d19d860c3e00ead11e71cc45480ea728d6
|
refs/heads/master
| 2021-01-19T07:40:43.762213 | 2014-02-05T01:17:06 | 2014-02-05T01:17:06 | 14,177,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import matplotlib.pyplot as plt
import numpy as np
import random
from mytools import hrr, timed, fh, nf, extract_probe_data
from build_semantic_network import build_semantic_network
from learning_cleanup import build_and_run, plot
@timed.namedtimer("extract_data")
def extract_data(filename, sim, address_input_p, stored_input_p,
pre_probes, cleanup_s, output_probes,
address_vectors, stored_vectors, testing_vectors, correct_vectors,
**kwargs):
t = sim.trange()
address_input, _ = extract_probe_data(t, sim, address_input_p)
stored_input, _ = extract_probe_data(t, sim, stored_input_p)
pre_decoded, _ = extract_probe_data(t, sim, pre_probes)
cleanup_spikes, _ = extract_probe_data(t, sim, cleanup_s, spikes=True)
output_decoded, _ = extract_probe_data(t, sim, output_probes)
def make_sim_func(h):
def sim(vec):
return h.compare(hrr.HRR(data=vec))
return sim
print len(stored_vectors)
print len(address_vectors)
print address_vectors
address_sim_funcs = [make_sim_func(hrr.HRR(data=h)) for h in address_vectors]
stored_sim_funcs = [make_sim_func(hrr.HRR(data=h)) for h in stored_vectors]
output_sim, _ = extract_probe_data(t, sim, output_probes, func=stored_sim_funcs)
input_sim, _ = extract_probe_data(t, sim, address_input_p, func=address_sim_funcs)
ret = dict(t=t, address_input=address_input, stored_input=stored_input,
pre_decoded=pre_decoded, cleanup_spikes=cleanup_spikes,
output_decoded=output_decoded,
output_sim=output_sim, input_sim=input_sim,
correct_vectors=correct_vectors, testing_vectors=testing_vectors)
fh.npsave(filename, **ret)
return ret
#@timed.namedtimer("plot")
#def plot(filename, t, address_input, pre_decoded, cleanup_spikes,
# output_decoded, output_sim, input_sim, **kwargs):
#
# num_plots = 6
# offset = num_plots * 100 + 10 + 1
#
# ax, offset = nengo_plot_helper(offset, t, address_input)
# ax, offset = nengo_plot_helper(offset, t, pre_decoded)
# ax, offset = nengo_plot_helper(offset, t, cleanup_spikes, spikes=True)
# ax, offset = nengo_plot_helper(offset, t, output_decoded)
# ax, offset = nengo_plot_helper(offset, t, output_sim)
# ax, offset = nengo_plot_helper(offset, t, input_sim)
#
# plt.savefig(filename)
def start():
seed = 81223
training_time = 1 #in seconds
testing_time = 0.5
DperE = 32
dim = 32
NperD = 30
N = 5
cleanup_n = N * 20
num_tests = 5
oja_scale = np.true_divide(2,1)
oja_learning_rate = np.true_divide(1,50)
pre_tau = 0.03
post_tau = 0.03
pes_learning_rate = np.true_divide(1,1)
config = locals()
#Don't put all parematers in config
cleanup_params = {'radius':1.0,
'max_rates':[400],
'intercepts':[0.13]}
ensemble_params = {'radius':1.0,
'max_rates':[400],
'intercepts':[0.1]}
#intercepts actually matter quite a bit, so put them in the filename
config['cint'] = cleanup_params['intercepts'][0]
config['eint'] = ensemble_params['intercepts'][0]
data_title = 'lsndata'
directory = 'learning_sn_data'
data_filename = fh.make_filename(data_title, directory=directory,
config_dict=config, extension='.npz',
use_time=False)
data = fh.npload(data_filename)
if data is None:
#build the graph and get the vectors encoding it
hrr_vectors, id_vectors, edge_vectors, G = build_semantic_network(dim, N, seed=seed)
edges = random.sample(list(G.edges_iter(data=True)), num_tests)
correct_vectors = [hrr_vectors[v] for u,v,d in edges]
testing_vectors = [hrr_vectors[u].convolve(~edge_vectors[d['index']]) for u,v,d in edges]
testing_vectors = map(lambda x: x.v, testing_vectors)
hrr_vectors = map(lambda x: hrr_vectors[x].v, G.nodes_iter())
id_vectors = map(lambda x: id_vectors[x].v, G.nodes_iter())
results = build_and_run(address_vectors = id_vectors, stored_vectors=hrr_vectors,
testing_vectors=testing_vectors, cleanup_params=cleanup_params,
ensemble_params=ensemble_params, **config)
data = extract_data(filename=data_filename, correct_vectors=correct_vectors, **results)
do_plots = True
if do_plots:
plot_title = 'lsnplot'
directory='learning_sn_plots'
plot_filename = fh.make_filename(plot_title, directory=directory,
config_dict=config, extension='.png')
plot(filename=plot_filename, **data)
plt.show()
if __name__=='__main__':
start()
|
UTF-8
|
Python
| false | false | 2,014 |
12,893,491,834,883 |
4bb6644e2b5ae367fe059f8623cb887871e5c8a7
|
cebdb2bd0f65e30d5a5d27425bdd415fc5ffe364
|
/ingestion/dar_builder.py
|
3968d44b79ddaeb38a32cde10643e152c985dee8
|
[
"LicenseRef-scancode-free-unknown",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
non_permissive
|
DREAM-ODA-OS/IngestionEngine
|
https://github.com/DREAM-ODA-OS/IngestionEngine
|
be1241ce92b5bddee723a6f7a0fc8a7881f003d5
|
fb84a6479ee8bc22ab392f23fa089f9277278101
|
refs/heads/master
| 2020-11-26T21:13:50.942116 | 2014-12-03T18:10:59 | 2014-12-03T18:10:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
############################################################
# Project: DREAM
# Module: Task 5 ODA Ingestion Engine
# Contribution: Milan Novacek (CVC)
# Date: Oct 20, 2013
#
# (c) 2013 Siemens Convergence Creators s.r.o., Prague
# Licensed under the 'DREAM ODA Ingestion Engine Open License'
# (see the file 'LICENSE' in the top-level directory)
#
# Ingestion Engine: Data Access Request (DAR) builder.
#
############################################################
import xml.etree.ElementTree as ET
import sys
LOCAL_DEBUG = 0
DAR_PREAMBLE = '<?xml version="1.0" encoding="UTF-8"?>'
TODO = """<ngeo:DataAccessMonitoring-Resp
xmlns:ngeo="http://ngeo.eo.esa.int/iicd-d-ws/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ngeo.eo.esa.int/iicd-d-ws/1.0 IF-ngEO-DataAccessMonitoring-Resp.xsd">
<ngeo:MonitoringStatus>IN_PROGRESS</ngeo:MonitoringStatus>"""
NGEO_URI = "http://ngeo.eo.esa.int/iicd-d-ws/1.0"
NGEO_NS = "{"+NGEO_URI+"}"
XSI_URI = "http://www.w3.org/2001/XMLSchema-instance"
XSI_NS = "{"+XSI_URI+"}"
SCHEMA_LOCATION = "http://ngeo.eo.esa.int/iicd-d-ws/1.0 IF-ngEO-DataAccessMonitoring-Resp.xsd"
DA_RESP = "DataAccessMonitoring-Resp"
MONITORINGSTATUS = "MonitoringStatus"
PRODACCESSLIST = "ProductAccessList"
PRODACCESS = "ProductAccess"
PRODACCESSURL = "ProductAccessURL"
PRODACCESSSTATUS = "ProductAccessStatus"
PRODDOWNLOADDIRECTORY = "ProductDownloadDirectory"
use_register = False
vers = sys.version_info
if vers[0] > 2: use_register = True
if vers[1] > 6 and vers[0] == 2: use_register = True
def build_DAR(urls):
""" urls consist of a list of tuples (dl_dir, url),
where dl_dir is the download directory for each url"""
if use_register:
try:
ET.register_namespace("ngeo", NGEO_URI)
ET.register_namespace("xsi", XSI_URI)
except Exception:
pass
root = ET.Element(NGEO_NS+DA_RESP,
{XSI_NS+"schemaLocation":SCHEMA_LOCATION})
ET.SubElement(root, NGEO_NS+MONITORINGSTATUS).text = "IN_PROGRESS"
pa_list = ET.SubElement(root, NGEO_NS+PRODACCESSLIST)
for url in urls:
pa = ET.SubElement(pa_list, NGEO_NS+PRODACCESS)
ET.SubElement(pa, NGEO_NS+PRODACCESSURL).text = url[1]
ET.SubElement(pa, NGEO_NS+PRODACCESSSTATUS).text = "READY"
ET.SubElement(pa, NGEO_NS+PRODDOWNLOADDIRECTORY).text = url[0]
if LOCAL_DEBUG > 0:
print "dAR:\n"+ DAR_PREAMBLE + ET.tostring(root)
return DAR_PREAMBLE + ET.tostring(root)
|
UTF-8
|
Python
| false | false | 2,014 |
3,513,283,260,192 |
354767c2a414370485206c1f84de8f53013f9744
|
10ac17df6b003c8fd0b3cf153903c960b8a0b3c6
|
/cummplotter.py
|
67e2895c8a1f8414491ecc7f8a52560b79291d2d
|
[] |
no_license
|
nippoo/astroimageprocessing
|
https://github.com/nippoo/astroimageprocessing
|
9b732e63ddfce24cabe0f220fb18796762a47e0e
|
16c1a154a743e3500a976a152305c2cbda46cf09
|
refs/heads/master
| 2016-09-06T02:09:07.914230 | 2014-03-28T12:06:36 | 2014-03-28T12:06:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
from starprocessor import StarProcessor
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import itertools
import csv
# finds galaxies and stores the corresponding data in the catalogue.
s = StarProcessor()
stars = np.load("catalogue.npy")
#print stars
fluxlist = np.array([[i['flux'], i['fluxerror']] for i in stars])
b = 80 #specifies the number of bins for the historgram
values, base = np.histogram(fluxlist[:,0], bins=b)
fluxlist = np.sort(fluxlist,axis=1)
# print np.where(fluxlist[:,0] == 0, fluxlist[:,0], fluxlist[:,1])
x_error = []
for first, second in itertools.izip(base, base[1:]):
x_error.append(np.std([t[0] for t in fluxlist if ((t[1] >= first) & (t[1] < second))]))
#fluxerror = np.array([[np.where(fluxlist[0] > i[0])] for i in base])
#[t for t in fluxlist if (fluxlist[0] > base[0][0])]
print x_error
cumulative = np.cumsum(values)
#x_error
y_error = cumulative**0.5
cumulative_log=np.log10(cumulative)
y_error_log=y_error*(2*cumulative*np.log(10))**-1
with open('cumplot_data_inc_errors.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['base','x_error','cumulative','y_error','log10(N)','y_error_log'])
for i in range(len(base)-1):
spamwriter.writerow([base[i],x_error[i], cumulative[i], y_error[i], cumulative_log[i], y_error_log[i]])
#print cumulative
#print y_error
plt.errorbar(base[:-1], cumulative,y_error,x_error,c='blue')
plt.semilogy()
plt.show()
|
UTF-8
|
Python
| false | false | 2,014 |
3,762,391,381,754 |
010e56428dde6102c38fd823bafbdea24d1d8309
|
36db24ab3ee198791eabb98db2056c699dc65415
|
/src/ProblemSets/ProblemSet01 - PeakFind/Code/problem.py
|
c31547dfc84bbc306f85a9629116dc729fcb0ec9
|
[] |
no_license
|
ConanZhang/6.006
|
https://github.com/ConanZhang/6.006
|
db2f1466e50f5f930744971964178a9672288ba3
|
9c44eb113ccf060d96a57b1f26eb8f73a426fb81
|
refs/heads/master
| 2015-08-12T13:45:55.911336 | 2014-08-08T00:39:25 | 2014-08-08T00:39:25 | 22,047,212 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Original problem
problemMatrix = [
[ 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2],
[ 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3],
[ 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4],
[ 7, 8, 9, 10, 11, 10, 9, 8, 7, 6, 5],
[ 8, 9, 10, 11, 12, 11, 10, 9, 8, 7, 6],
[ 7, 8, 9, 10, 11, 10, 9, 8, 7, 6, 5],
[ 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4],
[ 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3],
[ 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2],
[ 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1],
[ 2, 3, 4, 5, 6, 5, 4, 3, 2, 1, 0]
]
# Michael's counter example to Algorithm 3
# problemMatrix = [
# [ 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2],
# [ 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3],
# [ 6, 7, 8, 9, 10, 11, 8, 7, 6, 5, 4],
# [ 7, 8, 9, 10, 9, 10, 9, 8, 7, 6, 5],
# [ 8, 9, 10, 9, 12, 11, 10, 9, 8, 7, 6],
# [ 7, 8, 9, 10, 11, 10, 9, 8, 7, 6, 5],
# [ 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4],
# [ 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3],
# [ 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2],
# [ 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1],
# [ 2, 3, 4, 5, 6, 5, 4, 3, 2, 1, 0]
# ]
# Conan's counter example to Algorithm 3
# problemMatrix = [
# [ 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2],
# [ 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3],
# [ 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4],
# [ 7, 8, 9, 10, 11, 10, 9, 8, 7, 6, 5],
# [ 8, 9, 10, 11, 12, 11, 10, 9, 8, 7, 6],
# [ 7, 11, 9, 10, 11, 10, 9, 8, 7, 6, 5],
# [ 6, 12, 8, 9, 10, 9, 8, 7, 6, 5, 4],
# [ 5, 6, 7, 8, 7, 8, 7, 6, 5, 4, 3],
# [ 4, 5, 6, 7, 8, 9, 6, 5, 4, 3, 2],
# [ 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1],
# [ 2, 3, 4, 5, 6, 5, 4, 3, 2, 1, 0]
# ]
# MIT's counter example to Algorithm 3
# problemMatrix=[
# [0,0,9,8,0,0,0],
# [0,0,0,0,0,0,0],
# [0,1,0,0,0,0,0],
# [0,2,0,0,0,0,0],
# [0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0]
# ]
|
UTF-8
|
Python
| false | false | 2,014 |
14,559,939,143,577 |
021328651db601ac94419b3e37a75f3c85c9a4b4
|
9bbb1d240dc89f2567d8f0e8fcd264023a40d62a
|
/soulightrd/scripts/13_generate_project_activity.py
|
4044d0f6fa4d4dbf99a8514da8711b1f5eaa108d
|
[] |
no_license
|
vunhatminh241191/SoulightRd
|
https://github.com/vunhatminh241191/SoulightRd
|
256b19ab8797d3ef1e3613fb7a7fc6cc58806846
|
7727aaab2990fe6174d3601c470198324f7faf3f
|
refs/heads/master
| 2021-01-23T15:29:30.807748 | 2014-11-27T09:08:26 | 2014-11-27T09:08:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os, sys,random, datetime
SETTING_PATH = os.path.abspath(__file__ + "/../../")
PROJECT_PATH = os.path.abspath(__file__ + "/../../../")
sys.path.append(SETTING_PATH)
sys.path.append(PROJECT_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.contrib.auth.models import User
from soulightrd.apps.main.models import ProjectActivity, Project, Photo
from soulightrd.apps.main.models import OrganizationBoardMember
from soulightrd.apps.app_helper import get_any_admin_object, generate_unique_id
from soulightrd.apps.app_settings import DEFAULT_IMAGE_PATH_MAPPING, DEFAULT_IMAGE_UNIQUE_ID
from dummy_database import NAMES
from django import db
def main():
print "... RUNNING GENERATE PROJECT ACTIVITY ..."
project_activities = ProjectActivity.objects.all()
if len(project_activities) == 0:
admin = get_any_admin_object()
project_activity_picture = None
try:
project_activity_picture = Photo.objects.get(
unique_id=DEFAULT_IMAGE_UNIQUE_ID['default_project_activity_picture'])
except Photo.DoesNotExist:
project_activity_picture = Photo.objects.create(caption="default_project_activity_picture"
,user_post=admin,image=DEFAULT_IMAGE_PATH_MAPPING['default_project_activity_picture']
,unique_id=generate_unique_id("photo"))
try:
projects = Project.objects.all()
for project in projects:
year = random.choice(range(2005, 2014))
month = random.choice(range(1, 12))
day = random.choice(range(1, 28))
responsible_member = OrganizationBoardMember.objects.filter(
organization=project.organization)[0].user
project_activity = ProjectActivity.objects.create(
title='abcdef',
project=project,
description='done',
responsible_member=responsible_member,
date=datetime.datetime(year,month,day))
project_activity.image_proof.add(project_activity_picture)
project_activity.save()
print "Generate Project Activity Successfully"
except:
print "Generate Project Activity Failed"
raise
db.close_connection()
else:
print "Project Activity dummy data already created"
if __name__ == '__main__':
stage = sys.argv[1]
if stage != "prod":
main()
|
UTF-8
|
Python
| false | false | 2,014 |
5,549,097,766,780 |
016ad3f974bc32a79f4a6a2ecd8acef4b7716cd4
|
db6eeb60394d8df74ae5f453a3c93fa8809e7e8e
|
/djangoproject/core/urls/watch_urls.py
|
2ad93d6ec088f80e6c9931d276f2b7e1da7c560b
|
[
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft"
] |
non_permissive
|
gladson/www.freedomsponsors.org
|
https://github.com/gladson/www.freedomsponsors.org
|
e0bcbc800946c6ccc8922bbfd21d07f2f1d44b6c
|
c72ab36461e9de710b7f1dc16c159aa97882b533
|
refs/heads/master
| 2020-12-27T14:46:35.934996 | 2013-12-27T17:44:55 | 2013-12-27T17:44:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.conf.urls import patterns, url
urlpatterns = patterns('core.views.watch_views',
url(r'^issue/(?P<issue_id>\d+)/watch$', 'watchIssue'),
url(r'^issue/(?P<issue_id>\d+)/unwatch$', 'unwatchIssue'),
)
|
UTF-8
|
Python
| false | false | 2,013 |
19,490,561,611,712 |
6e27e3535fb1d2e1e83e2f06ea516fe3a559cbe5
|
6f02af3d95a773405058b1b7ce945633e52cb00f
|
/cork/__init__.py
|
e40184b0efbce84d7c8b4bf8ee7ec4e751032aa1
|
[
"LGPL-3.0-only"
] |
non_permissive
|
TheJF/bottle-cork
|
https://github.com/TheJF/bottle-cork
|
04033762c027694e5b1646449e6a50ed6a1ce105
|
ac8ba7d60a964d2fc922834ecdc9d8b71b5709d1
|
refs/heads/master
| 2021-01-18T09:54:48.112513 | 2012-11-19T22:47:52 | 2012-11-19T22:47:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from cork import Cork, AAAException, AuthException, Mailer
__version__ = '0.3'
|
UTF-8
|
Python
| false | false | 2,012 |
8,924,942,057,925 |
e3392c5f428ec2820882c3026b7143eb2f84140a
|
739ca7304f1775320f8ab73a16249589c281f041
|
/split.py
|
5c40b1757a06dbe3094f6f5bafdb3882a727517b
|
[] |
no_license
|
haosharon/laughing-batman
|
https://github.com/haosharon/laughing-batman
|
228d43d18bf5604090d6997faf15afd7e767f452
|
f9559f8c086f6266ec7b64c0200d9592a279d5e8
|
refs/heads/master
| 2016-09-06T18:53:10.392867 | 2013-11-25T03:55:19 | 2013-11-25T03:55:19 | 14,665,270 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import subprocess
import sys
def print_message(message):
border = '********************************'
print
print border
print message
print border
print
def execute_command(cmd):
print '$ ' + cmd
sub = subprocess.Popen(cmd, shell=True)
sub.communicate()
return
def get_times(file_name):
f = open(file_name, 'r')
times = []
for line in f:
split = line.split(',')
time = split[0].strip()
# convert time to seconds
positions = time.split(':')
seconds = 0
for position in positions:
seconds *= 60
seconds += int(position)
tup = (seconds, split[1].strip())
times.append(tup)
return times
# split video into intermediate files, given a list of time tuples
def split(input_name, times):
print_message('Splitting video into intermediate files')
intermediate_names = []
index = 0
for time in times:
intermediate_name = "intermediate_%(index)s" % \
{'index': index}
intermediate_names.append(intermediate_name)
intermediate_file = intermediate_name + '.mp4'
start = time[0]
duration = time[1]
cmd = "ffmpeg -ss %(start)s -i %(input_name)s -t %(duration)s %(output)s" % \
{'input_name': input_name, 'start': start, 'duration': duration, 'output': intermediate_file}
print_message('splitting ' + intermediate_name)
execute_command(cmd)
index += 1
return intermediate_names
# converts mp4 files to mpg
def mp4_to_mpg(intermediate_names):
print_message('Converting intermediate files to mpg')
for name in intermediate_names:
cmd = "ffmpeg -i %(intermediate)s -qscale:v 1 %(mpg)s" % \
{'intermediate': name + '.mp4', 'mpg': name + '.mpg'}
print_message('converting ' + name)
execute_command(cmd)
print_message('Done converting all')
# joins many mpg files together
def concat(intermediate_names):
print_message('Joining mpg files together')
file_all = 'intermediate_all.mpg'
cmd = "cat "
for name in intermediate_names:
cmd += name + '.mpg '
cmd += "> " + file_all
execute_command(cmd)
return file_all
# convert final mgp file back to mp4
def mpg_to_mp4(mpg, output):
print_message("Converting mpg file back to mp4")
cmd = "ffmpeg -i %(name)s -qscale:v 2 %(output)s" % \
{'name': mpg, 'output': output}
execute_command(cmd)
# remove all intermediate files created
def clean_up(intermediate_names, file_all):
print_message('Removing intermediate files')
cmd = ''
for name in intermediate_names:
cmd += "rm %(name)s.mp4 %(name)s.mpg;" % \
{'name': name}
execute_command(cmd)
cmd = 'rm ' + file_all
execute_command(cmd)
return
# main
def main(input_name, times_file, output_name):
times = get_times(times_file)
intermediate_names = split(input_name, times)
mp4_to_mpg(intermediate_names)
file_all = concat(intermediate_names)
mpg_to_mp4(file_all, output_name)
clean_up(intermediate_names, file_all)
print_message('Done.')
if __name__ == '__main__':
if len(sys.argv) >= 4:
input_name = sys.argv[1]
times_file = sys.argv[2]
output_name = sys.argv[3]
main(input_name, times_file, output_name)
|
UTF-8
|
Python
| false | false | 2,013 |
13,958,643,717,948 |
4b0ba60e177a3c535f6990fdc161527764818fc7
|
0d7a6a9c7a2ea6deb2278224ed98139baeacb728
|
/pylint_django/transforms/transforms/django_db_models_fields.py
|
88d7dd3c0cc4803816eddaffe00c72a346645bda
|
[
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only"
] |
non_permissive
|
mbarrien/pylint-django
|
https://github.com/mbarrien/pylint-django
|
9eabf3da4e2040036680b516b529516be2101689
|
4918e91180783acf3b5b2e461e4f9db5871643af
|
refs/heads/master
| 2020-12-11T07:48:38.580567 | 2014-09-09T13:26:11 | 2014-09-09T13:26:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class CharField(object):
split = lambda x: None
class DateField(object):
strftime = lambda x: None
|
UTF-8
|
Python
| false | false | 2,014 |
17,806,934,411,054 |
ba144f98bd8e4508aa327463892b311b81dd0494
|
94c33daa02c2834b35e9ad271aa56e9317762916
|
/bin/align_vdj.py
|
6c306661d65050687220f36707536171b2a305ce
|
[] |
no_license
|
xflicsu/vdj
|
https://github.com/xflicsu/vdj
|
db8128dd3806296253713e900c70af22bfcff6cd
|
009f0a4ad982b0696e070a8c29723f956520a794
|
refs/heads/master
| 2021-01-18T01:00:07.906688 | 2014-04-23T03:56:24 | 2014-04-23T03:56:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#! /usr/bin/env python
import sys
import optparse
import vdj
import vdj.alignment
parser = optparse.OptionParser()
parser.add_option('-L','--locus',action='append',dest='loci')
parser.add_option('-R','--rigorous',action='store_true',default=False)
parser.add_option('-D','--debug',action='store_true',default=False)
(options, args) = parser.parse_args()
if len(args) == 2:
inhandle = open(args[0],'r')
outhandle = open(args[1],'w')
elif len(args) == 1:
inhandle = open(args[0],'r')
outhandle = sys.stdout
elif len(args) == 0:
inhandle = sys.stdin
outhandle = sys.stdout
else:
raise Exception, "Wrong number of arguments."
if options.debug:
import pdb
pdb.set_trace()
aligner = vdj.alignment.vdj_aligner_combined(loci=options.loci,rigorous=options.rigorous)
for chain in vdj.parse_imgt(inhandle):
aligner.align_chain(chain)
print >>outhandle, chain
|
UTF-8
|
Python
| false | false | 2,014 |
17,325,898,109,937 |
6262f406291d7bd0c1d24818b0af58f7b3cbffbd
|
19cc2b595eff6a995ddf5a95e8c5235ec08aa35b
|
/tests/charset_converter_tests.py
|
d3ce69359615d143ae0031e238a0b457e9c91b55
|
[] |
no_license
|
esancho/baudot
|
https://github.com/esancho/baudot
|
de802c06bcbe12c0c4a67d5f2869bbd00ad7d0c1
|
1ed787839f3678586e4c7bc229dc1c93ae420832
|
refs/heads/master
| 2021-05-25T10:41:37.786794 | 2011-07-04T00:42:19 | 2011-07-04T00:42:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import unittest
import tempfile
from md5 import md5
from pkg_resources import resource_filename
from path import path
from baudot.core import CharsetConverter
class CharsetConverterTest(unittest.TestCase):
def setUp(self):
self.converter = CharsetConverter()
self.samples = path(resource_filename(__package__, "samples"))
def test_detection(self):
file = self.samples / "sample1-ISO-8859-1.txt"
self.assertEquals("ISO-8859-1", self.converter.detect_encoding(file).charset)
file = self.samples / "sample1-UTF-8.txt"
self.assertEquals("UTF-8", self.converter.detect_encoding(file).charset)
def test_convertion_from_iso_to_utf(self):
# setup files
iso = self.samples / "sample1-ISO-8859-1.txt"
iso_checksum = self.__checksum(iso)
utf = self.samples / "sample1-UTF-8.txt"
utf_checksum = self.__checksum(utf)
# create temp file
fd, filename = tempfile.mkstemp(prefix="baudot")
tmp = path(filename)
tmp_checksum = self.__checksum(tmp)
# validate before convertion
self.assertNotEquals(iso_checksum, utf_checksum)
self.assertNotEquals(tmp_checksum, utf_checksum)
self.assertNotEquals(iso_checksum, tmp_checksum)
# convert files
self.converter.convert_encoding(iso, tmp, "ISO-8859-1", "UTF-8")
tmp_checksum = self.__checksum(tmp)
# validate output
self.assertNotEquals(iso_checksum, tmp_checksum)
self.assertEquals(tmp_checksum, utf_checksum)
tmp.remove()
self.assertFalse(tmp.exists())
def test_get_encodings(self):
available = self.converter.get_encodings()
self.assertIn("UTF-8", available)
self.assertIn("ISO-8859-1", available)
self.assertIn("windows-1251", available)
def __checksum(self, file):
block_size = 0x10000
def upd(m, data):
m.update(data)
return m
fd = open(file, "rb")
try:
contents = iter(lambda: fd.read(block_size), "")
m = reduce(upd, contents, md5())
return m.hexdigest()
finally:
fd.close()
|
UTF-8
|
Python
| false | false | 2,011 |
10,582,799,452,869 |
d5fecbe124f157195f8a809872e2436547e5e686
|
b8379b73f6665a74b14d3d5796cf7c8351852b85
|
/eldesc/3_5.py
|
bbb31357da7e278f1ca90c8cc84279a555bf7fbb
|
[
"BSD-3-Clause"
] |
permissive
|
certik/sfepy
|
https://github.com/certik/sfepy
|
ceb766ee51821ecd1f2bfa4f5611ef87abe88805
|
f89b2682df0cdba57c64caa6fe362855f2671465
|
refs/heads/master
| 2020-08-06T17:07:15.780747 | 2009-01-15T16:47:58 | 2009-01-15T16:47:58 | 110,970 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
name = '3_5'
name = '3D_5Node'
v_coors = {'m0' : (-1,-1, -1),
'm1' : ( 1,-1, -1),
'm2' : ( 1, 1, -1),
'm3' : (-1, 1, -1),
'm4' : ( 0, 0, 1)}
v_edges = (('m0', 'm1'),
('m1', 'm2'),
('m2', 'm3'),
('m3', 'm0'),
('m0', 'm4'),
('m1', 'm4'),
('m2', 'm4'),
('m3', 'm4'))
v_faces = (('m0', 'm3', 'm2', 'm1'),
('m0', 'm4', 'm3', ''),
('m0', 'm1', 'm4', ''),
('m1', 'm2', 'm4', ''),
('m2', 'm3', 'm4', ''))
s_coors = {'s0' : ( -1, -1),
's1' : ( 1, -1),
's2' : ( 1, 1),
's3' : ( -1, 1)}
s_edges = {'s3' : (('s0', 's1'),
('s1', 's3'),
('s3', 's0')),
's4' : (('s0', 's1'),
('s1', 's2'),
('s2', 's3'),
('s3', 's0'))}
s_faces = {'s3' : ('s0', 's1', 's3'), 's4' : ('s0', 's1', 's2', 's3')}
interpolation = '3_5_P1P'
|
UTF-8
|
Python
| false | false | 2,009 |
7,851,200,264,520 |
364a400712b2028bf31f186d69d801b0f5a6700c
|
6cea35ad90d80191d4a088685d9192fb43f39ee2
|
/example/server.py
|
29531a820e37b9e6b06d37f7e88d8cce8d23fb99
|
[] |
no_license
|
realtime-system/pysage
|
https://github.com/realtime-system/pysage
|
de48f538cae24caf08829d9311dfe64e2856c7be
|
6aef3a6f3c68ae8622f921254ee3815cd5cade07
|
refs/heads/master
| 2016-09-06T09:38:46.088683 | 2011-11-09T23:20:06 | 2011-11-09T23:20:06 | 24,540,925 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# server.py
import sys
import os
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from pysage.network import *
nmanager = NetworkManager.get_singleton()
nmanager.start_server(8000)
class TestMessage(Packet):
properties = ['secret']
types = ['p']
packet_type = 101
class TestMessageReceiver(PacketReceiver):
subscriptions = ['TestMessage']
def handle_TestMessage(self, msg):
print 'Got "%s"' % msg.get_property('secret')
return True
nmanager.register_object(TestMessageReceiver())
while True:
time.sleep(.33)
nmanager.tick()
|
UTF-8
|
Python
| false | false | 2,011 |
15,350,213,130,411 |
7ec40a563d6b411861dcf937e77af5bca064d3a3
|
09fc99d3f47bca5188971fd45212cc7a55819061
|
/GradientDescent/pkg/algorithm.py
|
1319cde1067c278012a243834e7077a09f220190
|
[] |
no_license
|
guyo14/IAPractica1
|
https://github.com/guyo14/IAPractica1
|
4f4bbe3310aa1274eab8055590c2f6b170e14155
|
81b9bdb5d2ef962bbf5c977c9f9ba4dc0394265e
|
refs/heads/master
| 2021-01-21T08:15:06.774935 | 2014-10-28T06:30:17 | 2014-10-28T06:30:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
Created on Oct 27, 2014
@author: alejandro
'''
import random
import files
from wxPython._wx import NULL
def gradient_descent(xs, ys, alpha, tolerance, iterations):
m = len(xs)
if m == len(ys):
for row in xs:
row.insert(0,1)
ranges = get_ranges(xs)
r = len(xs[0])
thetas = [None] * r
list_cost_functions = []
cost_function = NULL
for n in range(0, r):
thetas[n] = random.uniform(-1, 1)
for n in range(0, iterations):
new_cost_function = 0
for j in range(0, r):
theta = 0
for i in range(0, m):
sumh = 0
for h in range(0, r):
sumh += xs[i][h] * thetas[h]
theta += ((sumh - ys[i][0]) * xs[i][j])
theta = alpha * theta / m
thetas[j] = thetas[j] - theta
new_cost_function = get_cost_function(thetas, xs, ys)
list_cost_functions.append(str(new_cost_function))
if cost_function != NULL and abs(cost_function - new_cost_function) <= tolerance:
break
cost_function = new_cost_function;
files.writeFile("costFunction", list_cost_functions)
return thetas
return NULL
def get_cost_function(thetas, xs, ys):
m = len(xs)
r = len(xs[0])
cost_function = 0
for i in range(0, m):
summ = 0
for j in range(0, r):
summ = thetas[j] * xs[i][j]
summ -= ys[i][0]
summ = summ * summ
cost_function += summ
cost_function = cost_function / ( 2 * m )
return cost_function
def get_ranges(rows):
result = []
r = len(rows[0])
for x in range(0, r):
xmax = rows[0][x]
xmin = rows[0][x]
for row in rows:
if row[x] > max:
xmax = row[x]
elif row[x] < min:
xmin = row[x]
result.append([xmin, xmax])
return result
|
UTF-8
|
Python
| false | false | 2,014 |
11,802,570,171,390 |
e732e348bcee0f80ee32a90b3dfc4e57ef1607d9
|
58ef0d1e51c4b35077e995cc93486d0d231db5c7
|
/mightylemon/apps/events/models.py
|
f411f8c526fdb72506a1dce49569c4bbea232c76
|
[
"BSD-3-Clause"
] |
permissive
|
justinabrahms/mightylemon
|
https://github.com/justinabrahms/mightylemon
|
6a0348a55cc5becb73ed144b214bf8dfea8980a1
|
8e326492273fe7f824e2b044bb59c828522faa25
|
refs/heads/master
| 2021-01-20T21:37:40.188849 | 2010-01-25T13:53:39 | 2010-01-25T13:53:39 | 137,021 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.db import models
from datetime import date
class Event(models.Model):
"""
Represents an event you're attending.
"""
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
description = models.TextField()
location = models.CharField(max_length=150)
start_date = models.DateField(default=date.today)
end_date = models.DateField(blank=True, null=True)
link_to_url = models.URLField(max_length=250, blank=True, null=True)
class Meta:
ordering = ["-start_date"]
def is_old(self):
if self.start_date < date.today():
return True
return False
def __unicode__(self):
return "%s on %s" % (self.name, self.start_date)
|
UTF-8
|
Python
| false | false | 2,010 |
7,954,279,480,226 |
5ebcc0faba5834918d9c1fc3b92efea1ca3e337c
|
7f719501a5fddf4ba1c7cdc3c27ecfb39d56b03a
|
/wsgi_handler.py
|
82349e8b679ee7bf018c6fc078a90e67455271b3
|
[] |
no_license
|
bricetebbs/sharider
|
https://github.com/bricetebbs/sharider
|
b8096bc49e0bc1a5fe08a88e829ecafcbfa882f4
|
db0b5d61cd2816264b0d4aed25c73fa1242a34f1
|
refs/heads/master
| 2021-01-19T11:32:29.404059 | 2013-12-14T06:28:17 | 2013-12-14T06:28:17 | 3,133,543 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os
import sys
sys.stdout = sys.stderr
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
sys.path.append('/home/nikto/sites/www.spoketransit.com/sharider/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'sharider.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
|
UTF-8
|
Python
| false | false | 2,013 |
481,036,378,967 |
9610191c36721ac730179887ca41cdd8fdc8b491
|
4533d4c727c15ba217e3e736261790ee34dbc5ce
|
/moocng/teacheradmin/forms.py
|
285835b79068ac28840293509712e962fec6d445
|
[
"Apache-2.0"
] |
permissive
|
kaleidos/moocng
|
https://github.com/kaleidos/moocng
|
6b615ef176175a7283bc06194567bbf672bb4eeb
|
4ed6737be215a71b7f80bf7f37a2fc0fc35681c1
|
refs/heads/master
| 2021-01-18T06:12:39.057825 | 2013-10-16T08:39:39 | 2013-10-16T08:39:39 | 8,276,636 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
# Copyright 2012-2013 Rooter Analysis S.L.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django import forms
from django.core.files.images import get_image_dimensions
from django.utils.translation import ugettext_lazy as _
from tinymce.widgets import TinyMCE
from moocng.courses.forms import AnnouncementForm as CoursesAnnouncementForm
from moocng.courses.models import Course, StaticPage
from moocng.forms import (BootstrapMixin, BootstrapClearableFileInput,
HTML5DateInput, BootstrapInlineRadioSelect)
from moocng.teacheradmin.models import MassiveEmail
from moocng.media_contents import media_content_extract_id
from moocng.assets.models import Asset
class CourseForm(forms.ModelForm):
"""
Course form. Make some changes to the form classes and clean the media fields
to prevent errors processing the content.
:returns: HTML Form
..versionadded:: 0.1
"""
error_messages = {
'invalid_image': _('Image must be {0}px x {1}px').format(Course.THUMBNAIL_WIDTH, Course.THUMBNAIL_HEIGHT),
}
class Meta:
model = Course
exclude = ('slug', 'teachers', 'owner', 'students')
widgets = {
'start_date': HTML5DateInput(),
'end_date': HTML5DateInput(),
'certification_banner': BootstrapClearableFileInput(),
'status': BootstrapInlineRadioSelect(),
}
def __init__(self, *args, **kwargs):
super(CourseForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
widget = field.widget
if isinstance(widget, (forms.widgets.TextInput, forms.widgets.DateInput)):
widget.attrs['class'] = 'input-xlarge'
elif isinstance(widget, forms.widgets.Textarea):
widget.mce_attrs['width'] = '780' # bootstrap span10
def clean_promotion_media_content_id(self):
content_type = self.data.get('promotion_media_content_type')
content_id = self.data.get('promotion_media_content_id')
if content_type and content_id:
if not media_content_extract_id(content_type, content_id):
raise forms.ValidationError(_('Invalid content id or url'))
elif content_type and not content_id:
raise forms.ValidationError(_('Invalid content id or url'))
return content_id
def clean_promotion_media_content_type(self):
content_type = self.data.get('promotion_media_content_type')
content_id = self.data.get('promotion_media_content_id')
if content_id and not content_type:
raise forms.ValidationError(_('You must select a content type or remove the content id'))
return content_type
def clean_thumbnail(self):
thumbnail = self.cleaned_data.get("thumbnail")
if thumbnail:
w, h = get_image_dimensions(thumbnail)
if w < Course.THUMBNAIL_WIDTH or h < Course.THUMBNAIL_HEIGHT:
raise forms.ValidationError(self.error_messages['invalid_image'])
return thumbnail
class AnnouncementForm(CoursesAnnouncementForm, BootstrapMixin):
"""
Announcement form. Inherits from CoursesAnnouncementForm and adds a send_email
field.
:returns: HTML Form
.. versionadded:: 0.1
"""
send_email = forms.BooleanField(
required=False,
label=_(u'Send the announcement via email to all the students in this course'),
initial=False,
help_text=_(u'Please use this with caution as some courses has many students'),
)
class AssetTeacherForm(forms.ModelForm, BootstrapMixin):
"""
AssetTeacher model form
:returns: HTML Form
.. versionadded:: 0.1
"""
class Meta:
model = Asset
exclude = ('slot_duration', 'max_bookable_slots', 'reservation_in_advance',
'cancelation_in_advance',)
class MassiveEmailForm(forms.ModelForm, BootstrapMixin):
"""
Massive email model form. Adapts subject and message fields size.
:returns: HTML Form
.. versionadded:: 0.1
"""
class Meta:
model = MassiveEmail
exclude = ('course', )
widgets = {
'subject': forms.TextInput(attrs={'class': 'input-xxlarge'}),
'message': TinyMCE(attrs={'class': 'input-xxlarge'}),
}
class StaticPageForm(forms.ModelForm, BootstrapMixin):
class Meta:
model = StaticPage
include = ('title', 'body',)
widgets = {
'title': forms.TextInput(attrs={'class': 'input-xxlarge'}),
'body': TinyMCE(attrs={'class': 'input-xxlarge'}),
}
def __init__(self, *args, **kwargs):
super(StaticPageForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
widget = field.widget
if isinstance(widget, (forms.widgets.TextInput, forms.widgets.DateInput)):
widget.attrs['class'] = 'input-xxlarge'
elif isinstance(widget, forms.widgets.Textarea):
widget.mce_attrs['width'] = '780' # bootstrap span10
|
UTF-8
|
Python
| false | false | 2,013 |
12,893,491,825,796 |
e7165336a6508f18d196df7a0c3da33b838ebb73
|
3e40e4124f313ede2009de17ec818cb9165fb59f
|
/PythonProblems/validate_input.py
|
f4a788d5946d605f5a5cec6867d95297965258e2
|
[] |
no_license
|
c0untzer0/StudyProjects
|
https://github.com/c0untzer0/StudyProjects
|
7a1c92cb10a8ae6b3cf8d5fdd58cb685aabb6835
|
c40b6d54c741cbaf2a0d6377e84e45e17d2e3410
|
refs/heads/master
| 2021-01-22T20:35:39.867739 | 2013-07-10T19:57:37 | 2013-07-10T19:57:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/local/bin/python3
#-*- coding: utf-8 -*-
#
# validate_input.py
# PythonProblems
#
# Created by Johan Cabrera on 2/15/13.
# Copyright (c) 2013 Johan Cabrera. All rights reserved.
#
#import os
#import sys
#import re
#import random
valid_inputs=['yes','no','maybe']
input_query_string='Type %s: ' % ' or '.join(valid_inputs)
while True:
s = input(input_query_string)
if s in valid_inputs:
break
print("Wrong! Try again.")
print(s)
|
UTF-8
|
Python
| false | false | 2,013 |
2,774,548,878,228 |
f35ac856a86205976e2d7cd8fa3337a98d62b959
|
36163a05070a9cd0daab7c8b18b49053e0365bed
|
/src/python/WMCore/TaskQueue/Pilot/__init__.py
|
5709455f2e1b93084751e5e2992ab1695a1b78ec
|
[] |
no_license
|
sryufnal/WMCore
|
https://github.com/sryufnal/WMCore
|
472b465d1e9cff8af62b4f4a4587fd3927f82786
|
9575691bd7383e4de8bcdf83714ec71b3fec6aa7
|
refs/heads/master
| 2021-01-16T00:27:39.208561 | 2011-09-09T20:36:15 | 2011-09-09T20:36:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
"""
_PilotJob_
Pilot Job responsible for interacting with TaskQueue
"""
__all__ = []
|
UTF-8
|
Python
| false | false | 2,011 |
14,714,557,960,258 |
42ef31a022fc9e7ce09f8f0293ccef1530b613f5
|
91b6e767f04eae3681a72918bc0d84ee3ec9b09c
|
/data/make_sample.py
|
eff7a7f8ab990af717cc11b2a2e9a97c8457ef8f
|
[] |
no_license
|
shenli-uiuc/Centaur
|
https://github.com/shenli-uiuc/Centaur
|
6e6fb456f3d37e566a76d2d7a8b68d0750314f02
|
4e19055520fe350139d5733b912eaf38d51f8278
|
refs/heads/master
| 2021-01-10T20:15:34.468104 | 2013-04-20T21:54:02 | 2013-04-20T21:54:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
fin = open("vcoors", "r")
fout = open("small_coors", "w")
import random
sampleRate = 0.5
for line in fin:
if random.random() > sampleRate:
continue
fout.write(line)
fin.close()
fout.close()
|
UTF-8
|
Python
| false | false | 2,013 |
5,609,227,328,574 |
6d47bb7d99a6d6776fe300f58c273c4bf0c85a96
|
a6700751b026fa2be3900775ede95b698d49874f
|
/sctms/urls/tour.py
|
528beb706418a2b7ed88603e778d60e57a017873
|
[] |
no_license
|
martymarty/sctms
|
https://github.com/martymarty/sctms
|
78111e9df7d759fb65ea31fae2861d81674e0021
|
bf6943a79ffcaea455a2da28ad6c0bde2eb4a323
|
refs/heads/master
| 2021-01-17T21:37:46.674925 | 2011-07-06T16:25:22 | 2011-07-06T16:25:22 | 1,185,259 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from urls.base import pattern_list, sections, _404_below_this_
urlpatterns = pattern_list(
sections['nsl'],
sections['tms'],
_404_below_this_,
sections['admin'],
sections['cms'],
sections['irc'],
sections['pages'],
)
|
UTF-8
|
Python
| false | false | 2,011 |
7,198,365,231,681 |
df6dd7e8ddfc368cdc6120c92d304ee45b554b51
|
8152e548b15c2ae040e300883f3ead8e5cce0bcd
|
/gui/ui/accountdialog.py
|
1281975d4c780f49720ae9c0a46bccc68a395cbb
|
[
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only"
] |
non_permissive
|
guliujian/openkeeper
|
https://github.com/guliujian/openkeeper
|
1c97659d9c254c8a5db5c88c146e3ec3bbf15164
|
3246c268ecd1016db76e672f1b30db0d0f905eae
|
refs/heads/master
| 2020-04-10T17:14:14.835630 | 2010-11-17T15:04:49 | 2010-11-17T15:04:49 | 39,726,462 | 1 | 0 | null | true | 2015-07-26T13:29:17 | 2015-07-26T13:29:15 | 2013-11-23T10:06:05 | 2010-11-17T15:06:43 | 29,882 | 0 | 0 | 0 | null | null | null |
# -*- coding: utf-8 -*-
"""
Module implementing AccountDialog.
"""
from PyQt4 import QtCore
from PyQt4.QtGui import QDialog, QTreeWidgetItem
from PyQt4.QtCore import pyqtSignature, QStringList
from Ui_accountdialog import Ui_AccountDialog
from ui.addaccountdialog import AddAccountDialog
try:
_fromUtf8 = QtCore.QString.fromUtf8
_toUtf8 = QtCore.QString.toUtf8
except AttributeError:
_fromUtf8 = lambda s: s
_toUtf8 = lambda s: s
def to_s(s):
return str(_toUtf8(s))
class AccountDialog(QDialog, Ui_AccountDialog):
"""
Class documentation goes here.
"""
def __init__(self, parent = None):
"""
Constructor
"""
QDialog.__init__(self, parent)
self.setupUi(self)
self.refreshAccounts()
@pyqtSignature("")
def on_pushButton_add_clicked(self):
"""
添加账户
"""
AddAccountDialog(self).show()
def refreshAccounts(self):
self.accounts.clear()
conf = self.parent().config
for item in conf["outter_users"].keys():
if item == conf["outter_default_user"]:
self.accounts.addTopLevelItem(
QTreeWidgetItem( QStringList([_fromUtf8(item),_fromUtf8("YES"),_fromUtf8("是")])))
else:
self.accounts.addTopLevelItem(
QTreeWidgetItem( QStringList([_fromUtf8(item),_fromUtf8("YES"),_fromUtf8("否")])))
@pyqtSignature("")
def on_pushButton_edit_clicked(self):
user = to_s(self.accounts.currentItem().text(0))
self.parent().log.info(user)
if True: # for outter
AddAccountDialog(self,
{"user":user,"pass":self.parent().config["outter_users"][user],"type":"outter"}
).show()
@pyqtSignature("")
def on_pushButton_delete_clicked(self):
"""
delete a user
"""
conf = self.parent().config
user = to_s(self.accounts.currentItem().text(0))
type = to_s(self.accounts.currentItem().text(1))
if user in conf["outter_users"].keys() and "YES" == type:
del conf["outter_users"][user]
self.refreshAccounts()
self.parent().save_config()
self.parent().refresh_gui()
@pyqtSignature("")
def on_pushButton_setDefault_clicked(self):
"""
Set it as default
"""
conf = self.parent().config
user = to_s(self.accounts.currentItem().text(0))
type = to_s(self.accounts.currentItem().text(1))
if user in conf["outter_users"].keys() and "YES" == type:
self.parent().log.info("setting outter user %s as default "%user)
conf["outter_default_user"]=user
self.refreshAccounts()
self.parent().save_config()
self.parent().refresh_gui()
|
UTF-8
|
Python
| false | false | 2,010 |
8,108,898,292,612 |
6e96a44938be717cf999c708fa92604b4308ff35
|
66fd7322c00abe44d5d479af1cdafbebdb806b33
|
/klaasculator/debug.py
|
b7c9bf7dc0c50c722e99b25dc2747b716836e4ae
|
[] |
no_license
|
Tbutje/klaasculator_3
|
https://github.com/Tbutje/klaasculator_3
|
25d3e4197f289278564a7817c9fe1917dc510022
|
19de81b83fd3ba7cef9a6b4742728e8ac677ecff
|
refs/heads/master
| 2021-01-22T08:59:34.400360 | 2014-04-23T14:48:48 | 2014-04-23T14:48:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from compileer import compileeralles
from debcred import *
from powertools import *
from relaties import *
import csv
class Debug:
def __init__(self):
self.conf = Config()
self.rel = Relaties()
self.bdatum = getbegindatum()
self.edatum = geteinddatum()
self.begindc = Sheet_jr_ro('BeginDC')
self.log = False # dit logt stuff if true
if self.log:
csvfile = open('log_debug_journaal.csv', 'wb')
self.logwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
self.verder = True
ok = True
self.error = ''
# ok returned FALSE als er ergens iets niet ok is
# optioneel kan self.verder aangeven dat het al klaar is
# probleem is dat als er een fout gevonden wordt ok False blijft
# ook nadat je verberterd hebt
# misschien dubbele check doen? beetje loos. dan maar geen berichtje
# als je alles goed verbeterd hebt.
if self.verder:
ok = self.check_beginbalans(ok)
if self.verder:
ok = self.check_begindc(ok)
# maak check voor totaal begin dc / post == beginbalans
if self.verder:
ok = self.check_begindc_x_beginbalans(ok)
if self.verder:
ok = self.check_journaal(ok)
# close log
if self.log:
csvfile.close()
# even een schermpje als er geen fouten waren
if ok:
title = 'Gefeliciteerd'
text = 'Geen fouten gevonden.'
window = gtkwindow(title)
vbox = gtkvbox()
vbox.pack_start(gtk.Label(text))
button = gtk.Button(stock = gtk.STOCK_OK)
button.connect('clicked', self.sluiten, window)
vbox.pack_start(button)
window.add(vbox)
window.show_all()
gtk.main()
def check_balansregel(self, balansregel):
"""Controleert een balansregel."""
# bestaat de rekening als blanansrekening, gooit Fout als het niet zo is
try:
rek = self.conf.getrekening(balansregel.rekening, BALANSREKENING)
if rek.naam != balansregel.naam:
self.error = 'De naam van rekening %i komt niet overeen met die in het configuratiebestand (\'%s\' vs\' %s\')' % (balansregel.rekening, balansregel.naam, rek.naam)
return False
except Fout, f: # rekening bestaat niet afvangen
self.error = str(f)
return False
return True
def check_begindcregel(self, begindc):
"""Controleert een regel uit de begindc-lijst."""
try:
rek = self.conf.getrekening(begindc.rekening, BALANSREKENING)
if not self.rel.isrelatierekening(rek.naam):
self.error = '%i is geen relatierekening.' % rek.nummer
return False
except Fout, f:
self.error = str(f)
return False
if not self.rel.exist(begindc.omschrijving):
self.error = '\'%s\' staat niet in het relatiebestand.' % begindc.omschrijving
return False
if begindc.datum > self.bdatum:
d = inttodate(self.bdatum)
self.error = 'De datum is voor na de begindatum (%i-%i-%i)' % (d[0], d[1], d[2])
return False
return True
def check_boekstuk(self, boekstuk):
"""Check of een boekstuk deugt.
Geeft True als het deugt, anders False.
"""
# is het in balans:
if not boekstuk.inbalans():
self.error = 'Dit boekstuk is niet in balans.'
return False
# ligt de datum tussen begin- en einddatum
if boekstuk.datum < self.bdatum:
self.error = 'De datum is voor de begindatum (%i-%i-%i).' % inttodate(self.bdatum)
return False
elif boekstuk.datum > self.edatum:
self.error = 'De datum is na de einddatum (%i-%i-%i).' % inttodate(self.edatum)
return False
# afzonderlijke regels
# als boekstuk niet te groot is. 100?
if len(boekstuk) < 100:
for b in boekstuk:
# print b
try:
# controleer of de rekening bestaat (gooit exceptie als dat niet zo is)
r = self.conf.getrekening(b.rekening).naam
if self.rel.isrelatierekening(r) and not self.rel.exist(b.omschrijving):
self.error = '%s is niet gedefinieerd in het relatiebestand.' % b.omschrijving
return False
except: # exceptie voor als de rekening niet bestaat afvangen
self.error = 'Rekening %i is niet gedefinieerd.' % b.rekening
return False
# heeft het een tegenrekening
if not b.tegen:
self.error = 'Tegenrekening ontbreekt.'
return False
return True
def check_beginbalans(self, ok):
"""Checkt de beginbalans."""
s = Sheet_bl_ro('Beginbalans')
si = iter(s)
w = Euro()
try:
while self.verder:
b = si.next()
w += b.waarde
while self.check_balansregel(b):
b = si.next()
w += b.waarde
ok = False
self.error_balansregel(b)
except StopIteration:
pass
if w.true() and self.verder:
ok = False
window = gtkwindow('Fout')
vbox = gtkvbox()
vbox.pack_start(gtk.Label('De beginbalans is niet in balans'))
bbox = gtkhbuttonbox()
verder = gtk.Button(stock = gtk.STOCK_GO_FORWARD)
verder.connect('clicked', self.verder_bl, window)
sluiten = gtk.Button(stock = gtk.STOCK_CLOSE)
sluiten.connect('clicked', self.sluiten, window)
bbox.pack_start(verder)
bbox.pack_start(sluiten)
vbox.pack_start(bbox)
window.add(vbox)
window.show_all()
gtk.main()
return ok
def check_begindc(self, ok):
"""Checkt de beginlijst debiteuren/crediteuren."""
s = Sheet_jr_ro('BeginDC')
bdciter = iter(s)
try:
while self.verder:
b = bdciter.next()
while self.check_begindcregel(b):
b = bdciter.next()
ok = False
self.error_begindc(b, bdciter.i)
except StopIteration:
pass
return ok
def check_journaal(self, ok):
"""Checkt het Journaal."""
# iterator over het journaal
biter = iter(BoekstukIter())
# writer heeft nog wat review nodig
writer = BoekstukWriter('Journaal')
#add log
try:
# zolang we verder willen
while self.verder:
b = biter.next()
if(self.log):
self.logwriter.writerow(b)
while self.check_boekstuk(b): # controlleer
b = biter.next()
ok = False
# er is een fout
self.error_boekstuk(b, writer, biter.row)
except StopIteration:
pass
return ok
def error_boekstuk(self, boekstuk, writer, row):
"""Dit is om een error in een boekstuk te laten zien."""
# print self.error
# print boekstuk
d = inttodate(boekstuk.datum)
window = gtkwindow('Fout in boekstuk %i op %i-%i-%i' % (boekstuk.nummer, d[0], d[1], d[2]))
vbox = gtkvbox()
label = gtk.Label('Fout:\n\n%s' % self.error)
vbox.pack_start(label, expand = False)
bw = BoekstukWidget()
bw.set_editable(True)
bw.set_boekstuk(boekstuk)
vbox.pack_start(bw.widget)
bbox = gtkhbuttonbox()
volgende = gtk.Button(stock = gtk.STOCK_GO_FORWARD)
volgende.connect('clicked', self.volgende_boekstuk, bw, row, writer, window)
bbox.pack_start(volgende)
sluiten = gtk.Button(stock = gtk.STOCK_CLOSE)
sluiten.connect('clicked', self.sluiten, window)
bbox.pack_start(sluiten)
vbox.pack_start(bbox, expand = False)
window.add(vbox)
window.maximize()
window.show_all()
gtk.main()
def error_begindc(self, regel, row):
"""Errorscherm als er iets mis is in de begindc."""
window = gtkwindow('Fout in de Debiteuren/Crediteuren-beginlijst')
vbox = gtkvbox()
vbox.pack_start(gtk.Label(self.error))
# we vatten een regel op als een boekstuk met een regel
#
# Het zou mooier zijn om dit aan te passen / vervagen zodat het omschrijvings-veld de relatiewidget is.
# 'This is left as an excercise to the reader.'
bw = BoekstukWidget()
bw.set_editable(True)
bw.widget.remove(bw.buttons) # kleine hek, ik heb even geen behoeft aan knopjes
boekstuk = Boekstuk(regel.nummer, regel.datum)
boekstuk.append(regel)
bw.set_boekstuk(boekstuk)
vbox.pack_start(bw.widget)
bbox = gtkhbuttonbox()
volgende = gtk.Button(stock = gtk.STOCK_GO_FORWARD)
volgende.connect('clicked', self.volgende_begindc, bw, row, window)
bbox.pack_start(volgende)
sluiten = gtk.Button(stock = gtk.STOCK_CLOSE)
sluiten.connect('clicked', self.sluiten, window)
bbox.pack_start(sluiten)
vbox.pack_start(bbox)
window.add(vbox)
window.show_all()
gtk.main()
def error_balansregel(self, regel):
"""Errorscherm voor als er iest mis is in de beginbalans."""
# print self.error
# print regel
window = gtkwindow('Fout in beginbalans.')
vbox = gtkvbox()
rw = BalansregelWidget()
rw.set_balansregel(regel)
vbox.pack_start(gtk.Label(self.error))
vbox.pack_start(rw.widget)
bbox = gtkhbuttonbox()
volgende = gtk.Button(stock = gtk.STOCK_GO_FORWARD)
volgende.connect('clicked', self.volgende_balansregel, rw, window)
bbox.pack_start(volgende)
sluiten = gtk.Button(stock = gtk.STOCK_CLOSE)
sluiten.connect('clicked', self.sluiten, window)
bbox.pack_start(sluiten)
vbox.pack_start(bbox, expand = False)
window.add(vbox)
window.show_all()
gtk.main()
# hulpfuncties voor error_(boekstuk/balansregel/begindc):
def volgende_boekstuk(self, button, bw, row, writer, window):
writer.write(bw.get_boekstuk(), row)
window.destroy()
def volgende_balansregel(self, button, rw, window):
s = Sheet_bl('Beginbalans')
regel = rw.get_balansregel()
size = s.rows()
for i in range(size):
if s.getbalansregel(i).rekening == regel.rekening:
s.setbalansregel(i, regel)
s.write('Beginbalans')
window.destroy()
return
s.setbalansregel(size, regel)
s.write('Beginbalans')
window.destroy()
def volgende_begindc(self, button, bw, row, window):
row += 2
s = Sheet_jr(None, row)
s.setboekregel(0, bw.get_boekstuk()[0])
s.write('BeginDC')
window.destroy()
def sluiten(self, button, window):
self.verder = False
window.destroy()
def verder_bl(self, button, window):
window.destroy()
def check_begindc_x_beginbalans(self, ok):
dc = self.begindc_fix()
totals = {}
reks = self.conf.balansrekeningen()
reks.sort()
for line in reks:
if line.nummer > 129 and line.nummer < 150:
# haal Relates().exclude rek rekening eruit
# we nemen aan dat dit geen normale deb/cred zijn
# zoals bv btw
if not (self.conf.getrekening(line.nummer).naam in self.rel.exclude_rek):
totals[line.nummer] = 0
for line in dc:
if line.waarde.dc == 0: # debet
totals[line.rekening] += line.waarde.value/100
elif line.waarde.dc == 1: # credit
totals[line.rekening] -= line.waarde.value/100
beginbalans = Sheet_bl_ro('Beginbalans')
ok = True
foute_nummers = []
for key,value in totals.iteritems():
if beginbalans.getwaarde(key).dc == 0: # bebet
if beginbalans.getwaarde(key).value/100 != value:
foute_nummers.append( key)
if beginbalans.getwaarde(key).dc == 1: # credit
if (beginbalans.getwaarde(key).value/-100) != value:
foute_nummers.append( key)
if len(foute_nummers) > 0:
text = " ".join(str(x) for x in foute_nummers)
text = "Het totaal van de volgende begin DC posten is niet gelijk aan de beginbalans : " + text
ok = False
window = gtkwindow('Begin DC fout')
vbox = gtkvbox()
vbox.pack_start(gtk.Label(text))
bbox = gtkhbuttonbox()
verder = gtk.Button(stock = gtk.STOCK_GO_FORWARD)
verder.connect('clicked', self.verder_bl, window)
sluiten = gtk.Button(stock = gtk.STOCK_CLOSE)
sluiten.connect('clicked', self.sluiten, window)
bbox.pack_start(verder)
bbox.pack_start(sluiten)
vbox.pack_start(bbox)
window.add(vbox)
window.show_all()
gtk.main()
return ok
def begindc_fix(self):
"""Deze methode verwijdert dubbele entrys in de begindc.
Dus wanneer iemand twee keer op dezelfde rekening in de begindc iets heeft, wordt dit samengevat tot een.
Retourneert een lijst met boekregels zoals ze horen.
Omdat dit later van pas komt worden alle date vervangen door de begindatum - 1
"""
bdc = sorter(self.begindc, sorter_rodn)
it = 0
while it < len(bdc):
b = bdc[it]
it += 1
b.datum = self.bdatum - 1
while it < len(bdc) and b.rekening == bdc[it].rekening and b.omschrijving == bdc[it].omschrijving:
b.omschrijving2 += ', ' + bdc[it].omschrijving2
b.waarde += bdc[it].waarde
del bdc[it]
# for line in bdc:
# print line
return bdc
if __name__ == "__main__":
Debug()
|
UTF-8
|
Python
| false | false | 2,014 |
19,602,230,765,001 |
2fc27edf00b8abf9546e598cb1c386b851d1bf9a
|
dfa5857dc7b617b72eb1e53866ddeac2d157f9f8
|
/utils.py
|
319596bdfa8faebcc40f3fd452df7347f5e58e71
|
[
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only"
] |
non_permissive
|
willz/pybot
|
https://github.com/willz/pybot
|
bde7f28202fbd16bd7835b58e26502e34846cd48
|
18d242bf28814e8c76ab4bb42aa858ab12f95be5
|
refs/heads/master
| 2021-01-17T14:31:20.144279 | 2013-08-22T12:21:52 | 2013-08-22T12:21:52 | 12,295,865 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# cast dictionary's value to integer.
# e.x. {'num': '3'} --> {'num': 3}
def int_dict(d):
for key in d:
if isinstance(d[key], str) and d[key].isdigit():
d[key] = int(d[key])
|
UTF-8
|
Python
| false | false | 2,013 |
16,784,732,205,528 |
94ada5fae9fdffb86d1759754786210f6bf81210
|
0de5f943e27f03fa16f993add8fdf62e3af0ccad
|
/basicapp/basic/downloads/models.py
|
329f9eb77acdb9791c44af5bc003e6ecd35f6633
|
[] |
no_license
|
athityakumar/kgp-django-website
|
https://github.com/athityakumar/kgp-django-website
|
9f31543dc52c9a477c8b71c71ca6ffecdd0ef04d
|
6f5e1a572c79398b6c049c9c836c3ba092498121
|
refs/heads/master
| 2021-01-01T03:47:36.703394 | 2009-05-31T10:57:05 | 2009-05-31T10:57:05 | 56,304,668 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.db import models
from django.utils.translation import ugettext_lazy as _
import os
# Create your models here.
FILETYPE_CHOICE=(
('Audio/Video','Audio/Video'),
('Text/Word','Text/Word'),
('source','Source Archives'),
('Binary','All other files go here!'),
)
class Files(models.Model):
"""Downloads area model"""
filepath = models.FilePathField(_('Choose File'),path="/home/sumit/Downloads/")
filedescription = models.CharField(_('File Description'),max_length=100)
filetype = models.CharField(_('File Type'),max_length=1,choices=FILETYPE_CHOICE)
filesize=models.FloatField(_('Size(MB)'),null=True,blank=True, editable=False)
fileuploadtime = models.DateTimeField(_('File Upload Time'))
def __unicode__(self):
return self.filepath
class Admin:
list_display = ('filepath','filesize','fileuploaddate','fileuploadtime')
list_filter = ('fileuploaddate')
def save(self, force_insert=False, force_update=False):
"""Update the size field and save the record"""
if self.filepath:
self.filesize=os.path.getsize(self.filepath)/(1024.0*1024.0)
super(Files, self).save(force_insert,force_update)
|
UTF-8
|
Python
| false | false | 2,009 |
1,374,389,569,122 |
532ae5e281eadee8a47bdf72f8ad1a7040ded08c
|
f23adca4acf3347118c7e4df22d6a8a980ad88eb
|
/Python Implementation/challenges.py
|
13b5ad9065329ffcccdc889c5072321d4300316f
|
[] |
no_license
|
zknowles/API-Challenge
|
https://github.com/zknowles/API-Challenge
|
bc7c7998a74351549bea25409dbd610c3e428138
|
3f0be9703a77e8985a197caf8b0a1ee8b74514d0
|
refs/heads/master
| 2020-12-24T22:49:59.369812 | 2014-12-03T06:55:44 | 2014-12-03T06:55:44 | 40,203,122 | 1 | 0 | null | true | 2015-08-04T18:49:36 | 2015-08-04T18:49:34 | 2015-08-04T18:49:35 | 2014-12-03T06:55:45 | 6,484 | 0 | 0 | 0 |
JavaScript
| null | null |
__author__ = 'Darthfrazier'
import requests
import json
import datetime
#------------------------Register-----------------------------#
login = {"email":"[email protected]","github":"https://github.com/darthfrazier"}
login = json.dumps(login)
r = requests.post("http://challenge.code2040.org/api/register", data=login)
stringtoken = json.loads(r.text)
stringtoken = stringtoken["result"]
print("Your token is " + stringtoken + "\n")
#--------------------------Challenge One------------------------#
print("Running Challenge One\n")
token = {"token":stringtoken}
token = json.dumps(token)
r = requests.post("http://challenge.code2040.org/api/getstring", data=token)
string = json.loads(r.text)
print("Input string is " + string["result"])
outputstring = string["result"][::-1]
print("Reversed string is " + outputstring)
jsonstring = {"token":stringtoken, "string": outputstring}
jsonstring = json.dumps(jsonstring)
r = requests.post("http://challenge.code2040.org/api/validatestring", data=jsonstring)
results = json.loads(r.text)
results = results["result"]
print("Did I pass the test? \n" + results)
if results == "PASS: stage1. Enrollment record updated!":
print("Congratulations, on to the next one\n")
else:
print("Uh oh, there may be something wrong with the code\n")
#-----------------------------Challenge Two---------------------------#
print("Running Challenge Two\n")
r = requests.post("http://challenge.code2040.org/api/haystack", data=token)
jsonresult = json.loads(r.text)
result = jsonresult["result"]
needle = result["needle"]
haystack = result["haystack"]
print("Needle is " + needle)
print("Haystack is ")
for i in range (0,len(haystack)):
print(haystack[i])
index = haystack.index(needle)
jsonstring = {"token":stringtoken, "needle": index}
jsonstring = json.dumps(jsonstring)
r = requests.post("http://challenge.code2040.org/api/validateneedle", data=jsonstring)
results = json.loads(r.text)
results = results["result"]
print("Did I pass the test? \n" + results)
if results == "PASS: stage2. Enrollment record updated!":
print("Congratulations, on to the next one\n")
else:
print("Uh oh, there may be something wrong with the code\n")
#------------------------------Challenge Three------------------------#
print("Running Challenge Prefix\n")
r = requests.post("http://challenge.code2040.org/api/prefix", data=token)
jsonresult = json.loads(r.text)
result = jsonresult["result"]
prefix = result["prefix"]
array = result["array"]
temp = []
print("Prefix is " + prefix)
print("Array is ")
for i in range(0,len(array)):
print(array[i])
for j in range(0, len(array)):
if array[j].startswith(prefix) == False:
temp.append(array[j])
len = len(temp)
print(len)
jsonstring = {"token":stringtoken, "array": temp}
jsonstring = json.dumps(jsonstring)
r = requests.post("http://challenge.code2040.org/api/validateprefix", data=jsonstring)
results = json.loads(r.text)
results = results["result"]
print("Did I pass the test? \n" + results)
if results == "PASS: stage3. Enrollment record updated!":
print("Congratulations, on to the next one\n")
else:
print("Uh oh, there may be something wrong with the code\n")
#---------------------------Challenge Four---------------------------#
print("Running Challenge Four\n")
r = requests.post("http://challenge.code2040.org/api/time", data=token)
jsonresult = json.loads(r.text)
result = jsonresult["result"]
date = result["datestamp"]
interval = result["interval"]
print("Datestamp is " + date)
datestamp = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ")
datestampplus = datestamp + datetime.timedelta(0,interval)
datestampplus = datestampplus.isoformat()
print("New datestamp is " + datestampplus)
jsonstring = {"token":stringtoken, "datestamp": datestampplus}
jsonstring = json.dumps(jsonstring)
r = requests.post("http://challenge.code2040.org/api/validatetime", data=jsonstring)
results = json.loads(r.text)
results = results["result"]
print("Did I pass the test? \n" + results)
if results == "PASS: stage4. Enrollment record updated!":
print("Congratulations, all tests complete!\n")
else:
print("Uh oh, there may be something wrong with the code\n")
#-----------------------Status-----------------------------#
print("Checking Status\n")
r = requests.post("http://challenge.code2040.org/api/status", data=token)
jsonresult = json.loads(r.text)
result = jsonresult["result"]
print("Your results... ")
for k,v in result.items():
print(k,v)
|
UTF-8
|
Python
| false | false | 2,014 |
2,241,972,956,608 |
91302b186dc93b296dd38677e712ecdfbaeda9a2
|
a1f944c2efa4c7f73f483edc5c24dc199110e6f6
|
/lib.py
|
65b7bbe160f582a4e975ad9a58d4abec16ff5b1f
|
[] |
no_license
|
jrgcolin/sebi-cf
|
https://github.com/jrgcolin/sebi-cf
|
84c19b90b05da1a0d798b330644402a6b605acd1
|
b39b007f8326992dd44e0ec02c1e4062cc4a0036
|
refs/heads/master
| 2020-01-23T03:07:43.894542 | 2012-06-05T07:30:10 | 2012-06-05T07:30:10 | 2,925,506 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as n
import logging
lib_logger = logging.getLogger("SEBI-CF.lib")
def Bw(hr,L,z0h,z0m):
alphah=0.12
betah=125.
if (hr/L) > 0:
return -2.2*n.log(1+hr/L)
else:
if z0m < (alphah/betah*hr):
return -n.log(alphah) + Psym(-alphah*hr/L) - Psym(-z0m/L)
else:
return n.log(hr/(betah*z0m)) + Psym(-betah*z0m/L) - Psym(-z0m/L)
def Cw(hr,L,z0h,z0m):
alphah = 0.12
betah = 125.
res = n.zeros([len(z0m),z0m.size/len(z0m)])
for i in n.arange(0,len(z0m),1):
for j in n.arange(0,z0m.size/len(z0m),1):
if (hr[i,j]/L[i,j]) > 0:
res[i,j] = -7.6*n.log(hr[i,j]/L[i,j])
elif z0m[i,j] < (alphah/betah*hr[i,j]):
res[i,j] = -n.log(alphah) + Psyh(-alphah*hr[i,j]/L[i,j]) - Psyh(-z0h[i,j]/L[i,j])
else:
res[i,j] = n.log(hr[i,j]/(betah*z0m[i,j])) + Psyh(-betah*z0m[i,j]/L[i,j]) - Psyh(-z0h[i,j]/L[i,j])
return res
def cleanup(x,label):
try:
if label == "ndvi":
search = n.where(x<0.)
x[search] = abs(x[search])
search = n.where(x>1.)
x[search] = n.nan
search = n.where(x==0.)
x[search] = 0.001
elif label == "albedo":
search = n.where(x<0.)
x[search] = n.nan
search = n.where(x>1.)
x[search] = n.nan
elif label == "ts":
search = n.where(x<250.)
x[search] = n.nan
search = n.where(x>340.)
x[search] = n.nan
elif label == "swdw":
search = n.where(x<0.)
x[search] = n.nan
search = n.where(x>1400.)
x[search] = n.nan
elif label == "lwdw":
search = n.where(x<0.)
x[search] = n.nan
search = n.where(x>500.)
x[search] = n.nan
elif label == "RnDaily":
search = n.where(x<0.)
x[search] = n.nan
search = n.where(x>1400.)
x[search] = n.nan
elif label == "G0_Rn":
search = n.where(x<0.)
x[search] = n.nan
search = n.where(x>1.)
x[search] = n.nan
except :
pass
else:
pass
try:
log = str(len(x)) + " pixels cleaned up for " + label
except:
log = "unknown cleanup criteria for " + label
return x,log
def delta(es,t):
return n.log(10.)*7.5*237.3/(237.3+(t-273.16))**2 * es
def deltad(cp,red,rho,Rn,G0):
return red*(Rn-G0)/(rho*cp)
def deltaw(cp,delta,e,es,gamma,rew,rho,Rn,G0):
return (rew*(Rn-G0)/(rho*cp)-((es-e)/gamma))/(1+(delta/gamma))
def downscaling(x,myproj):
#try:
res = n.zeros([myproj.gridNb[0],myproj.gridNb[1]])
for i in n.arange(0,myproj.gridNb[0]):
for j in n.arange(0,myproj.gridNb[1]):
xgrid = x[i*myproj.pixPerGrid:(i+1)*myproj.pixPerGrid,
j*myproj.pixPerGrid:(j+1)*myproj.pixPerGrid]
if n.nansum(xgrid) == n.nan or myproj.pixPerGrid**2 - nancount(xgrid) == 0:
res[i,j] = n.nan
else:
res[i,j] = n.nansum(xgrid)/(myproj.pixPerGrid**2 - nancount(xgrid))
return res
#except Exception, err:
#print "\nDownscaling error:"
#print "pixels per grid=",myproj.pixPerGrid
#try:
# print "Grid cell ", i,j
# print "nansum(xgrid)=",n.nansum(xgrid)
# print "pixels with data=", myproj.pixPerGrid**2 - nancount(xgrid)
#except:
# pass
#sys.stderr.write('ERROR: %s\n' % str(err))
#return 1
def eact(p,q,rd,rv):
'''Pelgrum 2000, eq. 2.7, p.30'''
return p*q*rv/rd
def esat(es0,t):
'''Tetens (cf. Guyot 1999, eq.3.13, p.109)'''
if n.nansum(t)/(t.size-nancount(t)) > -40. and n.nansum(t)/(t.size-nancount(t)) < 100.:
return es0*pow(10,((7.5*(t))/(237.3+t)))
elif n.nansum(t)/(t.size-nancount(t)) > 233. and n.nansum(t)/(t.size-nancount(t)) < 373.:
return es0*pow(10,((7.5*(t-273.16))/(237.3+t-273.16)))
else:
print "WARNING: unit or value inconsitency in e(sat)"
def G0(fc,Rn):
return Rn*(0.05 + (1-fc)*(0.3-0.05))
#def getHist(x,label):
# p.clf()
# txtStats = label#getStats(x,label)
# p.hist(x,normed=True)
# p.title(txtStats)
# p.savefig(label+'-hist.png')
#def getPreview(x,label):
# p.clf()
# p.imshow(x,interpolation='nearest',vmin=n.nanmin(x),vmax=n.nanmax(x))
# p.colorbar()
# p.title(label)
# p.savefig(label+'-preview.png')
def getStats(x,label):
lib_stats_logger = logging.getLogger("SEBI-CF.lib.stats")
i = nancount(x)
#return label + ' : min=' + str(n.nanmin(x)) + ' max=' + str(n.nanmax(x)
# ) + ' avg=' + str(n.nansum(x)/x.size) + ' NanCount=' + str(i)
try:
lib_stats_logger.info('Mean ' + label + ' = ' + str("%10.4f" % (n.nansum(x)/(x.size-i))) + ' (NaN count is ' + str(i) +')')
except ZeroDivisionError:
lib_stats_logger.info('error on ' + label + ' (type is ' + str(x.dtype) + '): contains ' + str(n.nansum(x)) + ' Nan for a total of ' + str(x.size) + ' pixels')
def H(cp,delta_a,k,ra,rho,ustar):
return delta_a*k*ustar*rho*cp/ra
def hv2z0m(hv):
(i,j)=n.where(hv!=0)
z0m = hv-hv
z0m[i,j] = (0.136 * hv[i,j])
return z0m
def kB(cd,ct,fc,k,hg,hr,hs,hv,lai,ndvi,p0,pr,tr,ur,z0m):
lib_kb_logger = logging.getLogger("SEBI-CF.lib.kb")
'''Massman kB-1 model'''
fc = setMask(fc,0.,0.,1.)
fc = substitute(fc,0.,0.001)
#fc = substitute(fc,0.,n.NaN)
lai = substitute(lai,0.,0.001)
#lai = substitute(lai,0.,n.NaN)
U = 0.32 - 0.264*n.exp(-15.1*cd*lai) # U=u*/u(h)
N = cd*lai/(2.*(U**2.))
# N might be zero
(i,j)=N.nonzero()
d_h = N-N
d_h[i,j] = 1. -1/(2*N[i,j])*(1-n.exp(-2*N[i,j]))
z0m_h = (1-d_h)*n.exp(-k/U)
#z0m_h = z0m / hv
Prdt = 0.71 # Prandtl number
#pr = p0*((1-((0.0065*(hg+hr))/288.15))**5.256) INPUT!!
t = tr*((pr/p0)**.286)
# Some code added to avoid divide by zero
nu = pr - pr # just to get an array of the same dimension
search = n.nonzero(nu) # identify numerical
nu[search] = (1.327*(p0/pr[search])*(t[search]/273.16)**1.81)*1.E-5
z0m = ndvi2z0m(ndvi)
hv = z0m_h / z0m
d0 = z0m2d0(z0m)
ustar = u2ustar(d0,hr,k,ur,z0m)
# wind speed at canopy height
uh = z0m - z0m # just to get an array of the same dimension
# The following is done only to present calculation of log(0)
#hflow = hv-d0
#search = n.where(hflow=0.)
#loghflow =
uh = ur*((n.log(hv-d0)-n.log(z0m))/(n.log(hr-d0)-n.log(z0m)))
#Restar = U*uh*hv/nu
Restar = hs*ustar/nu
Ctstar = (Prdt**(-2./3))*(Restar**(-1/2.))
kb_dec_a = N-N
kb_dec_a[i,j] = (k*cd)/(4*ct*U[i,j]*(1-n.exp(-N[i,j]/2)))
kb_dec_b = (k*U*z0m_h)/Ctstar
kb_dec_b = nan2flt(kb_dec_b,0.) # Replace NaN with 0.
#kbs_1 = (2.46*(((ur*k/n.log(hr/hs))*hs/nu)**(1/4))) - n.log(7.4)
kbs_1 = 2.46*(Restar**0.25) - n.log(7.4)
kb_1 = kb_dec_a*fc**2 + kb_dec_b*fc*2*(1-fc) + kbs_1*(1-fc)**2
ref = n.where(fc<=0.1)
kb_1[ref] = kbs_1[ref]
getStats(U,'U')
getStats(N,'N')
getStats(d_h,'d_h')
getStats(z0m_h,'z0m_h')
getStats(pr,'pr')
getStats(t,'t')
getStats(nu,'nu')
getStats(d0,'d0')
getStats(ustar,'ustar')
getStats(uh,'uh')
getStats(Restar,'Restar')
getStats(Ctstar,'Ctstar')
getStats(kb_dec_a,'kb_dec_a')
getStats(kb_dec_b,'kb_dec_b')
getStats(kbs_1,'kbs_1')
# !!!
#kb_1 = kb_1-kb_1+4.0
# !!!
z0h = z0m / n.exp(kb_1)
return kb_1, z0h
def L(cp,delta_a,g,k,Le,rho,Rn,G0,ustar,state='none'):
if state == 'dry':
return -(ustar**3 *rho)/(k*g*(Rn-G0)/(delta_a*cp))
elif state == 'wet':
return -(ustar**3 *rho)/(k*g*0.61*(Rn-G0)/Le)
def nan2flt(x,xnew):
'''Remplace NaN in x with xnew value and return the array'''
ref = n.nonzero(x-x)
x[ref] = xnew
return x
def nancount(x):
'''Count NaN occurences in an array. Based on the result of numpy.nonzero() on
an array containing both zeros and NaN: only NaN are indexed'''
ref = n.nonzero(x-x)
i = x[ref]
return len(i)
def ndvi2emi(ndvi):
'''Following van de Griend & Owe, 1993'''
return 1.009 + 0.047*n.log(ndvi)
def ndvi2fc(ndvi):
'''Calculate fc = f(ndvi). Another option could be fc = 1.318*ndvi + 0.01877'''
return 1 - ((ndvi - n.nanmax(ndvi))/(n.nanmin(ndvi) - n.nanmax(ndvi)))**0.4631
def ndvi2lai(ndvi):
return (ndvi*(1.+ndvi)/(1.-ndvi))**0.5
def ndvi2z0m(ndvi):
'''Following Moran. Also 0.005 + 0.5*((ndvi/ndvi.max()))**2.5'''
return n.exp(-5.2 + 5.3*ndvi)
def ps_sea2gnd(ps,hg):
"""
ps MUST be in Pa
"""
return ps*((1-((0.0065*hg)/288.15))**5.256)
def Psyh(y):
return ((1-0.057)/0.78)*n.log((0.33+(n.abs(y)**0.78))/0.33)
def Psym(y):
a = 0.33
b = 0.41
psy0 = -n.log(a) + 3**(1/2.)*b*a**(1/3.)*n.pi/6
if y > b**(-3.):
y = b**(-3.)
x = (1/a*n.abs(y))
return n.log(a+n.abs(y)) - 3*b*n.abs(y)**(1/3.)+b*a**(1/3.)/2*n.log((1+x)**2 /(1-x+x**2)) + 3**(1/2.)*b*a**(1/3.)*n.arctan((2*x-1)/(3**(1/2.))) + psy0
def ra(d0,hr,z0h):
return n.log((hr-d0)/z0h)
def re(Cw,d0,hr,k,ustar,z0h):
re = (n.log((hr-d0)/z0h)-Cw)/(k*ustar)
re_alt = (n.log((hr-d0)/z0h))/(k*ustar)
search = n.where(re <= 0)
re[search] = re_alt[search]
return re
def rho(e,p,q,rd,t):
'''Brutsaert 1982, eq.3.6, p.38'''
return (p/(rd*t))*(1-(0.378*e/p))
def Rn(albedo,emi,lwdw,sigma,swdw,ts):
return swdw*(1.-albedo) + lwdw - (1-emi)*lwdw - emi*sigma*(ts**4.)
def setMask(x,xnew,vmin,vmax):
'''Replace in x values out of [vmin:vmax] with xnew'''
ref = n.where(x<=vmin)
x[ref] = xnew
ref = n.where(x>=vmax)
x[ref] = xnew
return x
def substitute(x,v,vnew):
'''Replace in x the value v with vnew'''
ref = n.where(x==v)
x[ref] = vnew
return x
def stabFunc(x):
"""Returns the set of 3 equations, with
x[0] = ustar
x[1] = H
x[2] = L
Get the variables from one single file
vars[0] = ur
vars[1] = hr
vars[2] = d0
vars[3] = z0m
vars[4] = Bw
vars[5] = delta_a
vars[6] = rho
vars[7] = ra
vars[8] = Ta(pot)
vars[9] = Le_i
vars[10] = Rn-G0"""
try:
vars = n.fromfile('tmp000')
#out = [vars[0] - x[0]/0.4*n.log((vars[1]-vars[2])/vars[3]) - vars[4]]
#out.append(x[1] - vars[5]*0.4*x[0]*vars[6]*1005./vars[7])
#out.append(x[2] + x[0]**3 *vars[7]/(0.4*9.81*(x[1]/(vars[9]*1005.)+0.61*((vars[9]-x[1])/vars[10]))))
#return out
return [(vars[0] - x[0]/(0.4*n.log((vars[1]-vars[2])/vars[3]) - vars[4])),(x[1] - vars[5]*0.4*x[0]*vars[6]*1005./vars[7]),(x[2] + ((x[0]**3) * vars[7])/(0.4*9.81*(x[1]/(vars[8]*1005.)+0.61*((vars[10]-x[1])/vars[9]))))]
except:
print "Error in vars ", vars
def tpot(cp,p,p0,q,rd,t):
kr = rd*(1-0.23*q)/cp
return t*((p0/p)**kr)
def u2ustar(d0,h,k,u,z0m):
"""
Calculate u* from the wind speed
"""
#TODO: Unit testing for u2ustar
ustar = z0m - z0m # to get an empty array of proper dimension
ratio = (h-d0)/z0m
search = n.nonzero(ratio)
ustar[search] = (u[search]*k)/(n.log(ratio[search]))
return ustar
def z0m2d0(z0m):
return z0m*4.9
def z0m2hv(z0m):
return z0m / 0.136
|
UTF-8
|
Python
| false | false | 2,012 |
11,647,951,312,106 |
ded0d1d4498b9d0f1ccc1fee2b327ba865ea0d5a
|
c897516e6e1861fbbf0ff818b6eca455eb0614f6
|
/python/graph_test.py
|
ec40d31e3c5411f75d321a42aad12e506d38e535
|
[] |
no_license
|
PanKaczka/iTonaPizzy
|
https://github.com/PanKaczka/iTonaPizzy
|
58ad4a2c6644fcfea132edc85f11af0f1df87a45
|
4422abb52a2de767c227af2e429d349d2ff09ad1
|
refs/heads/master
| 2015-08-13T05:33:52.853935 | 2014-08-28T11:25:46 | 2014-08-28T11:25:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""An actual graph application."""
import pygame
import socket
import threading
import cPickle as pickle
from graph import Graph
msg = ""
flag = False
def main():
pygame.init()
screen = pygame.display.set_mode((600, 900))
g = Graph()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = 31415
s.connect((host, port))
s.send('GRAPH')
str = s.recv(65536)
if str[0] == 'G':
g.read_graph_pickle(str[2:])
else:
print 'Packet error'
return
s.setblocking(0)
while True:
g.draw_graph(screen)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
return
try:
buf = s.recv(32)
print buf
if buf[0] == 'C':
g.set_current(int(buf[2:]))
except:
pass
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,014 |
11,570,641,906,287 |
965a1951c45593d4c8ccdf03de6dab98b1a2cd86
|
49013a6493b803af396f6dd7645a360d2807e80b
|
/src/neuroutils/__init__.py
|
0e2b5bacf6ed2e23a77db43a63e4a1f36b8df236
|
[] |
no_license
|
lixiaolong19890207/neuroutils
|
https://github.com/lixiaolong19890207/neuroutils
|
2c1caf5b52283fe7652fa7aa2a158378aa69b620
|
85151c30ad43745352c6dc641707d42b867a5adf
|
refs/heads/master
| 2021-05-28T08:25:06.613585 | 2012-02-27T12:24:51 | 2012-02-27T12:24:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from nipype.utils.config import config
import matplotlib
matplotlib.use(config.get("execution", "matplotlib_backend"))
from vis import Overlay, PsMerge, Ps2Pdf, PlotRealignemntParameters
from threshold import ThresholdGGMM, CreateTopoFDRwithGGMM, ThresholdGMM, ThresholdFDR
from simgen import SimulationGenerator
from resampling import CalculateNonParametricFWEThreshold, CalculateProbabilityFromSamples, CalculateFDRQMap
from bootstrapping import BootstrapTimeSeries, PermuteTimeSeries
from bedpostx_particle_reader import Particle2Trackvis
from annotate_tracks import AnnotateTracts
from icc import ICC
import numpy as np
def estimate_fdr_and_fnr(true_pattern, exp_result):
false_positives = sum(exp_result[true_pattern != 1] != 0)
false_negatives = sum(exp_result[true_pattern != 0] == 0)
all_positives = np.sum(exp_result != 0)
all_negatives = np.sum(exp_result == 0)
if all_positives == 0:
fdr = 0
else:
fdr = float(false_positives)/float(all_positives)
if all_negatives == 0:
fnr = 0
else:
fnr = float(false_negatives)/float(all_negatives)
return (fdr, fnr)
|
UTF-8
|
Python
| false | false | 2,012 |
11,055,245,834,991 |
fc22da66a5f9cf939202ab1b33ec2515984b83dc
|
735fa50ee217f8e732740e05d0acb159b86a47be
|
/p8.py
|
7bb55db348aff5d4837f7ad448b86f0c1f47f72c
|
[] |
no_license
|
coolplay/ProjectEuler
|
https://github.com/coolplay/ProjectEuler
|
2e50d89fbcae7533b9502e729109145543d932a7
|
bd5288037b1f2db7e00eb314ae81a5c0a8712808
|
refs/heads/master
| 2016-09-06T17:51:36.947813 | 2014-11-19T11:52:12 | 2014-11-19T11:52:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""Largest product in a series"""
import operator
import functools
# s.strip('\n') can't remove \n between digits. It only works from both *ends*.
# This is the difference between strip() and replace()
s = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
""".strip().replace('\n', '')
# 1.
maximum = 0
length = len(s)
for i in range(length-4):
res = functools.reduce(operator.mul, (int(elm) for elm in list(s[i:i+5])))
if res > maximum:
maximum = res
print maximum
# 2.
print max(functools.reduce(operator.mul, map(int, s[i:i+5])) for i in
range(len(s)-4))
|
UTF-8
|
Python
| false | false | 2,014 |
2,044,404,479,496 |
01179b1bd109374597541f4f227cd0cd3c614757
|
69e570c0a1a362250e987f2f63509d23bd95763e
|
/gsxws/diagnostics.py
|
d2a96964b3ba91f899b6b9109bb180117d18a4f4
|
[
"BSD-2-Clause"
] |
permissive
|
5l1v3r1/py-gsxws
|
https://github.com/5l1v3r1/py-gsxws
|
3b5316400ab0392d3f353adac6abd302d9c4a230
|
e36beeb68e017efe6d3a17a5fa23201789711a97
|
refs/heads/master
| 2023-03-15T18:54:23.644167 | 2013-10-23T21:07:25 | 2013-10-23T21:07:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from core import GsxObject
class Diagnostics(GsxObject):
_namespace = "glob:"
def fetch(self):
"""
The Fetch Repair Diagnostics API allows the service providers/depot/carriers
to fetch MRI/CPU diagnostic details from the Apple Diagnostic Repository OR
diagnostic test details of iOS Devices.
The ticket is generated within GSX system.
>>> Diagnostics(diagnosticEventNumber='12942008007242012052919').fetch()
"""
if hasattr(self, "alternateDeviceId"):
self._submit("lookupRequestData", "FetchIOSDiagnostic", "diagnosticTestData")
else:
self._submit("lookupRequestData", "FetchRepairDiagnostic", "FetchRepairDiagnosticResponse")
return self._req.objects
def events(self):
"""
The Fetch Diagnostic Event Numbers API allows users to retrieve all
diagnostic event numbers associated with provided input
(serial number or alternate device ID).
"""
self._submit("lookupRequestData", "FetchDiagnosticEventNumbers", "diagnosticEventNumbers")
return self._req.objects
|
UTF-8
|
Python
| false | false | 2,013 |
11,751,030,548,329 |
b1b91ae9fb704f908376a8cf42f21965103f962a
|
e53178ccf9218d5c97593e60aa617086d7c34f26
|
/mnemosyne/mnemosyne/libmnemosyne/plugin.py
|
1ed9cc4c31d465887cd1f4008a9504e13907ac00
|
[
"GPL-2.0-only",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-generic-exception",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft"
] |
non_permissive
|
wojas/pomni
|
https://github.com/wojas/pomni
|
d88acad65440320b3f014065f25957a69ca08a2a
|
0f248a34dc3ab510119101e871a789155d2db81e
|
refs/heads/master
| 2021-01-18T02:36:57.283528 | 2008-12-30T19:11:46 | 2008-12-30T19:11:46 | 98,562 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#
# plugin.py <[email protected]>
#
from mnemosyne.libmnemosyne.component import Component
from mnemosyne.libmnemosyne.component_manager import component_manager
class Plugin(Component):
"""A plugin is a component which can be activated and deactivated by the
user when the program is running. Typically, plugins derive from both
Plugin and the Component they implement, and set the 'provides' class
variable to the string describing the component type.
"""
name = None
description = None
active = False
provides = ""
def __init__(self):
assert Plugin.name and Plugin.description, \
"A Plugin needs a name and description."
def activate(self):
component_manager.register(Plugin.provides, self)
self.active = True
def deactivate(self):
component_manager.unregister(Plugin.provides, self)
self.active = False
|
UTF-8
|
Python
| false | false | 2,008 |
1,889,785,610,546 |
2acae44e6b237e447783309764d5084ad0af6a99
|
ba2ef8def1c1770b9186515b2c853c4dfcaf18a3
|
/nodes/vp_ardrone2_run_controlz.py~
|
eaf4ee905096bccb1ef3625a2e54cedb31f7e5a0
|
[] |
no_license
|
MorS25/vp_ardrone2
|
https://github.com/MorS25/vp_ardrone2
|
adc6ca05fd976ea96b0180c574400998447a2915
|
5e1e11f8bf8ed66a7ee04ab2b50d6fbb6f9abbe8
|
refs/heads/master
| 2020-11-30T12:32:27.795825 | 2014-10-01T05:59:44 | 2014-10-01T05:59:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Чтение из файла и выполнение команд сценария для ardrone 2.0
#
import roslib; roslib.load_manifest('vp_ardrone2')
import rospy
from std_msgs.msg import String
from ardrone_autonomy.msg import Navdata
from geometry_msgs.msg import Twist
def controller(data):
flag2=rospy.get_param("/vp_ardrone2/flag2");
rotZ1=rospy.get_param("/vp_ardrone2/rotZ1");
rotZ2=rospy.get_param("/vp_ardrone2/rotZ2");
if flag2==2:
rospy.set_param("/vp_ardrone2/rotZ1",data.rotZ);
rotZ2=rotZ2+data.rotZ/360;
rospy.set_param("/vp_ardrone2/rotZ2",rotZ2);
rospy.set_param("/vp_ardrone2/flag2",0);
if data.rotZ>rotZ2:
rospy.set_param("/vp_ardrone2/flag2",1);
def listener():
rospy.init_node('vp_ardrone2_controlz_node')
sub = rospy.Subscriber("ardrone/NavData",Navdata,controller)
rospy.spin()
if __name__ == '__main__':
try:
listener()
except rospy.ROSInterruptException: pass
except KeyboardInterrupt:
sys.exit(1)
|
UTF-8
|
Python
| false | false | 2,014 |
19,610,820,699,347 |
bd3f9c460bb7d1e6b7d7a1248d76b36357258768
|
44bfafa7a3de51e089a470afaa7d37e4e1176777
|
/utilspy/highfield_uvmot.py
|
b37a960e840bb1b9db05613564556209536ad039
|
[] |
no_license
|
drlightx/apparatus3-seq
|
https://github.com/drlightx/apparatus3-seq
|
b9bc4bd5d9b3a95f8610afff28ee7baea951b641
|
4505a2f484ecea2390482fb4ddf16ac9ca63b02d
|
refs/heads/master
| 2021-01-18T06:41:38.874121 | 2012-03-04T23:03:59 | 2012-03-04T23:03:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
""" Does CNCMOT then loads UVMOT and then ramps up to high field.
Atoms in the trap at high field are the starting point for many experiments"""
import wfm, gen, math, cnc, uvmot, odt
report=gen.getreport()
def f(sec,key):
global report
return float(report[sec][key])
def go_to_highfield(s):
#---Keep ODT on
ODT = gen.bstr('ODT',report)
if ODT == True:
s.digichg('odtttl',1)
s.wait(20.0)
ss = float(report['SEQ']['analogstepsize'])
#---Cool and Compress MOT
#---ENDCNC is defined as the time up to release from the MOT
motpow, repdet, trapdet, reppow, trappow, bfield, ENDCNC = cnc.cncRamps()
#---Load UVMOT from CNCMOT
uvfppiezo, uvpow2, uvpow, motpow, bfield, ENDUVMOT = uvmot.uvRamps(motpow, bfield, ENDCNC)
repdet.extend(ENDUVMOT)
trapdet.extend(ENDUVMOT)
reppow.extend(ENDUVMOT)
trappow.extend(ENDUVMOT)
#---Make sure everything has the same length before setting imaging values
#print motpow.dt(), repdet.dt(), trapdet.dt(), bfield.dt(), reppow.dt(), trappow.dt(), uvfppiezo.dt()
#print motpow.N(), repdet.N(), trapdet.N(), bfield.N(), reppow.N(), trappow.N(), uvfppiezo.N()
#--- Set imaging values
camera = 'ANDOR'
motpow, repdet, trapdet, reppow, trappow, maxDT = cnc.imagingRamps_nobfield(motpow, repdet, trapdet, reppow, trappow, camera)
#---Switch bfield to FESHBACH
overlapdt = float(report['ODT']['overlapdt'])
rampdelay = float(report['FESHBACH']['rampdelay'])
rampbf = float(report['FESHBACH']['rampbf'])
bf = float(report['FESHBACH']['bf'])
feshbachdt = float(report['FESHBACH']['feshbachdt'])
switchondt = float(report['FESHBACH']['switchondt'])
switchdelay = float(report['FESHBACH']['switchdelay'])
bias = float(report['FESHBACH']['bias'])
biasrampdt = float(report['FESHBACH']['rampdt'])
bfield.chop(ENDUVMOT-overlapdt,1)
bfield.appendhold(rampdelay)
bfield.linear( bf, rampbf)
bfield.extend(ENDUVMOT+feshbachdt)
bfield.linear(0.0, 0.0)
ENDBFIELD = feshbachdt
bfield.appendhold( switchondt + switchdelay)
bfield.linear(bias,biasrampdt)
#---Ramp up ODT
odtpow0 = odt.odt_wave('odtpow', f('ODT','odtpow0'), ss)
odtpow0.extend(ENDUVMOT)
#---Add waveforms to sequence
s.analogwfm_add(ss,[ motpow, repdet, trapdet, bfield, reppow, trappow, uvfppiezo, uvpow, uvpow2,odtpow0])
#wait normally rounds down using floor, here the duration is changed before so that
#the wait is rounded up
ENDUVMOT = ss*math.ceil(ENDUVMOT/ss)
#---Insert QUICK pulse for fast ramping of the field gradient during CNC
s.wait(-10.0)
quickval = 1 if gen.bstr('CNC',report) == True else 0
s.digichg('quick',quickval)
s.wait(10.0)
s.wait(ENDCNC)
s.digichg('quick',0)
#---Go back in time, shut down the UVAOM's and open the shutter
s.wait(-50.0)
s.digichg('uvaom1',0)
s.digichg('uvaom2',0)
s.digichg('uvshutter',1)
s.wait(50.0)
#---Turn OFF red light
delay_red = float(report['UV']['delay_red'])
s.wait(delay_red)
s.digichg('motswitch',0)
s.digichg('motshutter',1)
s.wait(-delay_red)
#---Turn ON UVAOM's
delay_uv = float(report['UV']['delay_uv'])
s.wait(delay_uv)
s.digichg('uvaom1',1)
s.digichg('uvaom2',1)
s.wait(-delay_uv)
s.wait(-ENDCNC)
#---Go to MOT release time and set QUICK back to low
s.wait(ENDUVMOT)
s.digichg('quick',0)
#---Turn OFF UVAOM2 for optical pumping
pumptime = float(report['UV']['pumptime'])
s.wait(-pumptime)
s.digichg('uvaom2',0)
s.wait(pumptime)
#---Turn OFF UVAOM
s.digichg('uvaom1',0)
#---Close UV shutter
waitshutter=5.0
s.wait(waitshutter)
s.digichg('uvshutter',0)
s.wait(-waitshutter)
#---Turn OFF MOT magnetic field
s.digichg('field',0)
#---Insert ODT overlap with UVMOT and switch field to FESHBACH
overlapdt = float(report['ODT']['overlapdt'])
servodt = float(report['ODT']['servodt'])
#
s.wait(-overlapdt-servodt)
s.digichg('odt7595',1)
s.wait(servodt)
s.digichg('odtttl',1)
s.wait(overlapdt)
s.wait( feshbachdt )
s.digichg('feshbach',1)
s.wait(switchondt)
do_quick=1
s.digichg('field',1)
s.digichg('hfquick',do_quick)
s.digichg('quick',do_quick)
#Can't leave quick ON for more than quickmax
quickmax=100.
s.wait(quickmax)
s.digichg('hfquick',0)
s.digichg('quick',0)
s.wait(-quickmax)
#
s.wait(switchdelay+biasrampdt)
s.digichg('quick',0)
s.wait(-biasrampdt)
s.wait(-switchdelay - switchondt - feshbachdt - ss)
#---At this point the time sequence is at ENDUVMOT
#This is the time until the end of the bfield ramp
toENDBFIELD = biasrampdt + switchdelay + switchondt + feshbachdt
return s, toENDBFIELD
|
UTF-8
|
Python
| false | false | 2,012 |
16,398,185,174,374 |
6cef56606376e523a9406aea9b5b9c9daca1be83
|
4d7302d61671ec1b602bef2e556efc33d76c665d
|
/eprofile/fixtures.py
|
ee98c30a6c47133c7bacaad0340308c90c92ea19
|
[] |
no_license
|
bdelliott/eprofile
|
https://github.com/bdelliott/eprofile
|
743268671e8f6668fb103c3d28132b5f335f65f4
|
570cc56d072d3911f13cd1ab2e244b39afef0867
|
refs/heads/master
| 2020-07-04T03:19:13.201659 | 2014-01-02T17:20:33 | 2014-01-02T17:20:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
""" Misc test code to profile. """
import time
from eventlet import greenthread
from eventlet import greenpool
def foo(i):
bar()
return i
def bar():
time.sleep(0.0) # force a greenthread swap
def multi(n=2):
n = int(n)
# Run in multiple greenthreads
pool = greenpool.GreenPool(n)
results = []
for result in pool.imap(foo, range(n)):
results.append(result)
def fib(n):
n = int(n)
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def swap():
t1 = greenthread.spawn(foo, 1)
t2 = greenthread.spawn(wait)
t1.wait()
t2.wait()
def wait():
time.sleep(0.2)
def outer():
inner()
def inner():
return
|
UTF-8
|
Python
| false | false | 2,014 |
14,516,989,512,452 |
f0b1ca9dda86efb9f57d772c292838e55b6be03c
|
a9847a299ba1275323137995460ca5bdd5bc5cf0
|
/Python/AllowableStresses/allowablestressesdlg.pyw
|
cb07b49e74adb2a8847cedfb275d411814c9a712
|
[] |
no_license
|
ayub-muhammad/MyProjects
|
https://github.com/ayub-muhammad/MyProjects
|
15c3bab7e68b8cb41213bd7b4f082756cb9f7016
|
e5f52abb72ce3ed77215a9bbb3a117cc5f1a0859
|
refs/heads/master
| 2019-05-28T13:10:17.913694 | 2014-08-23T17:06:42 | 2014-08-23T17:06:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from __future__ import division
import xlrd
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ui_allowableStresses
class AllowableStresses(QDialog,ui_allowableStresses.Ui_Dialog):
def __init__(self, parent=None):
super(AllowableStresses,self).__init__(parent)
self.setupUi(self)
try:
self.populateMatCombo()
except:
self.resultLabel.setText("Unable to open database file")
self.calculateButton.setDisabled(True)
def populateMatCombo(self):
self.wb = xlrd.open_workbook('Table-1A.xls')
#self.resultLabel.setText("Unable to open database file")
self.sh = self.wb.sheet_by_index(0)
numberOfRows=self.sh.nrows
col = self.sh.col_values(6)
self.matComboData=col[6:numberOfRows]
self.materialCombo.clear()
self.materialCombo.addItems(self.matComboData)
def calculateStress(self,currentRow, temperature):
tempRange=[-30, 65, 100, 125, 150, 200, 250, 300, 325, 350, 375, 400, 425, 450, 475, 500, 525, 550, 575, 600, 625, 650, 675, 700, 725, 750, 775, 800, 825, 850, 875, 900]
currentMatRow=currentRow[20:52]
for x2 in tempRange:
if x2 >= temperature:
i = list.index(tempRange, x2)
break
#print i, x2
x1 = tempRange[i-1]
y1 = currentMatRow[i-1]
if y1=="":
y1=0
y2 = currentMatRow[i]
if y2=="":
y2=0
#print tempRange
#print currentMatRow
#print i,x1,x2,y1,y2,len(tempRange), len(currentMatRow)
return (temperature - x1) * (y2 - y1) / (x2 - x1) + y1
@pyqtSlot()
def on_calculateButton_clicked(self):
try:
self.resultLabel.clear()
temperature=float(self.temperatureLineEdit.text())
matIndex=self.materialCombo.currentIndex()+6
matRow = self.sh.row_values(matIndex)
#print matIndex,temperature, matRow
stressValue=str(self.calculateStress(matRow,temperature))
self.resultLabel.setText("Allowable Stress Value @ " +str(temperature)+ " 'C = "+ stressValue +" MPa")
except:
self.resultLabel.setText("Invalid Input")
if __name__=="__main__":
import sys
app=QApplication(sys.argv)
form=AllowableStresses()
form.show()
app.exec_()
|
UTF-8
|
Python
| false | false | 2,014 |
15,779,709,857,181 |
22494aff823f244039b10245b5c2511da6cfd020
|
3963dcc4fd8f754e00e7387cd607173778164110
|
/test/testwiki/wikiserver.py
|
94de708c6d3ca90fc3b86befb43d7c0413f2ea17
|
[
"Apache-2.0"
] |
permissive
|
ptrourke/zenpub
|
https://github.com/ptrourke/zenpub
|
b75f3d5f892f2dea1f72f901498bdb2b4b516db8
|
73b210417bca43cc86b3b5c09ad358d4077ff7d0
|
refs/heads/master
| 2021-01-18T05:15:36.325824 | 2014-05-29T22:04:49 | 2014-05-29T22:04:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
"""
Start script for the standalone Wiki server.
@copyright: 2007 MoinMoin:ForrestVoight
@license: GNU GPL, see COPYING for details.
"""
import sys, os
# a) Configuration of Python's code search path
# If you already have set up the PYTHONPATH environment variable for the
# stuff you see below, you don't need to do a1) and a2).
# a1) Path of the directory where the MoinMoin code package is located.
# Needed if you installed with --prefix=PREFIX or you didn't use setup.py.
#sys.path.insert(0, 'PREFIX/lib/python2.4/site-packages')
# a2) Path of the directory where wikiconfig.py / farmconfig.py is located.
moinpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
sys.path.insert(0, moinpath)
os.chdir(moinpath)
# b) Configuration of moin's logging
# If you have set up MOINLOGGINGCONF environment variable, you don't need this!
# You also don't need this if you are happy with the builtin defaults.
# See wiki/config/logging/... for some sample config files.
from MoinMoin import log
log.load_config('wikiserverlogging.conf')
from MoinMoin.script import MoinScript
if __name__ == '__main__':
sys.argv = ["moin.py", "server", "standalone"]
MoinScript().run()
|
UTF-8
|
Python
| false | false | 2,014 |
9,844,065,064,164 |
e30bb6313c46556bf39d378262b765eb79bc8f86
|
6135340eb5e5af828cbdc4b873e078001a216616
|
/playground/benchmark/sr_tests.py
|
eec98d58e1891b65735e71306c8fc9f63a9b46e2
|
[
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later"
] |
non_permissive
|
a20r/playground
|
https://github.com/a20r/playground
|
df0ff6711308d3ee0dd78afd7424f7e959dcc732
|
1ae74280bd104984ec16d62cc74de351ddee7d5f
|
refs/heads/master
| 2021-05-28T01:40:49.023550 | 2014-02-03T15:57:00 | 2014-02-03T15:57:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import math
import random
import parser
# GLOBAL VARS
data_file_extension = ".dat"
def write_test_data(fp, data):
cols = len(data[0].split()) - 1
data_file = open(fp, "wb")
# create header
variables = ["var{0}".format(i + 1) for i in range(cols)]
variables.append("answer")
header = ", ".join(variables)
data_file.write(header + "\n")
# write data
for line in data:
data_file.write("{0}\n".format(line))
# close data file
data_file.close()
def generate_random_matrix(bounds, points, decimal_places=2):
points_generated = 0
matrix = []
columns = len(bounds)
while (points_generated != points):
tmp = []
for i in range(columns):
lower = bounds[i]["lower"]
upper = bounds[i]["upper"]
rand_num = round(random.uniform(lower, upper), decimal_places)
tmp.append(rand_num)
if tmp not in matrix:
matrix.append(tmp)
points_generated += 1
return matrix
def generate_series_matrix(bounds, points, decimal_places=2):
points_generated = 0
matrix = []
columns = len(bounds)
# calculate the steps
for i in range(columns):
step = bounds[i]["upper"] - bounds[i]["lower"]
step = step / float(points)
bounds[i]["step"] = round(step, decimal_places)
while (points_generated != points):
tmp = []
for i in range(columns):
if bounds[i].get("last_number") is not None:
num = round(bounds[i]["last_number"], decimal_places)
num += round(bounds[i]["step"], decimal_places)
bounds[i]["last_number"] = round(num, decimal_places)
else:
num = bounds[i]["lower"]
bounds[i]["last_number"] = round(num, decimal_places)
tmp.append(num)
matrix.append(tmp)
points_generated += 1
return matrix
def evaluate_test_function(equation, var_values):
data = []
points = len(var_values)
for i in range(points):
# eval equation
v = var_values[i]
code = parser.expr(equation).compile()
result = eval(code)
# stringify results
line = map(str, v) # add variable values
line.append(str(result)) # add result
line = ", ".join(map(str, line)) # stringfy the data line
data.append(line)
return data
def arabas_et_al_test_functions(data_file="arabas_et_al-f"):
t_funcs = [
"-v[0] * math.sin(10.0 * math.pi * v[0]) + 1.0",
"int(8.0 * v[0]) / 8.0",
"v[0] * math.copysign(1, v[0])",
" ".join(
"""
0.5 + (math.sin(math.sqrt(v[0] ** 2 + v[1] **2) - 0.5) ** 2)
/ (1 + 0.001 * (v[0] ** 2 + v[1] ** 2)) **2
""".split()
)
]
bounds = [
[{"lower": -2.0, "upper": 1.0}],
[{"lower": 0.0, "upper": 1.0}],
[{"lower": -1.0, "upper": 2.0}],
[{"lower": -100.0, "upper": 100.0}, {"lower": -100.0, "upper": 100.0}],
]
points = [200, 50, 50, 50]
for i in range(len(t_funcs)):
fp = "{0}{1}{2}".format(data_file, i + 1, data_file_extension)
matrix = generate_series_matrix(bounds[i], points[i])
data = evaluate_test_function(t_funcs[i], matrix)
write_test_data(fp, data)
def nguyen_et_al_test_functions(data_file="nguyen_et_al-f"):
t_funcs = [
"v[0] ** 3 + v[0] ** 2 + v[0]",
"v[0] ** 4 + v[0] ** 3 + v[0] ** 2 + v[0]",
"v[0] ** 5 + v[0] ** 4 + v[0] ** 3 + v[0] ** 2 + v[0]",
"v[0] ** 6 + v[0] ** 5 + v[0] ** 4 + v[0] ** 3 + v[0] ** 2 + v[0]",
"math.sin(v[0] ** 2) * math.cos(v[0]) - 1",
"math.sin(v[0]) + math.sin(v[0] + v[0] ** 2) - 1",
"math.log(v[0] + 1) + math.log(v[0] ** 2 + 1)",
"math.sqrt(v[0])",
"math.sin(v[0]) + math.sin(v[1] ** 2)",
"2 * math.sin(v[0]) * math.cos(v[1])"
]
bounds = [
[{"lower": -1, "upper": 1}],
[{"lower": -1, "upper": 1}],
[{"lower": -1, "upper": 1}],
[{"lower": -1, "upper": 1}],
[{"lower": -1, "upper": 1}],
[{"lower": -1, "upper": 1}],
[{"lower": 0, "upper": 2}],
[{"lower": 0, "upper": 4}],
[{"lower": -1, "upper": 1}, {"lower": -1, "upper": 1}],
[{"lower": -1, "upper": 1}, {"lower": -1, "upper": 1}]
]
points = [20, 20, 20, 20, 20, 20, 20, 20, 100, 100]
for i in range(len(t_funcs)):
fp = "{0}{1}{2}".format(data_file, i + 1, data_file_extension)
matrix = generate_random_matrix(bounds[i], points[i])
data = evaluate_test_function(t_funcs[i], matrix)
write_test_data(fp, data)
|
UTF-8
|
Python
| false | false | 2,014 |
18,468,359,386,348 |
c6312a5da981804c990fe71d7613094254d9e851
|
016e742ce8f369a0ff68a786917c805e6ad98e40
|
/scripts/bayes.py
|
a598acdcfb58210508bb22a30144ab93dade25e7
|
[] |
no_license
|
mehdifirouz/emote-cat
|
https://github.com/mehdifirouz/emote-cat
|
cefecb5af91209fb9ee44a1a14a228fe10dc3034
|
aeb4a1723f7118018a0d16791da00d5ec94751f0
|
refs/heads/master
| 2021-05-26T20:01:31.623668 | 2012-12-15T08:05:54 | 2012-12-15T08:05:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import nltk
word_features = set()
def document_features(feat_list):
document_words = set(feat_list)
features = {}
for word in word_features:
features['contains(%s)' % word] = (word in document_words)
return features
def run(fold, data, result):
for line in data.all():
for feat in line:
word_features.add(feat)
training_data = data.train(fold)
featuresets = [(document_features(x["Features"]), x["Answer"]) for x in training_data]
train_set, test_set = featuresets[500:], featuresets[:500]
classifier = nltk.NaiveBayesClassifier.train(train_set)
print nltk.classify.accuracy(classifier, test_set)
classifier.show_most_informative_features(5)
classifier = nltk.DecisionTreeClassifier.train(train_set)
print nltk.classify.accuracy(classifier, test_set)
|
UTF-8
|
Python
| false | false | 2,012 |
987,842,505,329 |
3ba73616efe24e23151eb2a2cbde8d1351221350
|
e0c2f2a9e2af421a214c26cd22bbd29252e5a4c0
|
/inkscapeParser.py
|
9ea3058c56db0a1d9646493d42a562b3bc4103f1
|
[] |
no_license
|
jceipek/SwarmBots
|
https://github.com/jceipek/SwarmBots
|
490aef750e4b61d07464ff19b12cd1fc3f2e05be
|
479a65f27dd80aae8a37404e9d5e715bf5933ab7
|
refs/heads/master
| 2016-09-05T18:02:32.836761 | 2011-12-14T23:41:01 | 2011-12-14T23:41:01 | 2,792,922 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import pygame
from BeautifulSoup import BeautifulStoneSoup
import BeautifulSoup
f = open('/Users/jceipek/Desktop/Abst.svg')
o = open('/Users/jceipek/Desktop/Abst.pde','w')
txt = f.read()
soup = BeautifulStoneSoup(txt, selfClosingTags=['defs','sodipodi:namedview','path'])
#print soup.prettify()
width = float(soup.find('svg')['width'])
height = float(soup.find('svg')['height'])
print width,height
def parsePoint(p,lastPoint,offset=(0,0)):
print "orig,",p
print "offset",offset
p = p.strip().split(' ')
lines = []
controlChar = ''
for coordI in range(len(p)):
if p[coordI] == 'M':
controlChar = 'M'
elif p[coordI] == 'm':
controlChar = 'm'
elif p[coordI] == 'l':
controlChar = 'l'
elif p[coordI] == 'L':
controlChar = 'L'
elif p[coordI] == 'z':
lines.append(lines[0])
else:
p[coordI] = p[coordI].split(',')
p[coordI] = tuple([float(c) for c in p[coordI]])
if controlChar == 'M' or controlChar == 'L':
lastPoint = (p[coordI][0]+offset[0],p[coordI][1]+offset[1])
lines.append(lastPoint)
elif controlChar == 'm' or controlChar == 'l':
if coordI == 1:
lastPoint = (p[coordI][0]+offset[0],p[coordI][1]+offset[1])
else:
m = (lastPoint[0]+p[coordI][0],lastPoint[1]+p[coordI][1])
lastPoint = m
lines.append(lastPoint)
#print lines
return lines
allPoints = []
for g in soup.findAll('g'):
lastPoint=(0,0)
try:
translate = g['transform']
translate = translate[len('translate('):-1]
translate = translate.split(',')
translate = float(translate[0]),float(translate[1])
except KeyError:
translate = (0,0)
for p in g.findAll('path'):
try:
ltranslate = p['transform']
ltranslate = ltranslate[len('translate('):-1]
ltranslate = ltranslate.split(',')
ltranslate = float(ltranslate[0])+float(translate[0]),float(ltranslate[1])+float(translate[1])
except KeyError:
ltranslate = translate
currLines = parsePoint(p['d'],lastPoint,offset=ltranslate)
allPoints.append(currLines)
lastPoint = currLines[1]
print "LAST PT:",lastPoint
'''
print "HERE"
stuff = [(tag.find('<path'),str(tag)) for tag in soup.find('svg')]
for i in stuff:
print i
'''
for p in soup.find('svg').findNextSiblings('path'):
print "PATHS ARE HURR"
try:
ltranslate = p['transform']
ltranslate = ltranslate[len('translate('):-1]
ltranslate = ltranslate.split(',')
ltranslate = float(ltranslate[0])+float(translate[0]),float(ltranslate[1])+float(translate[1])
except KeyError:
ltranslate = translate
currLines = parsePoint(p['d'],lastPoint,offset=ltranslate)
allPoints.append(currLines)
scale = 800.0/height
turnOffListVals = []
xListCoords = []
yListCoords = []
for pList in allPoints:
rPList = [(p[0]*scale,p[1]*scale) for p in pList]
xListCoords.extend([str(r[0]) for r in rPList])
yListCoords.extend([str(r[1]) for r in rPList])
turnOffListVals.append(str(len(xListCoords)))
o.write("int pathLen = ")
o.write(str(len(xListCoords)))
o.write(';\n\n')
o.write("byte lightPath[] = {\n ")
o.write(',\n '.join(turnOffListVals))
o.write("\n};\n\n")
o.write("float xPath[] = {\n ")
o.write(',\n '.join(xListCoords))
o.write("\n};\n\n")
o.write("float yPath[] = {\n ")
o.write(',\n '.join(yListCoords))
o.write("\n};\n")
o.close()
f.close()
scale = 800.0/height
pygame.init()
screen = pygame.display.set_mode((int(width*scale),int(height*scale)))
running = True
pan = [0,0]
while running:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_MINUS:
scale *= 0.9
elif event.key == pygame.K_EQUALS:
scale *= 1.1
elif event.key == pygame.K_UP:
pan[1] += 10
elif event.key == pygame.K_DOWN:
pan[1] -= 10
elif event.key == pygame.K_LEFT:
pan[0] -= 10
elif event.key == pygame.K_RIGHT:
pan[0] += 10
for pList in allPoints:
rPList = [(p[0]*scale+pan[0],p[1]*scale+pan[1]) for p in pList]
pygame.draw.lines(screen, (255,255,0), False, rPList)
pygame.display.flip();
|
UTF-8
|
Python
| false | false | 2,011 |
8,744,553,425,204 |
48951c886c0354d6c6c812024a7fb2fb6142f2e6
|
19c723f61451db78c8bb58f4e03ab6d8e42c4306
|
/views/models.py
|
04909e1ecd1457e69cbe9be49a74f90dd13b97fb
|
[] |
no_license
|
kingheaven/davidpaste.com
|
https://github.com/kingheaven/davidpaste.com
|
29ed98d3065556b98cb70b811cea3cc66292166b
|
4b32098062433c381e11574c596a672411a3fcf7
|
refs/heads/master
| 2021-01-10T19:09:57.290968 | 2011-11-27T13:08:33 | 2011-11-27T13:08:33 | 554,455 | 8 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
#-*-coding:utf-8-*-
from sqlalchemy import Column, Integer, String, DateTime, Text
from sqlalchemy import Table, MetaData, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from database import engine
from datetime import datetime
import hashlib
import random
__all__ = ['User', 'Syntax', 'Paste', 'Tag']
Base = declarative_base()
metadata = Base.metadata
paste_user = Table('pastes_users', metadata,
Column('paste_id', Integer, ForeignKey('pastes.id')),
Column('user_id', Integer, ForeignKey('users.id')),
)
class Syntax(Base):
__tablename__ = 'syntax'
id = Column(Integer, primary_key=True)
name = Column(String(45)) # 显示的名字
syntax = Column(String(45)) # pygments用的
def __init__(self, name, syntax):
self.name = name
self.syntax = syntax
def __repr__(self):
return "<Syntax (%s)>" % self.name
paste_tag = Table('pastes_tags', metadata,
Column('paste_id', Integer, ForeignKey('pastes.id')),
Column('tag_id', Integer, ForeignKey('tags.id')),
)
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
name = Column(String(45), unique=True)
times = Column(Integer(11), default=1)
def __init__(self, name):
self.name = name.lower()
def __repr__(self):
return "Tag <%s>" % self.name
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(String(45), unique=True) # 登陆使用的
nickname = Column(String(45)) # 显示时用的
password = Column(String(45))
paste_num = Column(Integer, default=0)
created_time = Column(DateTime, default=datetime.now())
modified_time = Column(DateTime, default=datetime.now())
favourites = relationship('Paste', secondary=paste_user, order_by='Paste.created_time', backref="users")
def __init__(self, nickname, email, password):
self.nickname = nickname
self.email = email
self.password = hashlib.md5(password).hexdigest()
def __repr__(self):
return "<User (%s@%s)>" % (self.nickname, self.email)
class Paste(Base):
__tablename__ = 'pastes'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
syntax_id = Column(Integer, ForeignKey('syntax.id'))
title = Column(String(45), default=u'未知标题')
content = Column(Text)
views = Column(Integer, default=0)
created_time = Column(DateTime, default=datetime.now())
modified_time = Column(DateTime, default=datetime.now())
user = relationship(User, backref=backref('pastes'))
syntax = relationship(Syntax, backref=backref('pastes'))
tags = relationship('Tag', secondary=paste_tag, order_by=Tag.name, backref="pastes")
def __init__(self, syntax_id, title, content):
self.user_id = None
self.syntax_id = syntax_id
self.title = title
self.content = content
def __repr__(self):
return "<Paste (%s@%s)>" % (self.title, self.user_id)
def isFavourited(self, user):
return self in user.favourites
if __name__ == '__main__':
from database import db_session
metadata.create_all(engine)
"""
syntax_dict = {'python':'Python',
'c':'C',
'html':('HTML', 'XHTML'),
'javascript':('JavaScript', 'JScript'),
'css':'CSS',
'actionscript':'ActionScript',
'applescript':'AppleScript',
'awk':'Awk',
'erlang':'Erlang',
'delphi':'Delphi',
'groovy':'Groovy',
'haskell':'Haskell',
'lua':'Lua',
'objective-c':'Objective-C',
'php':'PHP',
'perl':'Perl',
'ruby':'Ruby',
'scala':'Scala',
'sql':'SQL',
'diff':'Diff Files',
'xml':'XML',
'yaml':'YAML',
'java': 'JAVA',
'bash':'Bash',
'c#':'C#'}
keys = syntax_dict.keys()
keys.sort()
for key in keys:
value = syntax_dict[key]
if isinstance(value, tuple):
for name in value:
syntax = Syntax(name, key)
db_session.add(syntax)
if isinstance(value, str):
syntax = Syntax(value, key)
db_session.add(syntax)
db_session.commit()
password = ''.join([random.choice('abcdefghij') for i in range(10)])
user = User(u'未知用户', '[email protected]', hashlib.md5(password).hexdigest())
db_session.add(user)
db_session.commit()
"""
|
UTF-8
|
Python
| false | false | 2,011 |
12,395,275,653,240 |
dc88924c4227bb94b432a434f276731ed8363eaa
|
f234d21f03b25edbb670164497b92f6aabef8fcd
|
/hubcave/manage.py
|
d0d48a71cc787ccb9d48056f44bee13c8074b9ce
|
[
"MIT"
] |
permissive
|
naphthalene/hubcave
|
https://github.com/naphthalene/hubcave
|
e822966118a3a9d15b1be6faae4f993a0e0c64cc
|
e74edfe3b7700e1af5be90cf4765f19633ba2ebf
|
refs/heads/master
| 2021-01-19T16:35:41.828287 | 2014-12-04T17:28:52 | 2014-12-04T17:28:52 | 25,007,631 | 1 | 0 | null | false | 2014-11-25T18:07:40 | 2014-10-09T20:39:41 | 2014-11-21T21:02:48 | 2014-11-25T18:07:40 | 1,587 | 7 | 3 | 9 |
JavaScript
| null | null |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings.base")
sys.path.append(os.getcwd())
from django.conf import settings
if getattr(settings, 'SOCKETIO_ENABLED', False):
from gevent import monkey
monkey.patch_all()
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
UTF-8
|
Python
| false | false | 2,014 |
6,253,472,395,289 |
5b82d5eec27949b0783ab4942ea1aa8a99fe7a35
|
c6008349d6b7d191d2b52fbc6d21c3e1c4a63b99
|
/tunnel.py
|
f44b5e1248eca7ffdd2202e98f91d4b0b15a89be
|
[] |
no_license
|
jrecuero/automat
|
https://github.com/jrecuero/automat
|
f77229dac5dc0862e15a8fc23d98e52f87a9a36b
|
56d82059526a29363cce56748a9c7626bbf298aa
|
refs/heads/master
| 2021-01-25T08:38:36.333965 | 2013-09-07T04:50:01 | 2013-09-07T04:50:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
def getResourceId():
return 'Tunnel'
def getResourceTag():
return 'tunnels'
RESOURCE = {'id': getResourceId(),
'tag': getResourceTag(),
'attrs': [{'display': 'Name',
'name': 'name',
'type': 'str',
'dim': None,
'default': None,
'values': None, },
{'display': 'Node',
'name': 'node',
'type': 'str',
'dim': None,
'default': None,
'values': None, },
{'display': 'BVID',
'name': 'bvid',
'type': 'int',
'dim': None,
'default': None,
'values': None, },
{'display': 'Port',
'name': 'port',
'type': 'str',
'dim': None,
'default': None,
'values': None, },
{'display': 'BSA',
'name': 'bsa',
'type': 'str',
'dim': None,
'default': None,
'values': None, }, ], }
|
UTF-8
|
Python
| false | false | 2,013 |
7,421,703,535,245 |
26e75288c555a9405a7c5cde929e7b81349b1ac8
|
66d8edfc3bc615b39db53568d3d4aad04589c212
|
/denigma/apps/blog/search_indexes.py
|
7eecef62411c620011c20f78c344052cd6a35a83
|
[] |
no_license
|
spaceone/denigma
|
https://github.com/spaceone/denigma
|
0678e4a95d15d31c03d11baae765d6ce882f586d
|
36a8e7982c6a8d73f64aff02380439b0c3b750b4
|
refs/heads/master
| 2019-01-01T07:42:28.685853 | 2014-10-14T20:37:30 | 2014-10-14T20:37:30 | 42,683,895 | 0 | 0 | null | true | 2015-09-17T21:51:40 | 2015-09-17T21:51:40 | 2014-10-02T20:22:45 | 2014-10-14T20:37:58 | 17,619 | 0 | 0 | 0 | null | null | null |
import datetime
from haystack import indexes
from models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
created = indexes.DateTimeField(model_attr='created')
updated = indexes.DateTimeField(model_attr='updated')
text = indexes.CharField(document=True, use_template=True)
tags = indexes.MultiValueField()
def get_model(self):
return Post
def index_queryset(self):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(created__lte=datetime.datetime.now(), published=True)
|
UTF-8
|
Python
| false | false | 2,014 |
15,161,234,558,366 |
c1cce8bf6019cd20d89aced158c0b3f2dc2c43c4
|
bb518fc9c842b82a12728e3c199aae90ee4de15e
|
/bang_server/forms/bang.py
|
f7217b9dba2161961a409532b6e5442713d26a6e
|
[] |
no_license
|
deggs7/bang-origin
|
https://github.com/deggs7/bang-origin
|
b8517d7df97e3984be14e288ed9d3c338bd1979f
|
c307a3bf9f77289a8410501d69a3b7fbdd37613e
|
refs/heads/master
| 2021-01-23T12:17:48.687786 | 2014-04-17T09:25:25 | 2014-04-17T09:25:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
"""
bang_server.forms.bang
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by David De
"""
from flask.ext.wtf import Form, TextField, Required, BooleanField, \
PasswordField, validators, ValidationError
class CreateBangForm(Form):
name = TextField('Bang Name', [
Required(),
validators.Length(min=1, max=160),
])
class SearchBangForm(Form):
bang_str = TextField('Bang keyword',[
Required(),
validators.Length(min=1, max=160),
])
class SearchUserForm(Form):
user_str = TextField('User keyword',[
Required(),
validators.Length(min=1, max=100),
])
|
UTF-8
|
Python
| false | false | 2,014 |
6,193,342,874,812 |
1739a5885dd1015706c50b1a9d4e8664dd3b190e
|
5f94c768d7333ed9aab1f5a68e4dc7ce0f15d026
|
/src/fe2/helpers/cachedir.py
|
9372c300f4a5ef572cdc6dd990ed857b321366fd
|
[] |
no_license
|
WillemJan/IOTD
|
https://github.com/WillemJan/IOTD
|
28af03a862de4cdd11f18bc65088747a6f8a60e5
|
56f442bb56dc76579067f028e067e71907b0d212
|
refs/heads/master
| 2016-08-07T01:55:46.144745 | 2014-12-24T23:00:38 | 2014-12-24T23:00:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Copyright © 2013 Willem Jan Faber (http://www.fe2.nl) All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#* Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#* Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#* Neither the name of “Fe2“ nor the names of its contributors may be used to
# endorse or promote products derived from this software without specific prior
# written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
#ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
from fe2.helpers import homedir
from fe2.helpers import logger
def cachedir():
cachedir = os.path.join(homedir.get_homedir(), 'cache')
if not os.path.isdir(cachedir):
os.makedirs(cachedir)
return cachedir
def mkcachedir(cachedir):
if not os.path.isdir(cachedir):
os.makedirs(cachedir)
|
UTF-8
|
Python
| false | false | 2,014 |
11,587,821,770,452 |
5cc44dc83cc3399826f327e435ddeda1483b9706
|
39c4c1ee0485abb3c12fd99eee38aa1333e3517d
|
/src/zojax/principal/password/default.py
|
e5b1b5f6050ee6ccec8e1639b968591473aa9a29
|
[
"ZPL-2.1"
] |
permissive
|
Zojax/zojax.principal.password
|
https://github.com/Zojax/zojax.principal.password
|
1a071affff36d4dce23867de487f3f6e93d366b7
|
5f347f5c728b2abe125f7fca2e8ad69c517f7ff2
|
refs/heads/master
| 2016-09-06T08:30:12.172260 | 2014-01-29T16:05:11 | 2014-01-29T16:05:11 | 2,023,363 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
##############################################################################
#
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id$
"""
from zope import interface
from zope.schema import ValidationError
from zope.component import getUtility
from interfaces import _, PasswordError
from interfaces import IPasswordChecker, IDefaultPasswordCheckerConfiglet
class LengthPasswordError(PasswordError):
__doc__ = _('Password min length exceeded.')
def __init__(self, msg):
self.message = msg
def __str__(self):
return str(self.message)
def doc(self):
return self.message
class LettersDigitsPasswordError(PasswordError):
__doc__ = _('Password should contain both letters and digits.')
class LettersCasePasswordError(PasswordError):
__doc__ = _('Password should contain letters in mixed case.')
class DefaultPasswordChecker(object):
"""
>>> import zope.interface.verify
>>> from zope import interface, component
>>> from zojax.principal.password import interfaces, default
>>> zope.interface.verify.verifyClass(
... interfaces.IPasswordChecker, default.DefaultPasswordChecker)
True
Default password checker uses IDefaultPasswordCheckerConfiglet utility
to get configuration. We use controlpanel configlet for this but
in this code we should create it.
>>> class Configlet(object):
... interface.implements(interfaces.IDefaultPasswordCheckerConfiglet)
... min_length = 5
... letters_digits = False
... letters_mixed_case = False
>>> configlet = Configlet()
>>> component.provideUtility(configlet)
>>> checker = default.DefaultPasswordChecker()
>>> zope.interface.verify.verifyObject(interfaces.IPasswordChecker, checker)
True
>>> checker.validate('passw')
>>> checker.validate('ps1')
Traceback (most recent call last):
...
LengthPasswordError: ...
>>> configlet.min_length = 6
>>> checker.validate('passw')
Traceback (most recent call last):
...
LengthPasswordError: ...
>>> checker.validate('password')
>>> configlet.letters_digits = True
>>> checker.validate('password')
Traceback (most recent call last):
...
LettersDigitsPasswordError
>>> checker.validate('66665555')
Traceback (most recent call last):
...
LettersDigitsPasswordError
>>> checker.validate('pass5word')
>>> configlet.letters_mixed_case = True
>>> checker.validate('pass5word')
Traceback (most recent call last):
...
LettersCasePasswordError
>>> checker.validate('PASS5WORD')
Traceback (most recent call last):
...
LettersCasePasswordError
>>> checker.validate('Pass5word')
By default password strength is always 100%
>>> checker.passwordStrength('Pass5word')
100.0
"""
interface.implements(IPasswordChecker)
title = _(u'Default password checker')
def validate(self, password):
config = getUtility(IDefaultPasswordCheckerConfiglet)
if len(password) < config.min_length:
raise LengthPasswordError(
_('Password should be at least ${count} characters.',
mapping={'count': config.min_length}))
elif config.letters_digits and \
(password.isalpha() or password.isdigit()):
raise LettersDigitsPasswordError()
elif config.letters_mixed_case and \
(password.isupper() or password.islower()):
raise LettersCasePasswordError()
def passwordStrength(self, password):
return 100.0
def isAvailable(prefs):
return prefs.__name__ == prefs.__parent__.passwordChecker
|
UTF-8
|
Python
| false | false | 2,014 |
4,226,247,855,486 |
d5520a6be6e6f57b06611762352587d888c3c3db
|
0b8db821a277b7fa2d9da8844b9b869caaa37cf3
|
/strifepark_login/models.py
|
0257d65d697fee6827ca887d01990120a7dbad63
|
[] |
no_license
|
Kirembu/strifepark
|
https://github.com/Kirembu/strifepark
|
166bbd68b4902588ee9f8a8789304e157583ba14
|
bae1f08c474e12210c9dae9a2480537ffaf59e4f
|
refs/heads/master
| 2016-09-06T05:50:46.810270 | 2014-08-02T00:20:44 | 2014-08-02T00:20:44 | 3,647,400 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.db import models
from django.contrib.auth.models import User
class spUserProfile(models.Model):
user = models.ForeignKey(User)
bio = models.CharField(max_length=160,null=True,blank=True)
url = models.URLField(null=True,blank=True)
phone = models.CharField(max_length=25,null=True,blank=True)
class LoginStatus(models.Model):
userid = models.ForeignKey(User)
status = models.BooleanField()
class PasswordChangeRequest(models.Model):
account = models.ForeignKey(User)
req_random_key = models.CharField(max_length = 48)
created_at = models.DateTimeField()
|
UTF-8
|
Python
| false | false | 2,014 |
13,237,089,223,100 |
359f31ee4dead40f00a1ab7ed194484627de28c5
|
551e24499e3d0dbb4424e08ea78e8545f70ca21b
|
/python/lsst/detection/__init__.py
|
4c9e38e767cd2385a0c908f6100bdc00d50f1576
|
[] |
no_license
|
jonathansick-shadow/detection
|
https://github.com/jonathansick-shadow/detection
|
c1e858db34667499c7cae642406c808387038daf
|
277cb93284a2262c92c99935da747428221214d9
|
refs/heads/master
| 2021-01-12T12:02:59.244446 | 2011-12-09T20:03:49 | 2011-12-09T20:03:49 | 45,875,302 | 0 | 0 | null | true | 2015-11-09T23:59:41 | 2015-11-09T23:59:41 | 2014-08-16T07:42:19 | 2014-08-16T07:42:19 | 2,292 | 0 | 0 | 0 | null | null | null |
from detectionLib import *
|
UTF-8
|
Python
| false | false | 2,011 |
4,896,262,730,910 |
c985206ad5f364222306fe5aaac01b293ddca9d4
|
01766a6c51b6be326b6186e2e160269ea2ae6ea7
|
/FixedIncome/bond.py
|
1947b95dd919ec8c56c9e675133787b51df396d6
|
[] |
no_license
|
dhalik/fpl
|
https://github.com/dhalik/fpl
|
371ec5032985acebbf9f9ba54910be6e9a915444
|
6bd48218605c6fdb874d7f3e14de11d5f06b80aa
|
refs/heads/master
| 2020-06-07T18:39:30.603401 | 2014-08-04T00:01:44 | 2014-08-04T00:01:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from __future__ import division
from numpy import linspace
class Bond:
"""Basic bond object"""
def __init__(self, faceValue, coupon, maturity):
"""
@param faceValue - The face value of the bond
@param coupon - The coupon rate on the bond
@param maturity - The number of years until maturity of the bond
"""
self.couponRate = coupon
self.faceValue = faceValue
self.coupon = self.couponRate*faceValue
self.maturity = maturity
def price(self, rate):
"""
Calculate the price of a bond using a given rate
@param rate - The market rate to price the bond.
@return - The price of a bond
"""
annuity = self.coupon / rate * (1 - 1 / ((1 + rate) ** self.maturity))
fv = self.faceValue / (1 + rate) ** self.maturity
return annuity + fv
def main():
bond = Bond(1000, 0.08, 10)
template = "For rate {}, price is {}"
for r in xrange(1, 13):
print template.format(rate=r/100, price=bond.price(r/100))
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,014 |
17,162,689,346,804 |
d3b5a23a7918dc146ec513dd5a6b1b09c82edc26
|
74f48ca7c9dcb3d38cb65f6c6e9443e5757471db
|
/src/models.py
|
3b6ab68a4f8dc5370c64cefebec409d23a231894
|
[
"MIT"
] |
permissive
|
fagan2888/wealth-of-cities
|
https://github.com/fagan2888/wealth-of-cities
|
801d407f752ccd87197abe6bdd652dd54560c822
|
b42ba97ac3e1ec7acb3a8530d2d5400a0bd40104
|
refs/heads/master
| 2021-04-03T17:47:19.457503 | 2014-10-23T19:24:24 | 2014-10-23T19:24:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
Main classes representing the model.
@author : David R. Pugh
@date : 2014-10-21
"""
import numpy as np
import sympy as sym
# define parameters
f, beta, phi, tau = sym.var('f, beta, phi, tau')
elasticity_substitution = sym.DeferredVector('theta')
population = sym.DeferredVector('L')
# define variables
nominal_gdp = sym.DeferredVector('Y')
nominal_price_level = sym.DeferredVector('P')
nominal_wage = sym.DeferredVector('W')
num_firms = sym.DeferredVector('M')
class Model(object):
# initialize the cached values
__symbolic_equations = None
__symbolic_jacobian = None
__symbolic_system = None
__symbolic_variables = None
def __init__(self, params, physical_distances, population):
"""
Create an instance of the Model class.
Parameters
----------
params : dict
Dictionary of model parameters.
physical_distances : numpy.ndarray (shape=(N,N))
Square array of pairwise measures pf physical distance between
cities.
population : numpy.ndarray (shape=(N,))
Array of total population for each city.
"""
self.params = params
self.physical_distances = physical_distances
self.population = population
@property
def _symbolic_args(self):
"""
Arguments to pass to functions used for numeric evaluation of model.
:getter: Return the current arguments
:type: tuple
"""
variables = (nominal_price_level, nominal_gdp, nominal_wage, num_firms)
params = (population, f, beta, phi, tau, elasticity_substitution)
return variables + params
@property
def _symbolic_equations(self):
"""
List of symbolic equations defining the model.
:getter: Return the current list of model equations.
:type: list
"""
if self.__symbolic_equations is None:
# drop one equation as a result of normalization
N = self.number_cities
eqns = ([self.goods_market_clearing(h) for h in range(1, N)] +
[self.total_profits(h) for h in range(N)] +
[self.labor_market_clearing(h) for h in range(N)] +
[self.resource_constraint(h) for h in range(N)])
self.__symbolic_equations = eqns
return self.__symbolic_equations
@property
def _symbolic_jacobian(self):
"""
Symbolic representation of Jacobian matrix of partial derivatives.
:getter: Return the current Jacobian matrix.
:type: sympy.Matrix
"""
if self.__symbolic_jacobian is None:
jac = self._symbolic_system.jacobian(self._symbolic_variables)
self.__symbolic_jacobian = jac
return self.__symbolic_jacobian
@property
def _symbolic_system(self):
"""
Matrix representation of symbolic model equations.
:getter: Return the current model equations as a symbolic Matrix.
:type: sympy.Matrix
"""
return sym.Matrix(self._symbolic_equations)
@property
def _symbolic_variables(self):
"""
List of symbolic endogenous variables.
:getter: Return the current list of endogenous variables.
:type: list
"""
N = self.number_cities
if self.__symbolic_variables is None:
# normalize P[0] = 1.0 (only P[1]...P[num_cities-1] are unknowns)
variables = ([nominal_price_level[h] for h in range(1, N)] +
[nominal_gdp[h] for h in range(N)] +
[nominal_wage[h] for h in range(N)] +
[num_firms[h] for h in range(N)])
self.__symbolic_variables = variables
return self.__symbolic_variables
@property
def economic_distances(self):
"""
Square matrix of pairwise measures of economic distance between cities.
:getter: Return the matrix of economic distances.
:type: sympy.Basic
"""
return np.exp(self.physical_distances)**tau
@property
def number_cities(self):
"""
Number of cities in the economy.
:getter: Return the current number of cities.
:setter: Set a new number of cities.
:type: int
"""
return self._number_cities
@number_cities.setter
def number_cities(self, value):
"""Set a new number of cities."""
self._number_cities = self._validate_number_cities(value)
# don't forget to clear cache!
self._clear_cache()
@property
def physical_distances(self):
"""
Square array of pairwise measures pf physical distance between cities.
:getter: Return the current array of physical distances.
:setter: Set a new array of physical distances.
:type: numpy.ndarray
"""
return self._physical_distances[:self.number_cities, :self.number_cities]
@physical_distances.setter
def physical_distances(self, array):
"""Set a new array of physical distances."""
self._physical_distances = array
@property
def params(self):
"""
Dictionary of model parameters.
:getter: Return the current parameter dictionary.
:setter: Set a new parameter dictionary.
:type: dict
"""
return self._params
@params.setter
def params(self, value):
"""Set a new parameter dictionary."""
self._params = self._validate_params(value)
def _clear_cache(self):
"""Clear all cached values."""
self.__symbolic_equations = None
self.__symbolic_jacobian = None
self.__symbolic_system = None
self.__symbolic_variables = None
@classmethod
def _validate_number_cities(cls, value):
"""Validate number of cities attribute."""
if not isinstance(value, int):
mesg = "Model.number_cities attribute must have type int, not {}"
raise AttributeError(mesg.format(value.__class__))
elif value < 1:
mesg = ("Model.number_cities attribute must be greater than " +
"or equal to 1.")
raise AttributeError(mesg)
else:
return value
@classmethod
def _validate_params(cls, params):
"""Validate params attribute."""
required_params = ['f', 'beta', 'phi', 'tau']
if not isinstance(params, dict):
mesg = "Model.params attribute must have type dict and not {}"
raise AttributeError(mesg.format(params.__class__))
elif not set(required_params) <= set(params.keys()):
mesg = "Parameter dictionary must specify values for each of {}"
raise AttributeError(mesg.format(required_params))
else:
return params
def effective_labor_supply(self, h):
"""Effective labor supply is a constant multple of total population."""
return beta * population[h]
def goods_market_clearing(self, h):
"""Exports must balance imports for city h."""
return self.total_exports(h) - self.total_imports(h)
def labor_market_clearing(self, h):
"""Labor market clearing condition for city h."""
return self.effective_labor_supply(h) - self.total_labor_demand(h)
def labor_productivity(self, h, j):
"""Productivity of labor in city h when producing good j."""
return phi / self.economic_distances[h, j]
def marginal_costs(self, h, j):
"""Marginal costs of production of good j in city h."""
return nominal_wage[h] / self.labor_productivity(h, j)
@staticmethod
def mark_up(j):
"""Markup over marginal costs of production for good j."""
return (elasticity_substitution[j] / (elasticity_substitution[j] - 1))
def optimal_price(self, h, j):
"""Optimal price of good j sold in city h."""
return self.mark_up(j) * self.marginal_costs(h, j)
@classmethod
def quantity_demand(cls, price, j):
"""Quantity demand of a good is negative function of price."""
return cls.relative_price(price, j)**(-elasticity_substitution[j]) * cls.real_gdp(j)
@staticmethod
def real_gdp(i):
"""Real gross domestic product of city i."""
return nominal_gdp[i] / nominal_price_level[i]
@staticmethod
def relative_price(price, j):
"""Relative price of a good in city j."""
return price / nominal_price_level[j]
def resource_constraint(self, h):
"""Nominal GDP in city h must equal nominal income in city h."""
constraint = (nominal_gdp[h] -
self.effective_labor_supply(h) * nominal_wage[h])
return constraint
@staticmethod
def revenue(price, quantity):
"""Revenue from producing a certain quantity at a given price."""
return price * quantity
def total_cost(self, h):
"""Total cost of production for a firm in city h."""
return self.total_variable_cost(h) + self.total_fixed_cost(h)
def total_exports(self, h):
"""Total exports of various goods from city h."""
individual_exports = []
for j in range(self.number_cities):
p_star = self.optimal_price(h, j)
q_star = self.quantity_demand(p_star, j)
total_revenue_h = num_firms[h] * self.revenue(p_star, q_star)
individual_exports.append(total_revenue_h)
return sum(individual_exports)
@staticmethod
def total_fixed_cost(h):
"""Total fixed cost of production for a firm in city h."""
return f * nominal_wage[h]
@staticmethod
def total_fixed_labor_demand(h):
"""Total fixed labor demand for firms in city h."""
return num_firms[h] * f
def total_imports(self, h):
"""Total imports of various goods into city h."""
individual_imports = []
for j in range(self.number_cities):
p_star = self.optimal_price(j, h)
q_star = self.quantity_demand(p_star, h)
total_revenue_j = num_firms[j] * self.revenue(p_star, q_star)
individual_imports.append(total_revenue_j)
return sum(individual_imports)
def total_labor_demand(self, h):
"""Total demand for labor for firms in city h."""
total_demand = (self.total_variable_labor_demand(h) +
self.total_fixed_labor_demand(h))
return total_demand
def total_profits(self, h):
"""Total profits for a firm in city h."""
return self.total_revenue(h) - self.total_cost(h)
def total_revenue(self, h):
"""Total revenue for a firm producing in city h."""
individual_revenues = []
for j in range(self.number_cities):
p_star = self.optimal_price(h, j)
q_star = self.quantity_demand(p_star, j)
individual_revenues.append(self.revenue(p_star, q_star))
return sum(individual_revenues)
def total_variable_cost(self, h):
"""Total variable costs of production for a firm in city h."""
individual_variable_costs = []
for j in range(self.number_cities):
p_star = self.optimal_price(h, j)
q_star = self.quantity_demand(p_star, j)
individual_variable_costs.append(self.variable_cost(q_star, h, j))
return sum(individual_variable_costs)
def total_variable_labor_demand(self, h):
"""Total variable labor demand for firms in city h."""
individual_labor_demands = []
for j in range(self.number_cities):
p_star = self.optimal_price(h, j)
q_star = self.quantity_demand(p_star, j)
variable_demand_h = self.variable_labor_demand(q_star, h, j)
individual_labor_demands.append(variable_demand_h)
return num_firms[h] * sum(individual_labor_demands)
def variable_cost(self, quantity, h, j):
"""
Variable cost of a firm in city h to produce a given quantity of good
for sale in city j.
"""
return self.variable_labor_demand(quantity, h, j) * nominal_wage[h]
def variable_labor_demand(self, quantity, h, j):
"""
Variable labor demand by firm in city h to produce a given quantity of
good for sale in city j.
"""
return quantity / self.labor_productivity(h, j)
class SingleCityModel(Model):
# initialize cached values
__numeric_gdp = None
__numeric_num_firms = None
__numeric_wage = None
__symbolic_solution = None
_modules = [{'ImmutableMatrix': np.array}, "numpy"]
def __init__(self, params, physical_distances, population):
"""
Create an instance of the SingleCityModel class.
Parameters
----------
params : dict
Dictionary of model parameters.
physical_distances : numpy.ndarray (shape=(N,N))
Square array of pairwise measures pf physical distance between
cities.
population : numpy.ndarray (shape=(N,))
Array of total population for each city.
"""
super(SingleCityModel, self).__init__(params, physical_distances, population)
self.number_cities = 1
@property
def solution(self):
"""
Equilbrium values of nominal GDP, nominal wages, and number of firms.
:getter: Return current solution.
:type: numpy.ndarray
"""
P0 = np.ones(1.0)
Y0 = self.compute_nominal_gdp(P0, self.population, self.params)
W0 = self.compute_nominal_wage(P0, self.population, self.params)
M0 = self.compute_number_firms(P0, self.population, self.params)
return np.hstack((Y0, W0, M0))
@property
def _numeric_gdp(self):
"""
Vectorized function for evaluating solution for nominal GDP.
:getter: Return the current function.
:type: function
"""
if self.__numeric_gdp is None:
Y = nominal_gdp[0]
self.__numeric_gdp = sym.lambdify(self._symbolic_args,
self._symbolic_solution[Y],
self._modules)
return self.__numeric_gdp
@property
def _numeric_wage(self):
"""
Vectorized function for evaluating solution for nominal wage.
:getter: Return the current function.
:type: function
"""
if self.__numeric_wage is None:
W = nominal_wage[0]
self.__numeric_wage = sym.lambdify(self._symbolic_args,
self._symbolic_solution[W],
self._modules)
return self.__numeric_wage
@property
def _numeric_num_firms(self):
"""
Vectorized function for evaluating solution for number of firms.
:getter: Return the current function.
:type: function
"""
if self.__numeric_num_firms is None:
M = num_firms[0]
self.__numeric_num_firms = sym.lambdify(self._symbolic_args,
self._symbolic_solution[M],
self._modules)
return self.__numeric_num_firms
@property
def _symbolic_args(self):
"""
Arguments to pass to functions used for numeric evaluation of model.
:getter: Return the current arguments
:type: tuple
"""
variables = (nominal_price_level, population)
params = (f, beta, phi, tau, elasticity_substitution)
return variables + params
@property
def _symbolic_solution(self):
"""
Dictionary of symbolic expressions for analytic solution to the model.
:getter: Return the analytic solution to the model as a dictionary.
:type: dict
"""
if self.__symbolic_solution is None:
self.__symbolic_solution, = sym.solve(self._symbolic_equations,
self._symbolic_variables,
dict=True)
return self.__symbolic_solution
def compute_nominal_gdp(self, price_level, population, params):
"""
Compute equilibrium nominal GDP for the city given a price level and
some parameters.
Parameters
----------
price_level : numpy.ndarray (shape=(1,))
Price level index for the city.
population : numpy.ndarray (shape=(1,))
Total population for the city.
params : dict
Dictionary of model parameters.
Returns
-------
nominal_gdp : float
Equilibrium nominal GDP for the city.
"""
nominal_gdp = self._numeric_gdp(price_level, population, **params)
return nominal_gdp
def compute_nominal_wage(self, price_level, population, params):
"""
Compute equilibrium nominal wage for the city given a price level and
some parameters.
Parameters
----------
price_level : numpy.ndarray (shape=(1,))
Price level index for the city.
population : numpy.ndarray (shape=(1,))
Total population for the city.
params : dict
Dictionary of model parameters.
Returns
-------
nominal_wage : float
Equilibrium nominal wages for the city.
"""
nominal_wage = self._numeric_wage(price_level, population, **params)
return nominal_wage
def compute_number_firms(self, price_level, population, params):
"""
Compute equilibrium nominal number of firms for the city given a price
level and some parameters.
Parameters
----------
price_level : numpy.ndarray (shape=(1,))
Price level index for the city.
population : numpy.ndarray (shape=(1,))
Total population for the city.
params : dict
Dictionary of model parameters.
Returns
-------
number_firms: float
Equilibrium number of firms.
"""
number_firms = self._numeric_num_firms(price_level, population, **params)
return number_firms
|
UTF-8
|
Python
| false | false | 2,014 |
15,556,371,574,793 |
bcbe9b57a419a65887d9c8c826db4ebeb9a131f9
|
fb500cf4b6e199e7132a78d4a90645836be3fbc4
|
/PyDC/PyDC/CassetteObjects.py
|
93be509ece0d2091de5586f34b6519c660880c8b
|
[
"GPL-3.0-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-or-later",
"GPL-1.0-or-later"
] |
non_permissive
|
jedie/PyDragon32
|
https://github.com/jedie/PyDragon32
|
4493a6e9d34b0e08d613d4e579aebb8e77d7a67b
|
f7305c7741af579bfdc1909a5a6be6fc7cf81acd
|
refs/heads/master
| 2020-12-24T14:09:28.813140 | 2014-09-29T07:44:26 | 2014-09-29T07:44:26 | 12,244,451 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python2
# coding: utf-8
"""
PyDC - Cassette Objects
=======================
Python objects to hold the content of a Cassette.
:copyleft: 2013 by Jens Diemer
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
import itertools
import logging
import os
import sys
# own modules
from basic_tokens import bytes2codeline
from utils import get_word, codepoints2string, string2codepoint, LOG_LEVEL_DICT, \
LOG_FORMATTER, pformat_codepoints
from wave2bitstream import Wave2Bitstream, Bitstream2Wave
from bitstream_handler import BitstreamHandler, CasStream, BytestreamHandler
from PyDC.utils import iter_steps
log = logging.getLogger("PyDC")
class CodeLine(object):
def __init__(self, line_pointer, line_no, code):
assert isinstance(line_no, int), "Line number not integer, it's: %s" % repr(line_no)
self.line_pointer = line_pointer
self.line_no = line_no
self.code = code
def get_ascii_codeline(self):
return "%i %s" % (self.line_no, self.code)
def get_as_codepoints(self):
return tuple(string2codepoint(self.get_ascii_codeline()))
def __repr__(self):
return "<CodeLine pointer: %s line no: %s code: %s>" % (
repr(self.line_pointer), repr(self.line_no), repr(self.code)
)
class FileContent(object):
"""
Content (all data blocks) of a cassette file.
"""
def __init__(self, cfg):
self.cfg = cfg
self.code_lines = []
def create_from_bas(self, file_content):
for line in file_content.splitlines():
if not line:
# Skip empty lines (e.g. XRoar need a empty line at the end)
continue
try:
line_number, code = line.split(" ", 1)
except ValueError:
etype, evalue, etb = sys.exc_info()
evalue = etype(
"Error split line: %s (line: %s)" % (evalue, repr(line))
)
raise etype, evalue, etb
line_number = int(line_number)
if self.cfg.case_convert:
code = code.upper()
self.code_lines.append(
CodeLine(None, line_number, code)
)
def add_block_data(self, block_length, data):
"""
add a block of tokenized BASIC source code lines.
>>> cfg = Dragon32Config
>>> fc = FileContent(cfg)
>>> block = [
... 0x1e,0x12,0x0,0xa,0x80,0x20,0x49,0x20,0xcb,0x20,0x31,0x20,0xbc,0x20,0x31,0x30,0x0,
... 0x0,0x0]
>>> len(block)
19
>>> fc.add_block_data(19,iter(block))
19 Bytes parsed
>>> fc.print_code_lines()
10 FOR I = 1 TO 10
>>> block = iter([
... 0x1e,0x29,0x0,0x14,0x87,0x20,0x49,0x3b,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22,0x0,
... 0x0,0x0])
>>> fc.add_block_data(999,block)
25 Bytes parsed
ERROR: Block length value 999 is not equal to parsed bytes!
>>> fc.print_code_lines()
10 FOR I = 1 TO 10
20 PRINT I;"HELLO WORLD!"
>>> block = iter([
... 0x1e,0x31,0x0,0x1e,0x8b,0x20,0x49,0x0,
... 0x0,0x0])
>>> fc.add_block_data(10,block)
10 Bytes parsed
>>> fc.print_code_lines()
10 FOR I = 1 TO 10
20 PRINT I;"HELLO WORLD!"
30 NEXT I
Test function tokens in code
>>> fc = FileContent(cfg)
>>> data = iter([
... 0x1e,0x4a,0x0,0x1e,0x58,0xcb,0x58,0xc3,0x4c,0xc5,0xff,0x88,0x28,0x52,0x29,0x3a,0x59,0xcb,0x59,0xc3,0x4c,0xc5,0xff,0x89,0x28,0x52,0x29,0x0,
... 0x0,0x0
... ])
>>> fc.add_block_data(30, data)
30 Bytes parsed
>>> fc.print_code_lines()
30 X=X+L*SIN(R):Y=Y+L*COS(R)
Test high line numbers
>>> fc = FileContent(cfg)
>>> data = [
... 0x1e,0x1a,0x0,0x1,0x87,0x20,0x22,0x4c,0x49,0x4e,0x45,0x20,0x4e,0x55,0x4d,0x42,0x45,0x52,0x20,0x54,0x45,0x53,0x54,0x22,0x0,
... 0x1e,0x23,0x0,0xa,0x87,0x20,0x31,0x30,0x0,
... 0x1e,0x2d,0x0,0x64,0x87,0x20,0x31,0x30,0x30,0x0,
... 0x1e,0x38,0x3,0xe8,0x87,0x20,0x31,0x30,0x30,0x30,0x0,
... 0x1e,0x44,0x27,0x10,0x87,0x20,0x31,0x30,0x30,0x30,0x30,0x0,
... 0x1e,0x50,0x80,0x0,0x87,0x20,0x33,0x32,0x37,0x36,0x38,0x0,
... 0x1e,0x62,0xf9,0xff,0x87,0x20,0x22,0x45,0x4e,0x44,0x22,0x3b,0x36,0x33,0x39,0x39,0x39,0x0,0x0,0x0
... ]
>>> len(data)
99
>>> fc.add_block_data(99, iter(data))
99 Bytes parsed
>>> fc.print_code_lines()
1 PRINT "LINE NUMBER TEST"
10 PRINT 10
100 PRINT 100
1000 PRINT 1000
10000 PRINT 10000
32768 PRINT 32768
63999 PRINT "END";63999
"""
# data = list(data)
# # print repr(data)
# print_as_hex_list(data)
# print_codepoint_stream(data)
# sys.exit()
# create from codepoint list a iterator
data = iter(data)
byte_count = 0
while True:
try:
line_pointer = get_word(data)
except (StopIteration, IndexError), err:
log.error("No line pointer information in code line data. (%s)" % err)
break
# print "line_pointer:", repr(line_pointer)
byte_count += 2
if not line_pointer:
# arrived [0x00, 0x00] -> end of block
break
try:
line_number = get_word(data)
except (StopIteration, IndexError), err:
log.error("No line number information in code line data. (%s)" % err)
break
# print "line_number:", repr(line_number)
byte_count += 2
# data = list(data)
# print_as_hex_list(data)
# print_codepoint_stream(data)
# data = iter(data)
# get the code line:
# new iterator to get all characters until 0x00 arraived
code = iter(data.next, 0x00)
code = list(code) # for len()
byte_count += len(code) + 1 # from 0x00 consumed in iter()
# print_as_hex_list(code)
# print_codepoint_stream(code)
# convert to a plain ASCII string
code = bytes2codeline(code)
self.code_lines.append(
CodeLine(line_pointer, line_number, code)
)
print "%i Bytes parsed" % byte_count
if block_length != byte_count:
print "ERROR: Block length value %i is not equal to parsed bytes!" % block_length
def add_ascii_block(self, block_length, data):
"""
add a block of ASCII BASIC source code lines.
>>> data = [
... 0xd,
... 0x31,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x54,0x45,0x53,0x54,0x22,
... 0xd,
... 0x32,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22,
... 0xd
... ]
>>> len(data)
41
>>> fc = FileContent(Dragon32Config)
>>> fc.add_ascii_block(41, iter(data))
41 Bytes parsed
>>> fc.print_code_lines()
10 PRINT "TEST"
20 PRINT "HELLO WORLD!"
"""
data = iter(data)
data.next() # Skip first \r
byte_count = 1 # incl. first \r
while True:
code = iter(data.next, 0xd) # until \r
code = "".join([chr(c) for c in code])
if not code:
log.warning("code ended.")
break
byte_count += len(code) + 1 # and \r consumed in iter()
try:
line_number, code = code.split(" ", 1)
except ValueError, err:
print "\nERROR: Splitting linenumber in %s: %s" % (repr(code), err)
break
try:
line_number = int(line_number)
except ValueError, err:
print "\nERROR: Part '%s' is not a line number!" % repr(line_number)
continue
self.code_lines.append(
CodeLine(None, line_number, code)
)
print "%i Bytes parsed" % byte_count
if block_length != byte_count:
log.error(
"Block length value %i is not equal to parsed bytes!" % block_length
)
def get_as_codepoints(self):
result = []
delim = list(string2codepoint("\r"))[0]
for code_line in self.code_lines:
result.append(delim)
result += list(code_line.get_as_codepoints())
result.append(delim)
# log.debug("-"*79)
# for line in pformat_codepoints(result):
# log.debug(repr(line))
# log.debug("-"*79)
return result
def get_ascii_codeline(self):
for code_line in self.code_lines:
yield code_line.get_ascii_codeline()
def print_code_lines(self):
for code_line in self.code_lines:
print "%i %s" % (code_line.line_no, code_line.code)
def print_debug_info(self):
print "\tcode lines:"
print "-"*79
self.print_code_lines()
print "-"*79
class CassetteFile(object):
def __init__(self, cfg):
self.cfg = cfg
self.is_tokenized = False
self.ascii_flag = None
self.gap_flag = None # one byte gap flag (0x00=no gaps, 0xFF=gaps)
def create_from_bas(self, filename, file_content):
filename2 = os.path.split(filename)[1]
filename2 = filename2.upper()
filename2 = filename2.rstrip()
filename2 = filename2.replace(" ", "_")
# TODO: remove non ASCII!
filename2 = filename2[:8]
log.debug("filename '%s' from: %s" % (filename2, filename))
self.filename = filename2
self.file_type = self.cfg.FTYPE_BASIC # BASIC programm (0x00)
# http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4231&p=9723#p9723
self.ascii_flag = self.cfg.BASIC_ASCII
self.gap_flag = self.cfg.GAPS # ASCII File is GAP, tokenized is no gaps
self.file_content = FileContent(self.cfg)
self.file_content.create_from_bas(file_content)
def create_from_wave(self, codepoints):
log.debug("filename data: %s" % pformat_codepoints(codepoints))
raw_filename = codepoints[:8]
self.filename = codepoints2string(raw_filename).rstrip()
print "\nFilename: %s" % repr(self.filename)
self.file_type = codepoints[8]
if not self.file_type in self.cfg.FILETYPE_DICT:
raise NotImplementedError(
"Unknown file type %s is not supported, yet." % hex(self.file_type)
)
log.info("file type: %s" % self.cfg.FILETYPE_DICT[self.file_type])
if self.file_type == self.cfg.FTYPE_DATA:
raise NotImplementedError("Data files are not supported, yet.")
elif self.file_type == self.cfg.FTYPE_BIN:
raise NotImplementedError("Binary files are not supported, yet.")
self.ascii_flag = codepoints[9]
log.info("Raw ASCII flag is: %s" % repr(self.ascii_flag))
if self.ascii_flag == self.cfg.BASIC_TOKENIZED:
self.is_tokenized = True
elif self.ascii_flag == self.cfg.BASIC_ASCII:
self.is_tokenized = False
else:
raise NotImplementedError("Unknown BASIC type: '%s'" % hex(self.ascii_flag))
log.info("ASCII flag: %s" % self.cfg.BASIC_TYPE_DICT[self.ascii_flag])
self.gap_flag = codepoints[10]
log.info("gap flag is %s (0x00=no gaps, 0xff=gaps)" % hex(self.gap_flag))
# machine code starting/loading address
if self.file_type != self.cfg.FTYPE_BASIC: # BASIC programm (0x00)
codepoints = iter(codepoints)
self.start_address = get_word(codepoints)
log.info("machine code starting address: %s" % hex(self.start_address))
self.load_address = get_word(codepoints)
log.info("machine code loading address: %s" % hex(self.load_address))
else:
# not needed in BASIC files
# http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4341&p=9109#p9109
pass
self.file_content = FileContent(self.cfg)
def add_block_data(self, block_length, codepoints):
if self.is_tokenized:
self.file_content.add_block_data(block_length, codepoints)
else:
self.file_content.add_ascii_block(block_length, codepoints)
print "*"*79
self.file_content.print_code_lines()
print "*"*79
def get_filename_block_as_codepoints(self):
"""
TODO: Support tokenized BASIC. Now we only create ASCII BASIC.
"""
codepoints = []
codepoints += list(string2codepoint(self.filename.ljust(8, " ")))
codepoints.append(self.cfg.FTYPE_BASIC) # one byte file type
codepoints.append(self.cfg.BASIC_ASCII) # one byte ASCII flag
# one byte gap flag (0x00=no gaps, 0xFF=gaps)
# http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4231&p=9110#p9110
codepoints.append(self.gap_flag)
# machine code starting/loading address
if self.file_type != self.cfg.FTYPE_BASIC: # BASIC programm (0x00)
codepoints = iter(codepoints)
self.start_address = get_word(codepoints)
log.info("machine code starting address: %s" % hex(self.start_address))
self.load_address = get_word(codepoints)
log.info("machine code loading address: %s" % hex(self.load_address))
else:
# not needed in BASIC files
# http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4341&p=9109#p9109
pass
log.debug("filename block: %s" % pformat_codepoints(codepoints))
return codepoints
def get_code_block_as_codepoints(self):
result = self.file_content.get_as_codepoints()
# XXX: Is a code block end terminator needed?
# e.g.:
# if self.is_tokenized:
# result += [0x00, 0x00]
# else:
# result.append(0x0d) # 0x0d == \r
return result
def print_debug_info(self):
print "\tFilename: '%s'" % self.filename
print "\tfile type: %s" % self.cfg.FILETYPE_DICT[self.file_type]
print "\tis tokenized:", self.is_tokenized
self.file_content.print_debug_info()
def __repr__(self):
return "<BlockFile '%s'>" % (self.filename,)
class Cassette(object):
"""
>>> d32cfg = Dragon32Config()
>>> c = Cassette(d32cfg)
>>> c.add_from_bas("../test_files/HelloWorld1.bas")
>>> c.print_debug_info() # doctest: +NORMALIZE_WHITESPACE
There exists 1 files:
Filename: 'HELLOWOR'
file type: BASIC programm (0x00)
is tokenized: False
code lines:
-------------------------------------------------------------------------------
10 FOR I = 1 TO 10
20 PRINT I;"HELLO WORLD!"
30 NEXT I
-------------------------------------------------------------------------------
>>> c.pprint_codepoint_stream()
255 x LEAD_BYTE_CODEPOINT
0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55 0x55
1x SYNC_BYTE_CODEPOINT
0x3c
block type filename block (0x00)
0x0
block length: 0xa
0xa
yield block data
0x48 0x45 0x4c 0x4c 0x4f 0x57 0x4f 0x52 0x0 0xff
block type data block (0x01)
0x1
block length: 0x36
0x36
yield block data
0x31 0x30 0x20 0x46 0x4f 0x52 0x20 0x49 0x20 0x3d 0x20 0x31 0x20 0x54 0x4f 0x20 0x31 0x30 0x32 0x30 0x20 0x50 0x52 0x49 0x4e 0x54 0x20 0x49 0x3b 0x22 0x48 0x45 0x4c 0x4c 0x4f 0x20 0x57 0x4f 0x52 0x4c 0x44 0x21 0x22 0x33 0x30 0x20 0x4e 0x45 0x58 0x54 0x20 0x49 0x0 0x0
block type end-of-file block (0xff)
0xff
block length: 0x0
0x0
"""
def __init__(self, cfg):
self.cfg = cfg
self.files = []
self.current_file = None
self.wav = None # Bitstream2Wave instance only if write_wave() used!
# temp storage for code block
self.buffer = []
self.buffered_block_length = 0
def add_from_wav(self, source_file):
bitstream = iter(Wave2Bitstream(source_file, self.cfg))
# store bitstream into python objects
bh = BitstreamHandler(self, self.cfg)
bh.feed(bitstream)
def add_from_cas(self, source_file):
cas_stream = CasStream(source_file)
bh = BytestreamHandler(self, self.cfg)
bh.feed(cas_stream)
def add_from_bas(self, filename):
with open(filename, "r") as f:
file_content = f.read()
self.current_file = CassetteFile(self.cfg)
self.current_file.create_from_bas(filename, file_content)
self.files.append(self.current_file)
def buffer2file(self):
"""
add the code buffer content to CassetteFile() instance
"""
if self.current_file is not None and self.buffer:
self.current_file.add_block_data(self.buffered_block_length, self.buffer)
self.buffer = []
self.buffered_block_length = 0
def buffer_block(self, block_type, block_length, block_codepoints):
block = tuple(itertools.islice(block_codepoints, block_length))
log.debug("pprint block: %s" % pformat_codepoints(block))
if block_type == self.cfg.EOF_BLOCK:
self.buffer2file()
return
elif block_type == self.cfg.FILENAME_BLOCK:
self.buffer2file()
self.current_file = CassetteFile(self.cfg)
self.current_file.create_from_wave(block)
log.info("Add file %s" % repr(self.current_file))
self.files.append(self.current_file)
elif block_type == self.cfg.DATA_BLOCK:
# store code until end marker
self.buffer += block
self.buffered_block_length += block_length
else:
raise TypeError("Block type %s unkown!" & hex(block_type))
def print_debug_info(self):
print "There exists %s files:" % len(self.files)
for file_obj in self.files:
file_obj.print_debug_info()
def block2codepoint_stream(self, file_obj, block_type, block_codepoints):
if file_obj.gap_flag == self.cfg.GAPS:
# file has gaps (e.g. ASCII BASIC)
log.debug("File has GAP flag set:")
log.debug("yield %sx bit-sync bytes %s",
self.cfg.LEAD_BYTE_LEN, hex(self.cfg.LEAD_BYTE_CODEPOINT)
)
leadin = [self.cfg.LEAD_BYTE_CODEPOINT for _ in xrange(self.cfg.LEAD_BYTE_LEN)]
yield leadin
log.debug("yield 1x leader byte %s", hex(self.cfg.LEAD_BYTE_CODEPOINT))
yield self.cfg.LEAD_BYTE_CODEPOINT
log.debug("yield sync byte %s" % hex(self.cfg.SYNC_BYTE_CODEPOINT))
if self.wav:
log.debug("wave pos: %s" % self.wav.pformat_pos())
yield self.cfg.SYNC_BYTE_CODEPOINT
log.debug("yield block type '%s'" % self.cfg.BLOCK_TYPE_DICT[block_type])
yield block_type
codepoints = tuple(block_codepoints)
block_length = len(codepoints)
assert block_length <= 255
log.debug("yield block length %s (%sBytes)" % (hex(block_length), block_length))
yield block_length
if not codepoints:
# EOF block
# FIXME checksum
checksum = block_type
checksum += block_length
checksum = checksum & 0xFF
log.debug("yield calculated checksum %s" % hex(checksum))
yield checksum
else:
log.debug("content of '%s':" % self.cfg.BLOCK_TYPE_DICT[block_type])
log.debug("-"*79)
log.debug(repr("".join([chr(i) for i in codepoints])))
log.debug("-"*79)
yield codepoints
checksum = sum([codepoint for codepoint in codepoints])
checksum += block_type
checksum += block_length
checksum = checksum & 0xFF
log.debug("yield calculated checksum %s" % hex(checksum))
yield checksum
log.debug("yield 1x tailer byte %s", hex(self.cfg.LEAD_BYTE_CODEPOINT))
yield self.cfg.LEAD_BYTE_CODEPOINT
def codepoint_stream(self):
if self.wav:
self.wav.write_silence(sec=0.1)
for file_obj in self.files:
# yield filename
for codepoints in self.block2codepoint_stream(file_obj,
block_type=self.cfg.FILENAME_BLOCK,
block_codepoints=file_obj.get_filename_block_as_codepoints()
):
yield codepoints
if self.wav:
self.wav.write_silence(sec=0.1)
# yield file content
codepoints = file_obj.get_code_block_as_codepoints()
for raw_codepoints in iter_steps(codepoints, 255):
# log.debug("-"*79)
# log.debug("".join([chr(i) for i in raw_codepoints]))
# log.debug("-"*79)
# Add meta information
codepoint_stream = self.block2codepoint_stream(file_obj,
block_type=self.cfg.DATA_BLOCK, block_codepoints=raw_codepoints
)
for codepoints2 in codepoint_stream:
yield codepoints2
if self.wav:
self.wav.write_silence(sec=0.1)
# yield EOF
for codepoints in self.block2codepoint_stream(file_obj,
block_type=self.cfg.EOF_BLOCK,
block_codepoints=[]
):
yield codepoints
if self.wav:
self.wav.write_silence(sec=0.1)
def write_wave(self, destination_file):
wav = Bitstream2Wave(destination_file, self.cfg)
for codepoint in self.codepoint_stream():
if isinstance(codepoint, (tuple, list)):
for item in codepoint:
assert isinstance(item, int), "Codepoint %s is not int/hex" % repr(codepoint)
else:
assert isinstance(codepoint, int), "Codepoint %s is not int/hex" % repr(codepoint)
wav.write_codepoint(codepoint)
wav.close()
def write_cas(self, destination_file):
log.info("Create %s..." % repr(destination_file))
def _write(f, codepoint):
try:
f.write(chr(codepoint))
except ValueError, err:
log.error("Value error with %s: %s" % (repr(codepoint), err))
raise
with open(destination_file, "wb") as f:
for codepoint in self.codepoint_stream():
if isinstance(codepoint, (tuple, list)):
for item in codepoint:
_write(f, item)
else:
_write(f, codepoint)
print "\nFile %s saved." % repr(destination_file)
def write_bas(self, destination_file):
dest_filename = os.path.splitext(destination_file)[0]
for file_obj in self.files:
bas_filename = file_obj.filename # Filename from CSAVE argument
out_filename = "%s_%s.bas" % (dest_filename, bas_filename)
log.info("Create %s..." % repr(out_filename))
with open(out_filename, "w") as f:
for line in file_obj.file_content.get_ascii_codeline():
if self.cfg.case_convert:
line = line.lower()
f.write("%s\n" % line)
print "\nFile %s saved." % repr(out_filename)
def pprint_codepoint_stream(self):
log_level = LOG_LEVEL_DICT[3]
log.setLevel(log_level)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(LOG_FORMATTER)
log.addHandler(handler)
for codepoint in self.codepoint_stream():
try:
print hex(codepoint),
except TypeError, err:
raise TypeError(
"\n\nERROR with '%s': %s" % (repr(codepoint), err)
)
if __name__ == "__main__":
# import doctest
# print doctest.testmod(
# verbose=False
# # verbose=True
# )
# sys.exit()
import subprocess
# bas -> wav
subprocess.Popen([sys.executable, "../PyDC_cli.py",
# "--verbosity=10",
"--verbosity=5",
# "--logfile=5",
# "--log_format=%(module)s %(lineno)d: %(message)s",
# "../test_files/HelloWorld1.bas", "--dst=../test.wav"
"../test_files/HelloWorld1.bas", "--dst=../test.cas"
]).wait()
# print "\n"*3
# print "="*79
# print "\n"*3
#
# # # wav -> bas
# subprocess.Popen([sys.executable, "../PyDC_cli.py",
# # "--verbosity=10",
# "--verbosity=7",
# # "../test.wav", "--dst=../test.bas",
# # "../test.cas", "--dst=../test.bas",
# # "../test_files/HelloWorld1 origin.wav", "--dst=../test_files/HelloWorld1.bas",
# "../test_files/LineNumber Test 02.wav", "--dst=../test.bas",
# ]).wait()
#
# print "-- END --"
|
UTF-8
|
Python
| false | false | 2,014 |
11,450,382,859,518 |
aa3f1dc93ef5605ea12138495ee214e0f474e7e7
|
d8f49aac2841880f2ff7349e72a9cf30c386d1dd
|
/libbe/command/new.py
|
33ede500b53ea152d311322dd57bc6fac39038a0
|
[
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only"
] |
non_permissive
|
mikadosoftware/be
|
https://github.com/mikadosoftware/be
|
8c08405068f8badefe4856178c5bc0c20cf4c027
|
49808306c939de24acabc423024970a76055e52b
|
refs/heads/master
| 2021-01-20T02:16:43.876975 | 2013-10-31T17:46:09 | 2013-10-31T20:26:01 | 15,676,263 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Copyright (C) 2005-2012 Aaron Bentley <[email protected]>
# Andrew Cooper <[email protected]>
# Chris Ball <[email protected]>
# Gianluca Montecchi <[email protected]>
# Niall Douglas ([email protected]) <[email protected]>
# W. Trevor King <[email protected]>
#
# This file is part of Bugs Everywhere.
#
# Bugs Everywhere 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.
#
# Bugs Everywhere 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
# Bugs Everywhere. If not, see <http://www.gnu.org/licenses/>.
import libbe
import libbe.command
import libbe.command.util
from .assign import parse_assigned as _parse_assigned
class New (libbe.command.Command):
"""Create a new bug
>>> import os
>>> import sys
>>> import time
>>> import libbe.bugdir
>>> import libbe.util.id
>>> bd = libbe.bugdir.SimpleBugDir(memory=False)
>>> io = libbe.command.StringInputOutput()
>>> io.stdout = sys.stdout
>>> ui = libbe.command.UserInterface(io=io)
>>> ui.storage_callbacks.set_storage(bd.storage)
>>> cmd = New()
>>> uuid_gen = libbe.util.id.uuid_gen
>>> libbe.util.id.uuid_gen = lambda: 'X'
>>> ui._user_id = u'Fran\\xe7ois'
>>> options = {'assigned': 'none'}
>>> ret = ui.run(cmd, options=options, args=['this is a test',])
Created bug with ID abc/X
>>> libbe.util.id.uuid_gen = uuid_gen
>>> bd.flush_reload()
>>> bug = bd.bug_from_uuid('X')
>>> print bug.summary
this is a test
>>> bug.creator
u'Fran\\xe7ois'
>>> bug.reporter
u'Fran\\xe7ois'
>>> bug.time <= int(time.time())
True
>>> print bug.severity
minor
>>> print bug.status
open
>>> print bug.assigned
None
>>> ui.cleanup()
>>> bd.cleanup()
"""
name = 'new'
def __init__(self, *args, **kwargs):
libbe.command.Command.__init__(self, *args, **kwargs)
self.options.extend([
libbe.command.Option(name='reporter', short_name='r',
help='The user who reported the bug',
arg=libbe.command.Argument(
name='reporter', metavar='NAME')),
libbe.command.Option(name='creator', short_name='c',
help='The user who created the bug',
arg=libbe.command.Argument(
name='creator', metavar='NAME')),
libbe.command.Option(name='assigned', short_name='a',
help='The developer in charge of the bug',
arg=libbe.command.Argument(
name='assigned', metavar='NAME',
completion_callback=libbe.command.util.complete_assigned)),
libbe.command.Option(name='status', short_name='t',
help='The bug\'s status level',
arg=libbe.command.Argument(
name='status', metavar='STATUS',
completion_callback=libbe.command.util.complete_status)),
libbe.command.Option(name='severity', short_name='s',
help='The bug\'s severity',
arg=libbe.command.Argument(
name='severity', metavar='SEVERITY',
completion_callback=libbe.command.util.complete_severity)),
libbe.command.Option(name='bugdir', short_name='b',
help='Short bugdir UUID for the new bug. You '
'only need to set this if you have multiple bugdirs in '
'your repository.',
arg=libbe.command.Argument(
name='bugdir', metavar='ID', default=None,
completion_callback=libbe.command.util.complete_bugdir_id)),
libbe.command.Option(name='full-uuid', short_name='f',
help='Print the full UUID for the new bug')
])
self.args.extend([
libbe.command.Argument(name='summary', metavar='SUMMARY')
])
def _run(self, **params):
if params['summary'] == '-': # read summary from stdin
summary = self.stdin.readline()
else:
summary = params['summary']
storage = self._get_storage()
bugdirs = self._get_bugdirs()
if params['bugdir']:
bugdir = bugdirs[params['bugdir']]
elif len(bugdirs) == 1:
bugdir = bugdirs.values()[0]
else:
raise libbe.command.UserError(
'Ambiguous bugdir {}'.format(sorted(bugdirs.values())))
storage.writeable = False
bug = bugdir.new_bug(summary=summary.strip())
if params['creator'] != None:
bug.creator = params['creator']
else:
bug.creator = self._get_user_id()
if params['reporter'] != None:
bug.reporter = params['reporter']
else:
bug.reporter = bug.creator
if params['assigned'] != None:
bug.assigned = _parse_assigned(self, params['assigned'])
if params['status'] != None:
bug.status = params['status']
if params['severity'] != None:
bug.severity = params['severity']
storage.writeable = True
bug.save()
if params['full-uuid']:
bug_id = bug.id.long_user()
else:
bug_id = bug.id.user()
self.stdout.write('Created bug with ID %s\n' % (bug_id))
return 0
def _long_help(self):
return """
Create a new bug, with a new ID. The summary specified on the
commandline is a string (only one line) that describes the bug briefly
or "-", in which case the string will be read from stdin.
"""
|
UTF-8
|
Python
| false | false | 2,013 |
10,668,698,799,000 |
f9af81fc8c39ecfbc68a0018723f4e96cef4d936
|
ecd8d7751efb9d4e603c4d3422c06dd511c47213
|
/chapters/kirby-4/src/lin_rel.py
|
553cf207d45d8992b570d7115bc5b80dabc9dd93
|
[] |
no_license
|
FEniCS/fenics-book
|
https://github.com/FEniCS/fenics-book
|
b0bf5e786fc24330dd6a5cadbedfa3b319650526
|
7d3a80e7dda0fc279c7964dc6000d57942f11eb3
|
refs/heads/master
| 2016-08-07T16:22:48.481060 | 2013-04-30T12:05:31 | 2013-04-30T12:05:31 | 9,391,921 | 3 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
from scipy.linalg import det, svd
from math import sqrt
from itertools import combinations
eps = 1e-9
A0 = np.array([[3,0,0,0],
[0,-1,0,0],
[1,1,0,0],
[-4,-4,0,0],
[0,4,0,0],
[0,0,0,0],
[0,0,-1,0],
[0,0,0,3],
[0,0,1,1],
[0,0,0,0],
[0,0,4,0],
[0,0,-4,-4],
[1,0,1,0],
[0,1,0,1],
[3,3,3,3],
[-4,0,-4,0],
[0,0,0,0],
[0,-4,0,-4],
[-4,0,-4,0],
[0,0,0,0],
[-4,-4,0,0],
[8,4,4,8],
[0,-4,-4,-8],
[0,4,4,0],
[0,0,4,0],
[0,4,0,0],
[0,0,0,0],
[0,-4,-4,-8],
[8,4,4,8],
[-8,-4,-4,0],
[0,0,0,0],
[0,-4,0,-4],
[0,0,-4,-4],
[0,4,0,4],
[-8,-4,-4,0],
[8,4,4,8]])
A0 = np.array([[1, 1, 0, 0],
[-4, -4, 0, 0],
[0, 0, 1, 1],
[3, 3, 3, 3],
[0, 4, 4, 0],
[8, 4, 4, 8],
[0,-4,-4,-8],
[-8,-4,-4,0],
[0,0,0,0],
[8,4,4,8]])
def randproj( m , n ):
"""creates a random matrix in R^{m,n}"""
# maps from R^n to R^m
if m >= n:
A = np.random.rand( m , n )
[u,s,vt] = svd(A, full_matrices=False)
return u
else:
A = np.random.rand( n , m )
[u,s,vt] = svd(A, full_matrices=False)
return np.transpose(u)
def normalize_sign( u ):
"""Returns u or -u such that the first nonzero entry (up to eps)
is positive"""
for ui in u:
if abs(ui) > eps:
if ui < 0.0:
return -u
else:
return u
return u
def normalize(u):
mau = max(abs(u))
if mau < eps:
raise RuntimeError, "barf: divide by zero"
return normalize_sign( u / mau )
def check_lin(x, y):
return np.allclose(normalize(x),normalize(y))
def strike_col( A , j ):
m,n = A.shape
return np.take( A , [ k for k in range(0,n) if k != j ] , 1 )
def proj_cross( vecs ):
n,d = len( vecs ) , len( vecs[ 0 ] )
udude = randproj(n,3)
pi_
mat = np.array( vecs )
if n != d - 1:
for v in vecs:
print v
raise RuntimeError, "barf"
# normalize the cross product to have unit value to avoid
# rounding to zero in the cross product routine.
foo = np.array( \
[ (-1)**i * det(strike_col(mat,i)) for i in range( d ) ] )
foo /= max( abs( foo ) )
return normalize( foo )
def compare( u , v ):
"""Lexicographic ordering that respects floating-point
fuzziness"""
if len(u) != len(v):
raise RuntimeError, "can't compare"
diff = u-v
for d in diff:
if abs(d) > eps:
if d < 0:
return -1
else:
return 1
return 0
def process(vecs):
n = len(vecs)
d = len(vecs[0])
idx = set(range(n))
z = np.zeros(d)
zidx = [i for i in xrange(n) \
if np.allclose(vecs[i], z)]
idx -= set(zidx)
print "zeros:", zidx
l = [(i,normalize(vecs[i])) for i in idx]
l.sort(lambda x,y: compare(x[1], y[1]))
lidx = set()
for i in xrange(len(l) - 1):
# print l[i]
if np.allclose(l[i][1], l[i+1][1]):
lidx.add(l[i+1][0])
idx -= set(lidx)
print "lines:", lidx
p = []
udude = randproj(3,d)
pi_vecs = [(i, np.dot(udude,A0[i])) for i in idx]
for c1, c2 in combinations(xrange(len(pi_vecs)), 2):
idx1, vec1 = pi_vecs[c1]
idx2, vec2 = pi_vecs[c2]
p.append((idx1, idx2, normalize(np.cross(vec1, vec2))))
p.sort(lambda x, y: compare(x[2], x[2]))
# print p
curr_pidx = 0
curr_plane = p[0][2]
pidx = {curr_pidx:set([p[0][0], p[0][1]])}
# print 0, curr_pidx, p[0]
for i in xrange(1, len(p) - 1):
# print i, curr_pidx, p[i]
if np.allclose(p[i][2], curr_plane):
pidx[curr_pidx].add(p[i][0])
pidx[curr_pidx].add(p[i][1])
else:
curr_pidx += 1
pidx[curr_pidx] = set([p[i][0], p[i][1]])
curr_plane = p[i][2]
real_pidx = []
for a in pidx.keys():
if len(pidx[a]) > 2:
real_pidx.append(pidx[a])
print "planes:", real_pidx
if __name__ == "__main__":
process(A0)
|
UTF-8
|
Python
| false | false | 2,013 |
85,899,393,741 |
1ce66469e9bac969623256cb1b4245162daee2e9
|
2795cdfc9adcf53fac917ed1e9fad4826cfa26d3
|
/NLP/spel/src/test_spel.py
|
9970d5710ffca2c8c0b74f871a00492296ecf3bc
|
[] |
no_license
|
tehf0x/gabe-and-joh
|
https://github.com/tehf0x/gabe-and-joh
|
cd0416fa53604d110c5ced1910826d2232ba5d87
|
ae5e54713648e32d5a8498fc3e7f6e94cddb1b6d
|
refs/heads/master
| 2016-08-05T23:40:25.470756 | 2009-11-25T11:51:29 | 2009-11-25T11:51:29 | 279,753 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
Test cases for Spel
Created on 10 Sep 2009
@author: Johannes H. Jensen <[email protected]>
"""
from spellcheck import Spellcheck
from dictionary import Dictionary
# spell-errors.txt contains common spelling mistakes
# each line is in the format:
# <correct>: <wrong1> [wrong2] ...
fh = open('spell-errors.txt')
n_right = 0
n_unknown = 0
n_wrong = 0
n_total = 0
dictionary = Dictionary()
for line in fh:
right, wrongs = line.split(':')
wrongs = [w.strip() for w in wrongs.split(',')]
print right + ':'
for wrong in wrongs:
if dictionary.has_word(wrong.lower()):
continue
n_total += 1
sc = Spellcheck(wrong)
guess = sc.corrected()[0][0]
print '\t%s => %s\t' % (wrong, guess),
if guess == right:
print 'CORRECT!'
n_right += 1
elif guess == wrong:
print 'UNKNOWN'
n_unknown += 1
else:
n_wrong += 1
print 'WRONG'
print 'RESULTS:'
print '%d words checked' % (n_total)
print '%d right (%.2f)' % (n_right, 100 * float(n_right) / float(n_total))
print '%d wrong (%.2f)' % (n_wrong, 100 * float(n_wrong) / float(n_total))
print '%d unknown (%.2f)' % (n_unknown, 100 * float(n_unknown) / float(n_total))
|
UTF-8
|
Python
| false | false | 2,009 |
15,229,954,041,934 |
bf5f0238048153e24f4f2365d5a0bce266e2f163
|
c4fe6a42f979af4740ac8cda953c19a5876f20b1
|
/example/display.py
|
b2893b5525a22a1545f69054289367d17b0a8446
|
[] |
no_license
|
HyperSuprime-Cam/distEst
|
https://github.com/HyperSuprime-Cam/distEst
|
3baa3c37cd2a623ea8a56a2d7b4f7eed2a1202f1
|
eea7699e91c4db0e549384cfedcb3e7fc9fbd490
|
refs/heads/master
| 2020-06-05T11:22:16.422808 | 2014-06-27T18:08:22 | 2014-06-27T18:08:22 | 16,705,545 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#
# LSST Data Management System
# Copyright 2008, 2009, 2010 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
# see <http://www.lsstcorp.org/LegalNotices/>.
#
import math
import numpy
import matplotlib.pyplot as plt
import lsst.afw.cameraGeom as cameraGeom
import lsst.afw.geom as afwGeom
import lsst.obs.hscSim as hscSim
import lsst.pipette.config as pipConfig
import lsst.pipette.distortion as pipDist
SAMPLE = 100
def main(camera, distortionConfig):
fig = plt.figure(1)
fig.clf()
ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
# ax.set_autoscale_on(False)
# ax.set_ybound(lower=-0.2, upper=0.2)
# ax.set_xbound(lower=-17, upper=-7)
ax.set_title('Distorted CCDs')
for raft in camera:
raft = cameraGeom.cast_Raft(raft)
for ccd in raft:
ccd = cameraGeom.cast_Ccd(ccd)
size = ccd.getSize()
width, height = 2048, 4096
dist = pipDist.createDistortion(ccd, distortionConfig)
corners = ((0.0,0.0), (0.0, height), (width, height), (width, 0.0), (0.0, 0.0))
for (x0, y0), (x1, y1) in zip(corners[0:4],corners[1:5]):
if x0 == x1 and y0 != y1:
yList = numpy.linspace(y0, y1, num=SAMPLE)
xList = [x0] * len(yList)
elif y0 == y1 and x0 != x1:
xList = numpy.linspace(x0, x1, num=SAMPLE)
yList = [y0] * len(xList)
else:
raise RuntimeError("Should never get here")
xDistort = []; yDistort = []
for x, y in zip(xList, yList):
distorted = dist.actualToIdeal(afwGeom.Point2D(x, y))
xDistort.append(distorted.getX())
yDistort.append(distorted.getY())
ax.plot(xDistort, yDistort, 'k-')
plt.show()
if __name__ == '__main__':
camera = hscSim.HscSimMapper().camera
config = pipConfig.Config()
config['class'] = "hsc.meas.match.hscDistortion.HscDistortion"
main(camera, config)
|
UTF-8
|
Python
| false | false | 2,014 |
15,444,702,399,185 |
931d54532b99940a33861462a65376abf496e71f
|
e7e453268dc74c74a54c85d35a1f9b254298b9a2
|
/sage/homology/chain_complex_morphism.py
|
46e7caa0500d1acbcb202c00e67465bbdec62f48
|
[] |
no_license
|
pombredanne/sage-1
|
https://github.com/pombredanne/sage-1
|
4128172b20099dfcdaa9792a61945e97537501bd
|
4262d856b92f9e1772d71f993baa6aecbbd87a87
|
refs/heads/master
| 2018-03-04T20:07:27.273680 | 2013-03-22T02:31:54 | 2013-03-22T02:31:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
r"""
Morphisms of chain complexes
AUTHORS:
- Benjamin Antieau <[email protected]> (2009.06)
- Travis Scrimshaw (2012-08-18): Made all simplicial complexes immutable to
work with the homset cache.
This module implements morphisms of chain complexes. The input is a dictionary
whose keys are in the grading group of the chain complex and whose values are
matrix morphisms.
EXAMPLES::
from sage.matrix.constructor import zero_matrix
sage: S = simplicial_complexes.Sphere(1)
sage: S
Simplicial complex with vertex set (0, 1, 2) and facets {(1, 2), (0, 2), (0, 1)}
sage: C = S.chain_complex()
sage: C.differential()
{0: [], 1: [ 1 1 0]
[ 0 -1 -1]
[-1 0 1]}
sage: f = {0:zero_matrix(ZZ,3,3),1:zero_matrix(ZZ,3,3)}
sage: G = Hom(C,C)
sage: x = G(f)
sage: x
Chain complex morphism from Chain complex with at most 2 nonzero terms over Integer Ring to Chain complex with at most 2 nonzero terms over Integer Ring
sage: x._matrix_dictionary
{0: [0 0 0]
[0 0 0]
[0 0 0], 1: [0 0 0]
[0 0 0]
[0 0 0]}
"""
#*****************************************************************************
# Copyright (C) 2009 D. Benjamin Antieau <[email protected]>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code 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; the full text
# is available at:
#
# http://www.gnu.org/licenses/
#
#*****************************************************************************
import sage.matrix.all as matrix
from sage.structure.sage_object import SageObject
from sage.rings.integer_ring import ZZ
def is_ChainComplexMorphism(x):
"""
Returns ``True`` if and only if ``x`` is a chain complex morphism.
EXAMPLES::
sage: from sage.homology.chain_complex_morphism import is_ChainComplexMorphism
sage: S = simplicial_complexes.Sphere(14)
sage: H = Hom(S,S)
sage: i = H.identity() # long time (8s on sage.math, 2011)
sage: S = simplicial_complexes.Sphere(6)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: x # indirect doctest
Chain complex morphism from Chain complex with at most 7 nonzero terms over Integer Ring to Chain complex with at most 7 nonzero terms over Integer Ring
sage: is_ChainComplexMorphism(x)
True
"""
return isinstance(x,ChainComplexMorphism)
class ChainComplexMorphism(SageObject):
"""
An element of this class is a morphism of chain complexes.
"""
def __init__(self,matrices,C,D):
"""
Create a morphism from a dictionary of matrices.
EXAMPLES::
from sage.matrix.constructor import zero_matrix
sage: S = simplicial_complexes.Sphere(1)
sage: S
Simplicial complex with vertex set (0, 1, 2) and facets {(1, 2), (0, 2), (0, 1)}
sage: C = S.chain_complex()
sage: C.differential()
{0: [], 1: [ 1 1 0]
[ 0 -1 -1]
[-1 0 1]}
sage: f = {0:zero_matrix(ZZ,3,3),1:zero_matrix(ZZ,3,3)}
sage: G = Hom(C,C)
sage: x = G(f)
sage: x
Chain complex morphism from Chain complex with at most 2 nonzero terms over Integer Ring to Chain complex with at most 2 nonzero terms over Integer Ring
sage: x._matrix_dictionary
{0: [0 0 0]
[0 0 0]
[0 0 0], 1: [0 0 0]
[0 0 0]
[0 0 0]}
Check that the bug in :trac:`13220` has been fixed::
sage: X = simplicial_complexes.Simplex(1)
sage: Y = simplicial_complexes.Simplex(0)
sage: g = Hom(X,Y)({0:0, 1:0})
sage: g.associated_chain_complex_morphism()
Chain complex morphism from Chain complex with at most 2 nonzero terms over Integer Ring to Chain complex with at most 1 nonzero terms over Integer Ring
"""
if C._grading_group != ZZ:
raise NotImplementedError, "Chain complex morphisms are not implemented over gradings other than ZZ."
d = C._degree
if d != D._degree:
raise ValueError, "Chain complex morphisms are not defined for chain complexes of different degrees."
if d != -1 and d != 1:
raise NotImplementedError, "Chain complex morphisms are not implemented for degrees besides -1 and 1."
dim_min = min(min(C.differential().keys()),min(D.differential().keys()))
dim_max = max(max(C.differential().keys()),max(D.differential().keys()))
if not C.base_ring()==D.base_ring():
raise NotImplementedError, "Chain complex morphisms between chain complexes of different base rings are not implemented."
for i in range(dim_min,dim_max):
try:
matrices[i]
except KeyError:
matrices[i] = matrix.zero_matrix(C.base_ring(),D.differential()[i].ncols(),C.differential()[i].ncols(),sparse=True)
try:
matrices[i+1]
except KeyError:
matrices[i+1] = matrix.zero_matrix(C.base_ring(),D.differential()[i+1].ncols(),C.differential()[i+1].ncols(),sparse=True)
if d==-1:
if (i+1) in C.differential().keys() and (i+1) in D.differential().keys():
if not matrices[i]*C.differential()[i+1]==D.differential()[i+1]*matrices[i+1]:
raise ValueError, "Matrices must define a chain complex morphism."
elif (i+1) in C.differential().keys():
if not (matrices[i]*C.differential()[i+1]).is_zero():
raise ValueError, "Matrices must define a chain complex morphism."
elif (i+1) in D.differential().keys():
if not (D.differential()[i+1]*matrices[i+1]).is_zero():
raise ValueError, "Matrices must define a chain complex morphism."
else:
if i in C.differential().keys() and i in D.differential().keys():
if not matrices[i+1]*C.differential()[i]==D.differential()[i]*matrices[i]:
raise ValueError, "Matrices must define a chain complex morphism."
elif i in C.differential().keys():
if not (matrices[i+1]*C.differential()[i]).is_zero():
raise ValueError, "Matrices must define a chain complex morphism."
elif i in D.differential().keys():
if not (D.differential()[i]*matrices[i]).is_zero():
raise ValueError, "Matrices must define a chain complex morphism."
self._matrix_dictionary = matrices
self._domain = C
self._codomain = D
def __neg__(self):
"""
Returns ``-x``.
EXAMPLES::
sage: S = simplicial_complexes.Sphere(2)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: w = -x
sage: w._matrix_dictionary
{0: [-1 0 0 0]
[ 0 -1 0 0]
[ 0 0 -1 0]
[ 0 0 0 -1],
1: [-1 0 0 0 0 0]
[ 0 -1 0 0 0 0]
[ 0 0 -1 0 0 0]
[ 0 0 0 -1 0 0]
[ 0 0 0 0 -1 0]
[ 0 0 0 0 0 -1],
2: [-1 0 0 0]
[ 0 -1 0 0]
[ 0 0 -1 0]
[ 0 0 0 -1]}
"""
f = dict()
for i in self._matrix_dictionary.keys():
f[i] = -self._matrix_dictionary[i]
return ChainComplexMorphism(f,self._domain,self._codomain)
def __add__(self,x):
"""
Returns ``self + x``.
EXAMPLES::
sage: S = simplicial_complexes.Sphere(2)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: z = x+x
sage: z._matrix_dictionary
{0: [2 0 0 0]
[0 2 0 0]
[0 0 2 0]
[0 0 0 2],
1: [2 0 0 0 0 0]
[0 2 0 0 0 0]
[0 0 2 0 0 0]
[0 0 0 2 0 0]
[0 0 0 0 2 0]
[0 0 0 0 0 2],
2: [2 0 0 0]
[0 2 0 0]
[0 0 2 0]
[0 0 0 2]}
"""
if not isinstance(x,ChainComplexMorphism) or self._codomain != x._codomain or self._domain != x._domain or self._matrix_dictionary.keys() != x._matrix_dictionary.keys():
raise TypeError, "Unsupported operation."
f = dict()
for i in self._matrix_dictionary.keys():
f[i] = self._matrix_dictionary[i] + x._matrix_dictionary[i]
return ChainComplexMorphism(f,self._domain,self._codomain)
def __mul__(self,x):
"""
Returns ``self * x`` if ``self`` and ``x`` are composable morphisms
or if ``x`` is an element of the base ring.
EXAMPLES::
sage: S = simplicial_complexes.Sphere(2)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: y = x*2
sage: y._matrix_dictionary
{0: [2 0 0 0]
[0 2 0 0]
[0 0 2 0]
[0 0 0 2],
1: [2 0 0 0 0 0]
[0 2 0 0 0 0]
[0 0 2 0 0 0]
[0 0 0 2 0 0]
[0 0 0 0 2 0]
[0 0 0 0 0 2],
2: [2 0 0 0]
[0 2 0 0]
[0 0 2 0]
[0 0 0 2]}
sage: z = y*y
sage: z._matrix_dictionary
{0: [4 0 0 0]
[0 4 0 0]
[0 0 4 0]
[0 0 0 4],
1: [4 0 0 0 0 0]
[0 4 0 0 0 0]
[0 0 4 0 0 0]
[0 0 0 4 0 0]
[0 0 0 0 4 0]
[0 0 0 0 0 4],
2: [4 0 0 0]
[0 4 0 0]
[0 0 4 0]
[0 0 0 4]}
"""
if not isinstance(x,ChainComplexMorphism) or self._codomain != x._domain:
try:
y = self._domain.base_ring()(x)
except TypeError:
raise TypeError, "Multiplication is not defined."
f = dict()
for i in self._matrix_dictionary.keys():
f[i] = self._matrix_dictionary[i] * y
return ChainComplexMorphism(f,self._domain,self._codomain)
f = dict()
for i in self._matrix_dictionary.keys():
f[i] = x._matrix_dictionary[i]*self._matrix_dictionary[i]
return ChainComplexMorphism(f,self._domain,x._codomain)
def __rmul__(self,x):
"""
Returns ``x * self`` if ``x`` is an element of the base ring.
EXAMPLES::
sage: S = simplicial_complexes.Sphere(2)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: 2*x == x*2
True
sage: 3*x == x*2
False
"""
try:
y = self._domain.base_ring()(x)
except TypeError:
raise TypeError, "Multiplication is not defined."
f = dict()
for i in self._matrix_dictionary.keys():
f[i] = y * self._matrix_dictionary[i]
return ChainComplexMorphism(f,self._domain,self._codomain)
def __sub__(self,x):
"""
Returns ``self - x``.
EXAMPLES::
sage: S = simplicial_complexes.Sphere(2)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: y = x-x
sage: y._matrix_dictionary
{0: [0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0],
1: [0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0],
2: [0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]}
"""
return self + (-x)
def __eq__(self,x):
"""
Returns ``True`` if and only if ``self == x``.
EXAMPLES::
sage: S = SimplicialComplex(is_mutable=False)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: x
Chain complex morphism from Chain complex with at most 0 nonzero terms over Integer Ring to Chain complex with at most 0 nonzero terms over Integer Ring
sage: f = x._matrix_dictionary
sage: C = S.chain_complex()
sage: G = Hom(C,C)
sage: y = G(f)
sage: x == y
True
"""
if not isinstance(x,ChainComplexMorphism) or self._codomain != x._codomain or self._domain != x._domain or self._matrix_dictionary != x._matrix_dictionary:
return False
else:
return True
def _repr_(self):
"""
Returns the string representation of ``self``.
EXAMPLES::
sage: S = SimplicialComplex(is_mutable=False)
sage: H = Hom(S,S)
sage: i = H.identity()
sage: x = i.associated_chain_complex_morphism()
sage: x
Chain complex morphism from Chain complex with at most 0 nonzero terms over Integer Ring to Chain complex with at most 0 nonzero terms over Integer Ring
sage: x._repr_()
'Chain complex morphism from Chain complex with at most 0 nonzero terms over Integer Ring to Chain complex with at most 0 nonzero terms over Integer Ring'
"""
return "Chain complex morphism from " + self._domain._repr_() + " to " + self._codomain._repr_()
|
UTF-8
|
Python
| false | false | 2,013 |
13,718,125,544,664 |
5ba8f9073d94a48dc72e2ad45fa6221633165c1d
|
adfac8d0ea5b2cae2b838408c69b18c7a4d14874
|
/csv_conv2.py
|
be381fdeac0e24d989dbdfaf479e8634188e3f40
|
[] |
no_license
|
dartydevil/YRS-FOC-2014
|
https://github.com/dartydevil/YRS-FOC-2014
|
25f042f4eb2bb19bbfe5e3b9cc45000520c7324a
|
2b8a9a50157b11cfa4c44e81787e9dd7b3d688da
|
refs/heads/master
| 2021-01-15T20:08:42.270353 | 2014-09-23T19:28:39 | 2014-09-23T19:28:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import csv
import json
csv_file = open("data/gov-spend-2012.csv")
json_file = open("data/gov-spend-2012.json", "w")
reader = csv.DictReader(csv_file)
json_data = {"comment": "Values are measured in billions of pounds"}
for row in reader:
json_data[row["UK SPENDING 2011-12"]] = row["a"]
json.dump(json_data, json_file, indent=4)
csv_file.close()
json_file.close()
|
UTF-8
|
Python
| false | false | 2,014 |
13,709,535,639,075 |
e68e8da78d63f40ada10bbb521eed2088bbaf189
|
5017c2c81008642c84181aab6c4dfcd476afd7ad
|
/Arithmetic.py
|
74e9dacc84eeb0980d9a2baf323e5b6a8c399179
|
[] |
no_license
|
Callulis/BasicPython
|
https://github.com/Callulis/BasicPython
|
a7e44bf65f5c2718be2b66c194e75d728b318576
|
4ab78326a9d63bbdc8585c5a6cd4d9d0e46917cb
|
refs/heads/master
| 2021-01-10T19:38:31.369430 | 2014-05-09T16:41:00 | 2014-05-09T16:41:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Chris Allulis
# What does this program do?
def main():
num1 = 9
num2 = 3
print num1 + num2
print num1 - num2
print num1 * num2
print num1 / num2
print num1 // num2
print num1 % num2
print num1 ** num2
num3 = 3
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,014 |
10,282,151,747,327 |
5d745980fee4cda9f95ba13483bccf8885b9aeba
|
9e5dbf7f46aea863c27365b55d87ac60cbbcfd24
|
/src/cron.py
|
02c191144fa82fa8a7baab1c3374c74b95647c1e
|
[] |
no_license
|
mdargan/weather
|
https://github.com/mdargan/weather
|
d50094c860856049c22d915c1384d732e4579471
|
bdf7bbb2d91dfdbd80753fca3904fad28690237a
|
refs/heads/master
| 2020-04-15T22:47:51.022077 | 2014-09-01T03:16:51 | 2014-09-01T03:16:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os
import json
import datetime
import time
from urllib.request import urlopen
from paste.deploy import appconfig
from sqlalchemy import engine_from_config, func
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
#Import sqlalchemy objects
from models import DBSession as db, City, WeatherRecord
#import the session manager. This way commits will be handled automatically by the Zope Transaction Manager
import transaction
# Load Application Configuration and Return as Dictionary
conf = appconfig('config:' + '../development.ini',
name="main", relative_to=os.getcwd())
#configure SQLAlchemy engine
engine = engine_from_config(conf, 'sqlalchemy.')
db.configure(bind=engine)
def update_weather_data(city_id, start_dt):
timestamp = time.mktime(start_dt.timetuple())
api_url = 'http://api.openweathermap.org/data/2.5/history/city?id=%d&type=day&start=%d' % (city_id, timestamp)
response = urlopen(api_url)
data = json.loads(response.read().decode())
conditions = { }
for d in data['list']:
dt = datetime.datetime.fromtimestamp(int(d['dt'])).date()
cond = d['weather'][0]['main']
conditions.setdefault(dt, []).append(cond)
with transaction.manager:
for k in conditions:
cds = set(conditions[k])
is_clear = len(cds) == 1 and 'Clear' in cds
record = WeatherRecord(date=k, is_clear=is_clear)
db.add(record)
count = db.query(func.count(WeatherRecord.id)).first()[0]
start_date = datetime.date.today()
if count == 0:
#We assume we running first time since database is empty
#and will load all records for last year
start_date = start_date - datetime.timedelta(days=365)
else:
#Perform incremental update from latest record
latest = db.query(WeatherRecord).order_by(WeatherRecord.date).first()
start_date = latest.date
cities = db.query(City).all()
for c in cities:
update_weather_data(c.owm_id, start_date)
|
UTF-8
|
Python
| false | false | 2,014 |
1,889,785,637,862 |
61a17194f000af95e5d7c084939243857f64df6c
|
25fc976a7b56ca45602c327efb96bc8c75a729b3
|
/hexapod/hexapodController.py
|
fd4448c7c78358449d22f8bde7320326585f54e7
|
[] |
no_license
|
henryeherman/BulletXcodeDemos
|
https://github.com/henryeherman/BulletXcodeDemos
|
75c86243a570e17adcf9403d82624a43836c2f84
|
b25b6c1055a8fa136a3c7770c6017e819cd7b6bb
|
refs/heads/master
| 2021-01-25T11:58:06.864189 | 2012-06-25T06:57:57 | 2012-06-25T06:57:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#
# Hexapod Controller
# Connects REQ socket to tcp://localhost:5555
#
import zmq
import msgpack
from ctypes import *
NUMLEGS = 6
class HpodCtrlParams(Structure):
_fields_ = [("kneeAngles", c_float*NUMLEGS),
("hipAnglesX", c_float*NUMLEGS),
("hipAnglesY", c_float*NUMLEGS),
("hipStrength", c_float),
("kneeStrength", c_float),
("dtKnee", c_float),
("dtHip", c_float)
]
def toString(self):
return buffer(self)[:]
def main():
context = zmq.Context()
# Socket to talk to server
socket = context.socket(zmq.REQ)
socket.connect ("tcp://localhost:5555")
params = HpodCtrlParams()
for i in range(6):
params.kneeAngles[i] = 0
params.hipAnglesY[i] = -1
params.hipAnglesX[0] = 2
params.hipAnglesX[1] = 0
params.hipAnglesX[2] = 2
params.hipAnglesX[3] = 0
params.hipAnglesX[4] = 2
params.hipAnglesX[5] = 0
params.hipStrength = 40
params.kneeStrength = 40
params.dtKnee = 4
params.dtHip = 4
send_string = params.toString()
# send_string = format_string(params)
socket.send(send_string)
message = socket.recv()
print "Received reply: " + message
if __name__ == "__main__":
main()
|
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.