<commit_before># -*- coding: utf-8 -*-

#...............................licence...........................................
#
#     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
#     S.A.Unipersonal (Telefonica I+D)
#
#     This file is part of Morfeo EzWeb Platform.
#
#     Morfeo EzWeb Platform is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
#
#     Morfeo EzWeb Platform is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.
#
#     You should have received a copy of the GNU Affero General Public License
#     along with Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
#
#     Info about members and contributors of the MORFEO project
#     is available at
#
#     http://morfeo-project.org
#
#...............................licence...........................................#

#

from os import path
from django.conf.urls.defaults import patterns, include
from django.conf import settings

from django.contrib import admin
admin.autodiscover()

from catalogue.views import ResourceEnabler

#from clms import admin_view as clms_admin_view
#from clms.admin import clms_site, setup_admin
#setup_admin(clms_site)

#JavaScript translation
js_info_dict = {
    'packages': ('ezweb', )
}

urlpatterns = patterns('',
    # Static content
     (r'^ezweb/(.*)$', 'django.views.static.serve', {'document_root': path.join(settings.BASEDIR, 'media')}),

    # EzWeb
    (r'^', include('ezweb.urls')),
    (r'^user/(?P<user_name>[\s\-\.\w]+)/$', include('ezweb.urls')),

    # Gadgets
    (r'^user/(?P<user_name>[\s\-\.\w]+)/gadget(s)?', include('gadget.urls')),
    (r'^gadget(s)?', include('gadget.urls')),

    # WorkSpaces
    (r'^workspace(s)?', include('workspace.urls')),

    # Contract Manager
    (r'^contract(s)?', include('resourceSubscription.urls')),

    # Remote Channel Manager
    (r'^channel(s)?/external', include('remoteChannel.urls')),

    # IGadgets
    (r'^workspace(s)?/(?P<workspace_id>\d+)/tab(s)?/(?P<tab_id>\d+)/igadget(s)?', include('igadget.urls')),

    # Connectables
    (r'^workspace(s)?/(?P<workspace_id>\d+)/connectable(s)?', include('connectable.urls')),

    # context
    (r'^user/(?P<user_name>[\s\-\.\w]+)/context(s)?', include('context.urls')),

    # Platform Preferences
    (r'^user/(?P<user_name>[_\w]+)/preference(s)?', include('preferences.urls')),

    # Catalogue Resource
    (r'^user/(?P<user_name>[\s\-\.\w]+)/catalogue/', include('catalogue.urls')),

    # Catalogue: Changing certification status
    (r'^catalogue/resource/(?P<resource_id>\d+)/activation$', ResourceEnabler(permitted_methods=('GET',))),

    #GadgetGenerator
    (r'^gadgetGenerator', include('gadgetGenerator.urls')),

    # Proxy
    (r'^proxy', include('proxy.urls')),

    # CLMS
    #(r'^clms/', include('clms.urls')),

    # Django contrib
    #(r'^registration/login_form/$', 'registration.views.login_form'),
    (r'^accounts/login/$', 'django.contrib.auth.views.login'),
 #   (r'^logout$', 'django.contrib.auth.views.logout'),
    # custom logouts (to enable anonymous access)
    (r'^logout$', 'authentication.logout'),
    (r'^admin/logout/$', 'authentication.logout'),

    #Admin CLMS interface
    #(r'^admin/clms/(?P<layout_id>\d+)/content/popup/', clms_admin_view.panel_list_popup),
    #(r'^admin/clms/content/popup/', clms_admin_view.panel_list_popup),
    #(r'^admin/clms/content/filter/', clms_admin_view.contents_filter),
    #(r'^admin/clms/(?P<url>.*)', clms_site.root),

    #Admin interface
    (r'^admin/(.*)', admin.site.root),

    # Django "set language" (internacionalitation)
    (r'^i18n/', include('django.conf.urls.i18n')),

    # Django JavaScript Internacionalitation
    (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),

)

handler404 = "django.views.defaults.page_not_found"
handler500 = "django.views.defaults.server_error"
<commit_msg>Fixes #529. Correct regular expression for usernames in preferences URL<commit_after># -*- coding: utf-8 -*-

#...............................licence...........................................
#
#     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
#     S.A.Unipersonal (Telefonica I+D)
#
#     This file is part of Morfeo EzWeb Platform.
#
#     Morfeo EzWeb Platform is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
#
#     Morfeo EzWeb Platform is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.
#
#     You should have received a copy of the GNU Affero General Public License
#     along with Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
#
#     Info about members and contributors of the MORFEO project
#     is available at
#
#     http://morfeo-project.org
#
#...............................licence...........................................#

#

from os import path
from django.conf.urls.defaults import patterns, include
from django.conf import settings

from django.contrib import admin
admin.autodiscover()

from catalogue.views import ResourceEnabler

#from clms import admin_view as clms_admin_view
#from clms.admin import clms_site, setup_admin
#setup_admin(clms_site)

#JavaScript translation
js_info_dict = {
    'packages': ('ezweb', )
}

urlpatterns = patterns('',
    # Static content
     (r'^ezweb/(.*)$', 'django.views.static.serve', {'document_root': path.join(settings.BASEDIR, 'media')}),

    # EzWeb
    (r'^', include('ezweb.urls')),
    (r'^user/(?P<user_name>[\s\-\.\w]+)/$', include('ezweb.urls')),

    # Gadgets
    (r'^user/(?P<user_name>[\s\-\.\w]+)/gadget(s)?', include('gadget.urls')),
    (r'^gadget(s)?', include('gadget.urls')),

    # WorkSpaces
    (r'^workspace(s)?', include('workspace.urls')),

    # Contract Manager
    (r'^contract(s)?', include('resourceSubscription.urls')),

    # Remote Channel Manager
    (r'^channel(s)?/external', include('remoteChannel.urls')),

    # IGadgets
    (r'^workspace(s)?/(?P<workspace_id>\d+)/tab(s)?/(?P<tab_id>\d+)/igadget(s)?', include('igadget.urls')),

    # Connectables
    (r'^workspace(s)?/(?P<workspace_id>\d+)/connectable(s)?', include('connectable.urls')),

    # context
    (r'^user/(?P<user_name>[\s\-\.\w]+)/context(s)?', include('context.urls')),

    # Platform Preferences
    (r'^user/(?P<user_name>[\s\-\.\w]+)/preference(s)?', include('preferences.urls')),

    # Catalogue Resource
    (r'^user/(?P<user_name>[\s\-\.\w]+)/catalogue/', include('catalogue.urls')),

    # Catalogue: Changing certification status
    (r'^catalogue/resource/(?P<resource_id>\d+)/activation$', ResourceEnabler(permitted_methods=('GET',))),

    #GadgetGenerator
    (r'^gadgetGenerator', include('gadgetGenerator.urls')),

    # Proxy
    (r'^proxy', include('proxy.urls')),

    # CLMS
    #(r'^clms/', include('clms.urls')),

    # Django contrib
    #(r'^registration/login_form/$', 'registration.views.login_form'),
    (r'^accounts/login/$', 'django.contrib.auth.views.login'),
 #   (r'^logout$', 'django.contrib.auth.views.logout'),
    # custom logouts (to enable anonymous access)
    (r'^logout$', 'authentication.logout'),
    (r'^admin/logout/$', 'authentication.logout'),

    #Admin CLMS interface
    #(r'^admin/clms/(?P<layout_id>\d+)/content/popup/', clms_admin_view.panel_list_popup),
    #(r'^admin/clms/content/popup/', clms_admin_view.panel_list_popup),
    #(r'^admin/clms/content/filter/', clms_admin_view.contents_filter),
    #(r'^admin/clms/(?P<url>.*)', clms_site.root),

    #Admin interface
    (r'^admin/(.*)', admin.site.root),

    # Django "set language" (internacionalitation)
    (r'^i18n/', include('django.conf.urls.i18n')),

    # Django JavaScript Internacionalitation
    (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),

)

handler404 = "django.views.defaults.page_not_found"
handler500 = "django.views.defaults.server_error"
<|endoftext|>


<commit_before>
def new_ratings(player1_rating,player2_rating,result,k_value=32,should_round=True):
	#Assign actual individual results
   player1_result = result
   player2_result = 1 - result

   #Calculate expected results
   player1_expectation = 1/(1+10**((player2_rating - player1_rating)/400.0)) #the .0 is important to force float operations!))
   player2_expectation = 1/(1+10**((player1_rating - player2_rating)/400.0))

	#Calculate new ratings
   player1_new_rating = player1_rating + (k_value*(player1_result - player1_expectation))
   player2_new_rating = player2_rating + (k_value*(player2_result - player2_expectation))

   #Optional rounding
   if should_round:
      player1_new_rating = int(player1_new_rating)
      player2_new_rating = int(player2_new_rating)

   # Create a dictionary to return and do so!
   new_ratings = dict()
   new_ratings['player1'] = player1_new_rating
   new_ratings['player2'] = player2_new_rating
   return new_ratings

class RatedPlayer(object):
   """A rated player"""
   def __init__(self,id,rating):
      self.id = id
      self.rating = rating
   def update_rating(self,rating):
      self.rating = rating

class Match(object):
   """Match"""
   def __init__(self,player1,player2,result):
      ratings_after_match = new_ratings(player1.rating,player2.rating,result)
      player1.update_rating(ratings_after_match['player1'])
      player2.update_rating(ratings_after_match['player2'])

tom = RatedPlayer("Tom",1600)
alan = RatedPlayer("Alan",2000)
print tom.rating
print alan.rating
Match(tom,alan,1)
print tom.rating
print alan.rating<commit_msg>shows examples both oop and procedural<commit_after>
def new_ratings(player1_rating,player2_rating,result,k_value=32,should_round=True):
	#Assign actual individual results
   player1_result = result
   player2_result = 1 - result

   #Calculate expected results
   player1_expectation = 1/(1+10**((player2_rating - player1_rating)/400.0)) #the .0 is important to force float operations!))
   player2_expectation = 1/(1+10**((player1_rating - player2_rating)/400.0))

	#Calculate new ratings
   player1_new_rating = player1_rating + (k_value*(player1_result - player1_expectation))
   player2_new_rating = player2_rating + (k_value*(player2_result - player2_expectation))

   #Optional rounding
   if should_round:
      player1_new_rating = int(player1_new_rating)
      player2_new_rating = int(player2_new_rating)

   # Create a dictionary to return and do so!
   new_ratings = dict()
   new_ratings['player1'] = player1_new_rating
   new_ratings['player2'] = player2_new_rating
   return new_ratings

class RatedPlayer(object):
   """A rated player"""
   def __init__(self,id,rating):
      self.id = id
      self.rating = rating
   def update_rating(self,rating):
      self.rating = rating

class Match(object):
   """Match"""
   def __init__(self,player1,player2,result):
      ratings_after_match = new_ratings(player1.rating,player2.rating,result)
      player1.update_rating(ratings_after_match['player1'])
      player2.update_rating(ratings_after_match['player2'])

# OOP
tom = RatedPlayer("Tom",1600)
alan = RatedPlayer("Alan",2000)
print tom.rating
print alan.rating
Match(tom,alan,1)
print tom.rating
print alan.rating
print

# procedural
tomRating = 1600
alanRating = 2000
print tomRating
print alanRating
after_match_ratings = new_ratings(tomRating,alanRating,1)
tomRating = after_match_ratings["player1"]
alanRating = after_match_ratings["player2"]
print tomRating
print alanRating<|endoftext|>


<commit_before>from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
     url(r'^admin/', include(admin.site.urls)),
     (r'^bio/(.*)/$', 'ap.apdirposts.views.bio'),
     (r'^post/(.*)/$', 'ap.apdirposts.views.post'),
     (r'^event/(.*)/$', 'ap.apdirposts.views.event'),
     (r'^join/$', 'ap.apdirposts.views.join'),
     (r'^donate/$', 'ap.apdirposts.views.donate'),
     (r'^about/$', 'ap.apdirposts.views.about'),
     (r'^about-us/$', 'ap.apdirposts.views.post', {'which': '7'}),
     (r'^history/$', 'ap.apdirposts.views.post', {'which': '9'}),
     (r'^photos/$', 'ap.apdirposts.views.post', {'which': '10'}),
     (r'^movies/$', 'ap.apdirposts.views.movies'),
     (r'^starchart/$', 'ap.apdirposts.views.starchart'),
     (r'^notice/(.*)/$', 'ap.apdirposts.views.notice'),
     (r'^post/$', 'ap.apdirposts.views.posttop'),
     (r'^notice/$', 'ap.apdirposts.views.noticetop'),
     (r'^event/$', 'ap.apdirposts.views.eventtop'),
     (r'^corner/$', 'ap.apdirposts.views.cornertop'),
     (r'^science/$', 'ap.apdirposts.views.sciencetop'),
     (r'^$', 'ap.apdirposts.views.front'),
)
<commit_msg>url for "about the website"<commit_after>from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
     url(r'^admin/', include(admin.site.urls)),
     (r'^bio/(.*)/$', 'ap.apdirposts.views.bio'),
     (r'^post/(.*)/$', 'ap.apdirposts.views.post'),
     (r'^event/(.*)/$', 'ap.apdirposts.views.event'),
     (r'^join/$', 'ap.apdirposts.views.join'),
     (r'^donate/$', 'ap.apdirposts.views.donate'),
     (r'^about/$', 'ap.apdirposts.views.about'),
     (r'^about-us/$', 'ap.apdirposts.views.post', {'which': '7'}),
     (r'^history/$', 'ap.apdirposts.views.post', {'which': '9'}),
     (r'^photos/$', 'ap.apdirposts.views.post', {'which': '10'}),
     (r'^movies/$', 'ap.apdirposts.views.movies'),
     (r'^starchart/$', 'ap.apdirposts.views.starchart'),
     (r'^notice/(.*)/$', 'ap.apdirposts.views.notice'),
     (r'^post/$', 'ap.apdirposts.views.posttop'),
     (r'^notice/$', 'ap.apdirposts.views.noticetop'),
     (r'^event/$', 'ap.apdirposts.views.eventtop'),
     (r'^corner/$', 'ap.apdirposts.views.cornertop'),
     (r'^science/$', 'ap.apdirposts.views.sciencetop'),
     (r'^website/$', 'ap.apdirposts.views.website'),
     (r'^$', 'ap.apdirposts.views.front'),
)
<|endoftext|>


<commit_before>from django.conf.urls import patterns, include
from django.conf import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
    (r'^$', 'equilibrator.gibbs.main_page.MainPage'),
    (r'^about', 'equilibrator.gibbs.info_pages.AboutPage'),
    (r'^faq', 'equilibrator.gibbs.info_pages.FAQPage'),
    (r'^whats_new', 'equilibrator.gibbs.info_pages.WhatsNewPage'),
    (r'^cite', 'equilibrator.gibbs.info_pages.CitePage'),
    (r'^classic_reactions', 'equilibrator.gibbs.info_pages.ClassicReactions'),
    (r'^compound_data', 'equilibrator.gibbs.compound_api.CompoundAPI'),
    (r'^compound_image', 'equilibrator.gibbs.compound_image.CompoundImage'),
    (r'^compound', 'equilibrator.gibbs.compound_page.CompoundPage'),
    (r'^download', 'equilibrator.gibbs.info_pages.DownloadPage'),
    (r'^enzyme', 'equilibrator.gibbs.enzyme_page.EnzymePage'),
    (r'^reaction', 'equilibrator.gibbs.reaction_page.ReactionPage'),
    (r'^graph_reaction', 'equilibrator.gibbs.reaction_graph.ReactionGraph'),
    (r'^data_refs', 'equilibrator.gibbs.data_refs_page.RefsPage'),
    (r'^search', 'equilibrator.gibbs.search_results_page.ResultsPage'),
    (r'^suggest', 'equilibrator.gibbs.suggest.SuggestJson'),
    #(r'^pathway$', 'equilibrator.gibbs.define_pathway_page.DefinePathwayPage'),
    #(r'^pathway/results', 'equilibrator.gibbs.pathway_result_page.PathwayResultPage'),
    (r'^robots\.txt', 'equilibrator.gibbs.info_pages.Robots'),
    # Example:
    # (r'^equilibrator/', include('equilibrator.foo.urls')),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
)
<commit_msg>Update access on urls.py<commit_after>from django.conf.urls import patterns, include
from django.conf import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
    (r'^$', 'equilibrator.gibbs.main_page.MainPage'),
    (r'^about', 'equilibrator.gibbs.info_pages.AboutPage'),
    (r'^faq', 'equilibrator.gibbs.info_pages.FAQPage'),
    (r'^whats_new', 'equilibrator.gibbs.info_pages.WhatsNewPage'),
    (r'^cite', 'equilibrator.gibbs.info_pages.CitePage'),
    (r'^classic_reactions', 'equilibrator.gibbs.info_pages.ClassicReactions'),
    (r'^compound_data', 'equilibrator.gibbs.compound_api.CompoundAPI'),
    (r'^compound_image', 'equilibrator.gibbs.compound_image.CompoundImage'),
    (r'^compound', 'equilibrator.gibbs.compound_page.CompoundPage'),
    (r'^download', 'equilibrator.gibbs.info_pages.DownloadPage'),
    (r'^enzyme', 'equilibrator.gibbs.enzyme_page.EnzymePage'),
    (r'^reaction', 'equilibrator.gibbs.reaction_page.ReactionPage'),
    (r'^graph_reaction', 'equilibrator.gibbs.reaction_graph.ReactionGraph'),
    (r'^data_refs', 'equilibrator.gibbs.data_refs_page.RefsPage'),
    (r'^search', 'equilibrator.gibbs.search_results_page.ResultsPage'),
    (r'^suggest', 'equilibrator.gibbs.suggest.SuggestJson'),
    #(r'^pathway$', 'equilibrator.gibbs.define_pathway_page.DefinePathwayPage'),
    #(r'^pathway/results', 'equilibrator.gibbs.pathway_result_page.PathwayResultPage'),
    (r'^robots\.txt', 'equilibrator.gibbs.info_pages.Robots'),
    # Example:
    # (r'^equilibrator/', include('equilibrator.foo.urls')),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
)
<|endoftext|>


<commit_before>from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^rdp/', include('rdp.urls')),
    url(r'admin/', include.site.urls),
]
<commit_msg> Deletes unecessary urls.py<commit_after><|endoftext|>


<commit_before>import os

from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.shortcuts import redirect

from tagging.views import tagged_object_list

from djangopeople import views, api #, clustering
from djangopeople.models import DjangoPerson

def perm_redirect(url):
    return lambda req: redirect(url, permanent=True)

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls), name='admin'),
    url(r'^$', views.index, name='index'),
    url(r'^login/$', 'django.contrib.auth.views.login',
        {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', views.logout, name='logout'),
    url(r'^about/$', views.about, name='about'),
    url(r'^recent/$', views.recent, name='recent'),
    url(r'^recover/$', views.lost_password, name='recover'),
    url(r'^recover/(?P<username>[a-z0-9]{3,})/(?P<days>[a-f0-9]+)/(?P<hash>[a-f0-9]{32})/$',
        views.lost_password_recover, name='do_recover'),
    url(r'^signup/$', views.signup, name='signup'),

    #openid stuff
    url(r'^openid/$', 'django_openidconsumer.views.begin', {
        'sreg': 'email,nickname,fullname',
        'redirect_to': '/openid/complete/',
    }, name='openid_begin'),
    url(r'^openid/complete/$', 'django_openidconsumer.views.complete', name='openid_complete'),
    url(r'^openid/whatnext/$', views.openid_whatnext, name='openid_whatnext'),
    url(r'^openid/signout/$', 'django_openidconsumer.views.signout', name='openid_signout'),
    url(r'^openid/associations/$', 'django_openidauth.views.associations', name='openid_associations'),

    url(r'^search/$', views.search, name='search'),

    url(r'^skills/(?P<tag>.*)/$', views.skill, name='skill_detail'),
    url(r'^skills/$', views.skill_cloud, name='skill_cloud'),

    url(r'^api/irc_lookup/(.*?)/$', api.irc_lookup, name='irc_lookup'),
    url(r'^api/irc_spotted/(.*?)/$', api.irc_spotted, name='irc_spotted'),
    url(r'^irc/active/$', views.irc_active, name='irc_active'),
    url(r'^irc/(.*?)/$', api.irc_redirect, name='irc_redirect'),

    (r'^uk/$', perm_redirect('/gb/')),

    url(r'^(?P<country_code>[a-z]{2})/$',
        views.country, name='country_detail'),

    url(r'^(?P<country_code>[a-z]{2})/sites/$',
        views.country_sites, name='country_sites'),

    url(r'^(?P<country_code>[a-z]{2})/skills/$',
        views.country_skill_cloud, name='country_skill_cloud'),

    url(r'^(?P<country_code>[a-z]{2})/skills/(?P<tag>.*)/$',
        views.country_skill, name='country_skill'),

    url(r'^(?P<country_code>[a-z]{2})/looking-for/(?P<looking_for>freelance|full-time)/$',
        views.country_looking_for, name='country_looking_for'),

    url(r'^([a-z]{2})/(\w+)/$', views.region, name='country_region'),

    url(r'^profile/', views.redirect_to_logged_in_user_profile,
        name='redirect_to_logged_in_user_profile'),
    url(r'^(?P<username>[a-z0-9]{3,})/$', views.profile, name='user_profile'),
    url(r'^(?P<username>[a-z0-9]{3,})/bio/$', views.edit_bio, name='edit_bio'),
    url(r'^(?P<username>[a-z0-9]{3,})/skills/$', views.edit_skills, name='edit_skills'),

    url(r'^(?P<username>[a-z0-9]{3,})/password/$',
        views.edit_password, name='edit_password'),

    url(r'^(?P<username>[a-z0-9]{3,})/account/$',
        views.edit_account, name='edit_account'),

    url(r'^(?P<username>[a-z0-9]{3,})/portfolio/$',
        views.edit_portfolio, name='edit_portfolio'),

    url(r'^(?P<username>[a-z0-9]{3,})/location/$',
        views.edit_location, name='edit_location'),

    url(r'^([a-z0-9]{3,})/finding/$',
        views.edit_finding, name='edit_finding'),

    url(r'^([a-z0-9]{3,})/upload/$',
        views.upload_profile_photo, name='upload_profile_photo'),

    url(r'^([a-z0-9]{3,})/upload/done/$',
        views.upload_done, name='upload_done'),
)

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<commit_msg>remove unused imports form urls.py<commit_after>from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.shortcuts import redirect

from djangopeople import views, api #, clustering

def perm_redirect(url):
    return lambda req: redirect(url, permanent=True)

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls), name='admin'),
    url(r'^$', views.index, name='index'),
    url(r'^login/$', 'django.contrib.auth.views.login',
        {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', views.logout, name='logout'),
    url(r'^about/$', views.about, name='about'),
    url(r'^recent/$', views.recent, name='recent'),
    url(r'^recover/$', views.lost_password, name='recover'),
    url(r'^recover/(?P<username>[a-z0-9]{3,})/(?P<days>[a-f0-9]+)/(?P<hash>[a-f0-9]{32})/$',
        views.lost_password_recover, name='do_recover'),
    url(r'^signup/$', views.signup, name='signup'),

    #openid stuff
    url(r'^openid/$', 'django_openidconsumer.views.begin', {
        'sreg': 'email,nickname,fullname',
        'redirect_to': '/openid/complete/',
    }, name='openid_begin'),
    url(r'^openid/complete/$', 'django_openidconsumer.views.complete', name='openid_complete'),
    url(r'^openid/whatnext/$', views.openid_whatnext, name='openid_whatnext'),
    url(r'^openid/signout/$', 'django_openidconsumer.views.signout', name='openid_signout'),
    url(r'^openid/associations/$', 'django_openidauth.views.associations', name='openid_associations'),

    url(r'^search/$', views.search, name='search'),

    url(r'^skills/(?P<tag>.*)/$', views.skill, name='skill_detail'),
    url(r'^skills/$', views.skill_cloud, name='skill_cloud'),

    url(r'^api/irc_lookup/(.*?)/$', api.irc_lookup, name='irc_lookup'),
    url(r'^api/irc_spotted/(.*?)/$', api.irc_spotted, name='irc_spotted'),
    url(r'^irc/active/$', views.irc_active, name='irc_active'),
    url(r'^irc/(.*?)/$', api.irc_redirect, name='irc_redirect'),

    (r'^uk/$', perm_redirect('/gb/')),

    url(r'^(?P<country_code>[a-z]{2})/$',
        views.country, name='country_detail'),

    url(r'^(?P<country_code>[a-z]{2})/sites/$',
        views.country_sites, name='country_sites'),

    url(r'^(?P<country_code>[a-z]{2})/skills/$',
        views.country_skill_cloud, name='country_skill_cloud'),

    url(r'^(?P<country_code>[a-z]{2})/skills/(?P<tag>.*)/$',
        views.country_skill, name='country_skill'),

    url(r'^(?P<country_code>[a-z]{2})/looking-for/(?P<looking_for>freelance|full-time)/$',
        views.country_looking_for, name='country_looking_for'),

    url(r'^([a-z]{2})/(\w+)/$', views.region, name='country_region'),

    url(r'^profile/', views.redirect_to_logged_in_user_profile,
        name='redirect_to_logged_in_user_profile'),
    url(r'^(?P<username>[a-z0-9]{3,})/$', views.profile, name='user_profile'),
    url(r'^(?P<username>[a-z0-9]{3,})/bio/$', views.edit_bio, name='edit_bio'),
    url(r'^(?P<username>[a-z0-9]{3,})/skills/$', views.edit_skills, name='edit_skills'),

    url(r'^(?P<username>[a-z0-9]{3,})/password/$',
        views.edit_password, name='edit_password'),

    url(r'^(?P<username>[a-z0-9]{3,})/account/$',
        views.edit_account, name='edit_account'),

    url(r'^(?P<username>[a-z0-9]{3,})/portfolio/$',
        views.edit_portfolio, name='edit_portfolio'),

    url(r'^(?P<username>[a-z0-9]{3,})/location/$',
        views.edit_location, name='edit_location'),

    url(r'^([a-z0-9]{3,})/finding/$',
        views.edit_finding, name='edit_finding'),

    url(r'^([a-z0-9]{3,})/upload/$',
        views.upload_profile_photo, name='upload_profile_photo'),

    url(r'^([a-z0-9]{3,})/upload/done/$',
        views.upload_done, name='upload_done'),
)

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *
from django.conf import settings

from django.views.generic.simple import direct_to_template

from django.contrib import admin
from django.views.generic.edit import CreateView

admin.autodiscover()

from sandbox.models import TempContactInfo

urlpatterns = patterns('',
    (r'^mesh_summit_contact/$', CreateView.as_view(model=TempContactInfo)),

    #MAIN
    (r'^$', 'main.views.main_landing'),

    #CMS
#    (r'^hack-and-tell/apply/$', 'cms.views.q_and_a_form', {'q_and_a_id': 1}),
    (r'^/cms/form/(?P<q_and_a_id>\d+)/$', 'cms.views.q_and_a_form'), #Public
    (r'^hack-and-tell/$', 'main.views.hack_and_tell'), #Public

    (r'^cms/edit_content_block/(?P<headline_slug>\w+)/$', 'cms.views.edit_content_block'),
    (r'^cms/edit_content_block/$', 'cms.views.edit_content_block'),

    (r'^blog/(?P<headline_slug>[-\w]+)/$', 'cms.views.blog'), #Public
    (r'^blog/$', 'cms.views.blog'), #Public

    #(r'^admin/varnish/', include('varnishapp.urls')),

    #Accounting
    (r'^accounting/show_donations', 'accounting.views.show_donations'),

    #Generic Ajax Handler - include object type in URL (This is used to update objects via ajax in a generic way)
    (r'^utility/submit_generic/(?P<app_name>\w+)/(?P<object_type>\w+)/$', 'utility.views.submit_generic'),
    (r'^utility/submit_generic_partial/(?P<object_type>\w+)/(?P<object_id>\d+)/$', 'utility.views.submit_generic_partial'),

    #Commerce
    (r'^commerce/record_purchase/$', 'commerce.views.record_purchase'),
    (r'^commerce/record_bill/$', 'commerce.views.record_purchase', {'is_bill': True}),
    (r'^commerce/record_donation', 'commerce.views.record_donation'),
    (r'^commerce/record_ingredient_order', 'commerce.views.record_ingredient_order'),
    (r'^commerce/view_exchange/(?P<id>\d+)/$', 'commerce.views.view_exchange'),
    (r'^commerce/view_purchase/(?P<seller_involvement_id>\d+)/$', 'commerce.views.view_purchase'),
    (r'^commerce/view_pledge/(?P<pledge_id>\d+)/$', 'commerce.views.view_pledge'),
    (r'^commerce/individual_delivery', 'commerce.views.individual_delivery'),
    (r'^commerce/fluidbarter', 'commerce.views.fluidbarter_main'),

    #Commerce: Front-facing eshu
    (r'^eshu$', 'commerce.views.eshu_main'),
    (r'^eshu/list_purchases/(?P<party_id>\d+)/$', 'commerce.views.list_purchases'),

    #Static
#    (r'^media/css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/css' % settings.PROJECT_ROOT}),
#    (r'^media/js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/js' % settings.PROJECT_ROOT}),
#    (r'^media/images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/images' % settings.PROJECT_ROOT}),
#    (r'^media/fonts/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/fonts' % settings.PROJECT_ROOT}),
#    (r'^media/code/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/code' % settings.PROJECT_ROOT}),
#    (r'^media/public/images/profile/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/public/images/profile' % settings.PROJECT_ROOT}),
#    (r'^media/public/images/message_files/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/public/images/message_files' % settings.PROJECT_ROOT}),
#    (r'^meta/docs/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/docs/_build/html' % settings.PROJECT_ROOT}),

    #Temp way to serve admin media files (we'll do it through nginx later, along with all other media files -Justin) (TODO: Or Twisted?)
    #(r'^media_admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/usr/local/lib/python2.6/dist-packages/django/contrib/admin/media'}),

    #Admin
    (r'^admin/doc/', include('django.contrib.admindocs.urls')),
    (r'^admin/', include(admin.site.urls)),

    #Contact
    (r'^contact/contact_list', 'contact.views.contact_list'),
    (r'^contact/contact_profile/(?P<contact_id>\d+)/', 'contact.views.contact_profile'),
    (r'^contact/contact_profile/(?P<username>\w+)/', 'contact.views.contact_profile'),
    (r'^contact/new_contact/', 'contact.views.new_contact'),
    (r'contact/toggle_dial_list/(?P<dial_list_id>\d+)/', 'contact.views.toggle_dial_list'),
    (r'contact/contact_forms_for_person/', 'contact.views.contact_forms_for_person'),
    (r'contact/phone_number_profile/(?P<phone_number_id>\d+)/', 'contact.views.phone_number_profile'),

    #Menu on TV
    (r'^bar_menu', 'pos.views.bar_menu'),

    #Login-related views
        #Presence
    (r'^bare_login', 'presence.views.bareLogin'), #Public
    (r'^bareLogout', 'presence.views.bareLogout'),

    (r'^api/whoami/', 'people.views.who_am_i'),
    (r'^api/remote_heartbeat_success', 'meta.views.remote_heartbeat_success'),

    #Main
    (r'^loggedInBubbles', 'main.views.loggedInBubbles'),
    (r'^rightSideWidgets', 'main.views.rightSideWidgets'),

    #People
    #(r'^members/', 'people.views.members'),
    #(r'^users/(?P<username>\w+)/$', 'people.views.memberProfile'),
    #(r'^apply/', 'people.views.memberApply'),
    #(r'^curriculum/', 'people.views.memberCurriculm'),

    #POS
    (r'^pos/pos_modal', 'commerce.views.pos_modal'),
    #Temporary solution until better way
    (r'^pos/$', 'pos.views.pos_landing'),
    (r'^pos/sales/$', 'pos.views.sales'),

    #Presence
    (r'^presence/askPurpose', 'presence.views.askPurpose'),
    (r'^presence/tellPurpose', 'presence.views.tellPurpose'),
    (r'^presence/viewSessions', 'presence.views.viewSessions'),
    (r'^presence/login', 'django.contrib.auth.views.login', {'template_name': 'presence/login_page.html'}),
    (r'^presence/close_slashroot', 'presence.views.close_slashroot'),

    #hwtrack
    (r'^hwtrack/all_devices', 'hwtrack.views.all_devices'),
    (r'^hwtrack/all_computers', 'hwtrack.views.all_computers'),
    #(r'^service/service_check_in', 'hwtrack.views.service_check_in'),

    #Service
    #(r'^serviceCheckIn', 'hwtrack.views.ServiceCheckIn'),
    (r'^computerOwner', 'hwtrack.views.Computer_Owner'),
    #This is for a client to track their computer through the site. It will be
    #something along these lines I suppose- AC, KP
    #(r'^hardwareTracking', 'hwtrack.views.hardware_Tracking')
    (r'^service/check_in/$', 'service.views.most_basic_check_in'),
    (r'^service/the_situation/$', 'service.views.the_situation'),
    (r'^service/archive/$', 'service.views.archive'),
    (r'^service/tickets/(?P<service_id>\d+)/$', 'service.views.tickets'),
    (r'^service/post_task_message/(?P<service_id>\d+)/', 'service.views.post_task_message'),

    #Social
    (r'^social/draw_attention_ajax/', 'social.views.draw_attention_ajax'),
    (r'^iam/$', 'social.views.dashboard'),
    (r'^social/messages/post_top_level/(?P<object_info>\w+)/', 'social.views.post_top_level_message'),
    (r'^social/acknowledge/(?P<attention_id>\d+)/', 'social.views.acknowledge_notification'),
    (r'^social/log/user/(?P<username>\w+)/$', 'social.views.log'),
    (r'^social/log/group/(?P<group_name>\w+)/$', 'social.views.log'),
    #(r'^social/log/$', 'social.views.log'),
    #(r'^social/log/log_landing/', 'social.views.log')

    #Phone
    (r'^comm/', include('comm.urls')),

    #do
    (r'^do/$', 'do.views.landing'),
    (r'^do/big_feed/$', 'do.views.big_feed'),
    (r'^do/public_list/$', 'do.views.public_list'),
    (r'^do/get_people_for_verb_as_html/(?P<verb_id>\d+)/$', 'do.views.get_people_for_verb_as_html'),

    (r'^do/task_form_handler', 'do.views.task_form_handler'),
    (r'^do/create_task', 'do.views.create_task'),
    (r'^do/task_prototype_list', 'do.views.task_prototype_list'),

    (r'^do/task_profile/(?P<task_id>\d+)/$','do.views.task_profile'),
    (r'^do/task_prototype_profile/(?P<task_prototype_id>\d+)/$','do.views.task_prototype_profile'),

    (r'^do/own_task/(?P<task_id>\d+)/$', 'do.views.own_task'),
    (r'^do/mark_completed/(?P<task_id>\d+)/', 'do.views.mark_completed'),
    (r'^do/mark_abandoned/(?P<task_id>\d+)/', 'do.views.mark_abandoned'),
    (r'^do/post_task_message/(?P<task_id>\d+)/', 'do.views.post_task_message'),

    (r'^do/new_child_ajax_handler/$', 'do.views.new_child_ajax_handler'),

    (r'^do/list_children_as_checkbox/$', 'do.views.task_family_as_checklist_template'),
    (r'^do/get_tasks_in_tag_ajax_as_html/(?P<object_id>\d+)/', 'do.views.get_tasks_as_html', {'by_verb': False}),
    (r'^do/get_tasks_in_verb_ajax_as_html/(?P<object_id>\d+)/', 'do.views.get_tasks_as_html'),

    (r'^do/protocols/$', 'do.views.protocols'),

    (r'^do/archives/$', 'do.views.archives'),

    (r'^do/get_taskBox_toot_court/(?P<task_id>\d+)/$', 'do.views.get_taskbox_toot_court'),

    #Power
    (r'^power/change/', 'power.views.change'),
    (r'^power/switch/', 'power.views.switch'),

    #Point of Sale
   # (r'^pos/autocomplete/(?P<criterion>\w+)/$', 'pos.views.autocomplete'),
    (r'^pos/beverageSale/', 'pos.views.beverageSale'),
    #(r'^pos/86product/' , 'pos.views.product86'),

    #Calendar
    (r'^calendar/(?P<moon_id>\d+)/$', 'mooncalendar.views.index'), #depricated in favor of new url
    (r'^happenings/(?P<moon_name>[-\w]+)/$', 'mooncalendar.views.index'),

    (r'^moons_info', 'mooncalendar.views.moons_info'),

    #Events
    #(r'^booking/', 'events.views.booking'),
    #(r'^upcoming/', 'events.mooncalendar.views.upcoming'),

    #Blog
    #(r'^blog/', 'blog.views.index'),

    #Searching
    #(r'^search/', include('haystack.urls')),

    #Utility
    (r'^utility/autocomplete/$', 'utility.views.autocomplete_dispatcher'),
    (r'^utility/save_tags_for_object/(?P<model_info>\w+)/$', 'utility.views.save_tags_for_object'),

     #Math
     (r'^donald/get_sigma/$', 'donald.views.get_sigma'),

     (r'^tinymce/', include('tinymce.urls')),

     #Mellon
     (r'^mellon/enter_new_magnetic_card/$', 'mellon.views.new_card_function_form'),
     (r'^mellon/submit_new_magnetic_card/$', 'mellon.views.save_new_card'),
     (r'^mellon/authenticate_card/$', 'mellon.views.authenticate_card'),

     #BlastForm
     (r'^blast_form/$', 'email_blast.views.email_blast'),
)

urlpatterns += patterns('django.views.generic.simple',
    (r'^isLoggedInDisplay/$', 'direct_to_template', {'template': 'widgets/login.html'}),
    (r'^graph_test/', 'direct_to_template', {'template': 'graph_test.html'}),
    )

urlpatterns += patterns('',(r'^users/(?P<username>\w+)/$', 'social.views.profile'),)

handler404 = 'meta.errors.page_not_found'
handler500 = "meta.errors.server_error"
<commit_msg>just committing to switch branch<commit_after>from django.conf.urls.defaults import *
from django.conf import settings

from django.views.generic.simple import direct_to_template

from django.contrib import admin
from django.views.generic.edit import CreateView

admin.autodiscover()

from sandbox.models import TempContactInfo

urlpatterns = patterns('',
    (r'^mesh_summit_contact/$', CreateView.as_view(model=TempContactInfo)),

    #MAIN
    (r'^$', 'main.views.main_landing'),

    #CMS
#    (r'^hack-and-tell/apply/$', 'cms.views.q_and_a_form', {'q_and_a_id': 1}),
    (r'^/cms/form/(?P<q_and_a_id>\d+)/$', 'cms.views.q_and_a_form'), #Public
    (r'^hack-and-tell/$', 'main.views.hack_and_tell'), #Public

    (r'^cms/edit_content_block/(?P<headline_slug>\w+)/$', 'cms.views.edit_content_block'),
    (r'^cms/edit_content_block/$', 'cms.views.edit_content_block'),

    (r'^blog/(?P<headline_slug>[-\w]+)/$', 'cms.views.blog'), #Public
    (r'^blog/$', 'cms.views.blog'), #Public

    #(r'^admin/varnish/', include('varnishapp.urls')),

    #Accounting
    (r'^accounting/show_donations', 'accounting.views.show_donations'),

    #Generic Ajax Handler - include object type in URL (This is used to update objects via ajax in a generic way)
    (r'^utility/submit_generic/(?P<app_name>\w+)/(?P<object_type>\w+)/$', 'utility.views.submit_generic'),
    (r'^utility/submit_generic_partial/(?P<object_type>\w+)/(?P<object_id>\d+)/$', 'utility.views.submit_generic_partial'),

    #Commerce
    (r'^commerce/record_purchase/$', 'commerce.views.record_purchase'),
    (r'^commerce/record_bill/$', 'commerce.views.record_purchase', {'is_bill': True}),
    (r'^commerce/record_donation', 'commerce.views.record_donation'),
    (r'^commerce/record_ingredient_order', 'commerce.views.record_ingredient_order'),
    (r'^commerce/view_exchange/(?P<id>\d+)/$', 'commerce.views.view_exchange'),
    (r'^commerce/view_purchase/(?P<seller_involvement_id>\d+)/$', 'commerce.views.view_purchase'),
    (r'^commerce/view_pledge/(?P<pledge_id>\d+)/$', 'commerce.views.view_pledge'),
    (r'^commerce/individual_delivery', 'commerce.views.individual_delivery'),
    (r'^commerce/fluidbarter', 'commerce.views.fluidbarter_main'),

    #Commerce: Front-facing eshu
    (r'^eshu$', 'commerce.views.eshu_main'),
    (r'^eshu/list_purchases/(?P<party_id>\d+)/$', 'commerce.views.list_purchases'),

    #Static
#    (r'^media/css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/css' % settings.PROJECT_ROOT}),
#    (r'^media/js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/js' % settings.PROJECT_ROOT}),
#    (r'^media/images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/images' % settings.PROJECT_ROOT}),
#    (r'^media/fonts/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/fonts' % settings.PROJECT_ROOT}),
#    (r'^media/code/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/code' % settings.PROJECT_ROOT}),
#    (r'^media/public/images/profile/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/public/images/profile' % settings.PROJECT_ROOT}),
#    (r'^media/public/images/message_files/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/static/public/images/message_files' % settings.PROJECT_ROOT}),
#    (r'^meta/docs/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '%s/docs/_build/html' % settings.PROJECT_ROOT}),

    #Temp way to serve admin media files (we'll do it through nginx later, along with all other media files -Justin) (TODO: Or Twisted?)
    #(r'^media_admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/usr/local/lib/python2.6/dist-packages/django/contrib/admin/media'}),

    #Admin
    (r'^admin/doc/', include('django.contrib.admindocs.urls')),
    (r'^admin/', include(admin.site.urls)),

    #Contact
    (r'^contact/contact_list', 'contact.views.contact_list'),
    (r'^contact/contact_profile/(?P<contact_id>\d+)/', 'contact.views.contact_profile'),
    (r'^contact/contact_profile/(?P<username>\w+)/', 'contact.views.contact_profile'),
    (r'^contact/new_contact/', 'contact.views.new_contact'),
    (r'contact/toggle_dial_list/(?P<dial_list_id>\d+)/', 'contact.views.toggle_dial_list'),
    (r'contact/contact_forms_for_person/', 'contact.views.contact_forms_for_person'),
    (r'contact/phone_number_profile/(?P<phone_number_id>\d+)/', 'contact.views.phone_number_profile'),

    #Menu on TV
    (r'^bar_menu', 'pos.views.bar_menu'),

    #Login-related views
        #Presence
    (r'^bare_login', 'presence.views.bareLogin'), #Public
    (r'^bareLogout', 'presence.views.bareLogout'),

    (r'^api/whoami/', 'people.views.who_am_i'),
    (r'^api/remote_heartbeat_success', 'meta.views.remote_heartbeat_success'),

    #Main
    (r'^loggedInBubbles', 'main.views.loggedInBubbles'),
    (r'^rightSideWidgets', 'main.views.rightSideWidgets'),

    #People
    #(r'^members/', 'people.views.members'),
    #(r'^users/(?P<username>\w+)/$', 'people.views.memberProfile'),
    #(r'^apply/', 'people.views.memberApply'),
    #(r'^curriculum/', 'people.views.memberCurriculm'),

    #POS
    (r'^pos/pos_modal', 'commerce.views.pos_modal'),
    #Temporary solution until better way
    (r'^pos/$', 'pos.views.pos_landing'),
    (r'^pos/sales/$', 'pos.views.sales'),

    #Presence
    (r'^presence/askPurpose', 'presence.views.askPurpose'),
    (r'^presence/tellPurpose', 'presence.views.tellPurpose'),
    (r'^presence/viewSessions', 'presence.views.viewSessions'),
    (r'^presence/login', 'django.contrib.auth.views.login', {'template_name': 'presence/login_page.html'}),
    (r'^presence/close_slashroot', 'presence.views.close_slashroot'),

    #hwtrack
    (r'^hwtrack/all_devices', 'hwtrack.views.all_devices'),
    (r'^hwtrack/all_computers', 'hwtrack.views.all_computers'),
    #(r'^service/service_check_in', 'hwtrack.views.service_check_in'),

    #Service
    #(r'^serviceCheckIn', 'hwtrack.views.ServiceCheckIn'),
    (r'^computerOwner', 'hwtrack.views.Computer_Owner'),
    #This is for a client to track their computer through the site. It will be
    #something along these lines I suppose- AC, KP
    #(r'^hardwareTracking', 'hwtrack.views.hardware_Tracking')
    (r'^service/check_in/$', 'service.views.most_basic_check_in'),
    (r'^service/the_situation/$', 'service.views.the_situation'),
    (r'^service/archive/$', 'service.views.archive'),
    (r'^service/tickets/(?P<service_id>\d+)/$', 'service.views.tickets'),
    (r'^service/post_task_message/(?P<service_id>\d+)/', 'service.views.post_task_message'),

    #Social
    (r'^social/draw_attention_ajax/', 'social.views.draw_attention_ajax'),
    (r'^iam/$', 'social.views.dashboard'),
    (r'^social/messages/post_top_level/(?P<object_info>\w+)/', 'social.views.post_top_level_message'),
    (r'^social/acknowledge/(?P<attention_id>\d+)/', 'social.views.acknowledge_notification'),
    (r'^social/log/user/(?P<username>\w+)/$', 'social.views.log'),
    (r'^social/log/group/(?P<group_name>\w+)/$', 'social.views.log'),
    #(r'^social/log/$', 'social.views.log'),
    #(r'^social/log/log_landing/', 'social.views.log')

    #Phone
    (r'^comm/', include('comm.urls')),

    #do
    (r'^do/$', 'do.views.landing'),
    (r'^do/big_feed/$', 'do.views.big_feed'),
    (r'^do/public_list/$', 'do.views.public_list'),
    (r'^do/get_people_for_verb_as_html/(?P<verb_id>\d+)/$', 'do.views.get_people_for_verb_as_html'),

    (r'^do/task_form_handler', 'do.views.task_form_handler'),
    (r'^do/create_task', 'do.views.create_task'),
    (r'^do/task_prototype_list', 'do.views.task_prototype_list'),

    (r'^do/task_profile/(?P<task_id>\d+)/$','do.views.task_profile'),
    (r'^do/task_prototype_profile/(?P<task_prototype_id>\d+)/$','do.views.task_prototype_profile'),

    (r'^do/own_task/(?P<task_id>\d+)/$', 'do.views.own_task'),
    (r'^do/mark_completed/(?P<task_id>\d+)/', 'do.views.mark_completed'),
    (r'^do/mark_abandoned/(?P<task_id>\d+)/', 'do.views.mark_abandoned'),
    (r'^do/post_task_message/(?P<task_id>\d+)/', 'do.views.post_task_message'),

    (r'^do/new_child_ajax_handler/$', 'do.views.new_child_ajax_handler'),

    (r'^do/list_children_as_checkbox/$', 'do.views.task_family_as_checklist_template'),
    (r'^do/get_tasks_in_tag_ajax_as_html/(?P<object_id>\d+)/', 'do.views.get_tasks_as_html', {'by_verb': False}),
    (r'^do/get_tasks_in_verb_ajax_as_html/(?P<object_id>\d+)/', 'do.views.get_tasks_as_html'),

    (r'^do/protocols/$', 'do.views.protocols'),

    (r'^do/archives/$', 'do.views.archives'),

    (r'^do/get_taskBox_toot_court/(?P<task_id>\d+)/$', 'do.views.get_taskbox_toot_court'),

    #Power
    (r'^power/change/', 'power.views.change'),
    (r'^power/switch/', 'power.views.switch'),

    #Point of Sale
   # (r'^pos/autocomplete/(?P<criterion>\w+)/$', 'pos.views.autocomplete'),
    (r'^pos/beverageSale/', 'pos.views.beverageSale'),
    #(r'^pos/86product/' , 'pos.views.product86'),

    #Calendar
    (r'^calendar/(?P<moon_id>\d+)/$', 'mooncalendar.views.index'), #depricated in favor of new url
    (r'^happenings/(?P<moon_name>[-\w]+)/$', 'mooncalendar.views.index'),

    (r'^moons_info', 'mooncalendar.views.moons_info'),

    #Events
    #(r'^booking/', 'events.views.booking'),
    #(r'^upcoming/', 'events.mooncalendar.views.upcoming'),

    #Blog
    #(r'^blog/', 'blog.views.index'),

    #Searching
    #(r'^search/', include('haystack.urls')),

    #Utility
    (r'^utility/autocomplete/$', 'utility.views.autocomplete_dispatcher'),
    (r'^utility/save_tags_for_object/(?P<model_info>\w+)/$', 'utility.views.save_tags_for_object'),

     #Math
     (r'^donald/get_sigma/$', 'donald.views.get_sigma'),

     (r'^tinymce/', include('tinymce.urls')),

     #Mellon
     (r'^mellon/enter_new_magnetic_card/$', 'mellon.views.new_card_function_form'),
     (r'^mellon/submit_new_magnetic_card/$', 'mellon.views.save_new_card'),
     (r'^mellon/authenticate_card/$', 'mellon.views.authenticate_card'),

     #BlastForm
     (r'^blast_form/$', 'email_blast.views.email_blast'),
     (r'^blast_form/confirmation/$', 'email_blast.views.confirmation'),
     (r'^people/role_form/$', 'people.views.role_form'),
)

urlpatterns += patterns('django.views.generic.simple',
    (r'^isLoggedInDisplay/$', 'direct_to_template', {'template': 'widgets/login.html'}),
    (r'^graph_test/', 'direct_to_template', {'template': 'graph_test.html'}),
    )

urlpatterns += patterns('',(r'^users/(?P<username>\w+)/$', 'social.views.profile'),)

handler404 = 'meta.errors.page_not_found'
handler500 = "meta.errors.server_error"
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings

from django.views.generic.simple import direct_to_template

import ideas
from ideas import views

from about.views import about_pages
from ideas.views import requires_login

from api.resources import IdeaResource, UserResource, CategoryResource
from tastypie.api import Api

v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(IdeaResource())
v1_api.register(CategoryResource())

admin.autodiscover()

handler500 = 'djangotoolbox.errorviews.server_error'

urlpatterns = patterns('',
    (r'^accounts/', include('registration.backends.default.urls')),
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
    ('^_ah/warmup$', 'djangoappengine.views.warmup'),
    (r'^admin/', include(admin.site.urls)),
    ('^$', 'views.main_page'),
    (r'^about/$', direct_to_template, {'template' : 'about.html'}),
    (r'^about/(\w+)/$', about_pages),
    (r'^', include('ideas.urls')),
    (r'^', include('contactus.urls')),
    (r'^api/', include(v1_api.urls)),
)

<commit_msg>Made it so the registration accepts only unique email.<commit_after>from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings

from django.views.generic.simple import direct_to_template

import ideas
from ideas import views

from about.views import about_pages
from ideas.views import requires_login

from registration.forms import RegistrationFormUniqueEmail

from api.resources import IdeaResource, UserResource, CategoryResource
from tastypie.api import Api

v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(IdeaResource())
v1_api.register(CategoryResource())

admin.autodiscover()

handler500 = 'djangotoolbox.errorviews.server_error'

urlpatterns = patterns('',
    (r'^accounts/register/$', 'registration.views.register', {'form_class' : RegistrationFormUniqueEmail, 'backend':'registration.backends.default.DefaultBackend' }),
    (r'^accounts/', include('registration.backends.default.urls')),
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
    ('^_ah/warmup$', 'djangoappengine.views.warmup'),
    (r'^admin/', include(admin.site.urls)),
    ('^$', 'views.main_page'),
    (r'^about/$', direct_to_template, {'template' : 'about.html'}),
    (r'^about/(\w+)/$', about_pages),
    (r'^', include('ideas.urls')),
    (r'^', include('contactus.urls')),
    (r'^api/', include(v1_api.urls)),

)

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from os import environ
try:
    from urllib.parse import urlparse as _urlparse
except ImportError:
    from urlparse import urlparse as _urlparse

def lower_dict(d):
    """Lower cases string keys in given dict."""

    _d = {}

    for k, v in d.iteritems():
        try:
            _d[k.lower()] = v
        except AttributeError:
            _d[k] = v

    return _d

def urlparse(d, keys=None):
    """Returns a copy of the given dictionary with url values parsed."""

    d = d.copy()

    if keys is None:
        keys = d.keys()

    for key in keys:
        d[key] = _urlparse(d[key])

    return d

def prefix(prefix):
    """Returns a dictionary of all environment variables starting with
    the given prefix, lower cased and stripped.
    """

    d = {}
    e = lower_dict(environ.copy())

    prefix = prefix.lower()

    for k, v in e.iteritems():
        try:
            if k.startswith(prefix):
                k = k[len(prefix):]
                d[k] = v
        except AttributeError:
            pass

    return d

def map(**kwargs):
    """Returns a dictionary of the given keyword arguments mapped to their
    values from the environment, with input keys lower cased.
    """

    d = {}
    e = lower_dict(environ.copy())

    for k, v in kwargs.iteritems():
        d[k] = e.get(v.lower())

    return d
<commit_msg>Style fix<commit_after># -*- coding: utf-8 -*-

from os import environ
try:
    from urllib.parse import urlparse as _urlparse
except ImportError:
    from urlparse import urlparse as _urlparse

def lower_dict(d):
    """Lower cases string keys in given dict."""

    _d = {}

    for k, v in d.iteritems():
        try:
            _d[k.lower()] = v
        except AttributeError:
            _d[k] = v

    return _d

def urlparse(d, keys=None):
    """Returns a copy of the given dictionary with url values parsed."""

    d = d.copy()

    if keys is None:
        keys = d.keys()

    for key in keys:
        d[key] = _urlparse(d[key])

    return d

def prefix(prefix):
    """Returns a dictionary of all environment variables starting with
    the given prefix, lower cased and stripped.
    """

    d = {}
    e = lower_dict(environ.copy())

    prefix = prefix.lower()

    for k, v in e.iteritems():
        try:
            if k.startswith(prefix):
                k = k[len(prefix):]
                d[k] = v
        except AttributeError:
            pass

    return d

def map(**kwargs):
    """Returns a dictionary of the given keyword arguments mapped to their
    values from the environment, with input keys lower cased.
    """

    d = {}
    e = lower_dict(environ.copy())

    for k, v in kwargs.iteritems():
        d[k] = e.get(v.lower())

    return d
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic import list_detail, date_based, create_update
from fumblerooski.college import views as college_views

admin.autodiscover()

urlpatterns = patterns('',
    # Uncomment this for admin:
     (r'^admin/(.*)', admin.site.root),
     (r'^$', college_views.homepage),
     (r'^blog/', include('fumblerooski.blog.urls')),
     (r'^college/seasons/(?P<season>\d+)/week/(?P<week>\d+)/$', college_views.season_week),
     (r'^college/conferences/$', college_views.conference_index),
     (r'^college/conferences/(?P<conf>[-a-z0-9]+)/(?P<season>\d+)/$', college_views.conference_detail),
     (r'^college/games/$', college_views.game_index),
     (r'^college/coaches/(?P<coach>[-a-z]+)/$', college_views.coach_detail),
     (r'^college/teams/$', college_views.team_index),
     (r'^college/teams/undefeated/(?P<season>\d+)/$', college_views.undefeated_teams),
     (r'^college/teams/(?P<team>[-a-z]+)/$', college_views.team_detail),
     (r'^college/teams/(?P<team>[-a-z]+)/offense/$', college_views.team_offense),
     (r'^college/teams/(?P<team>[-a-z]+)/offense/rushing/$', college_views.team_offense_rushing),
     (r'^college/teams/(?P<team>[-a-z]+)/defense/$', college_views.team_defense),
     (r'^college/teams/(?P<team>[-a-z]+)/penalties/$', college_views.team_penalties),
     (r'^college/teams/(?P<team>[-a-z]+)/first-downs/$', college_views.team_first_downs),
     (r'^college/teams/(?P<team>[-a-z]+)/first-downs/(?P<category>rushing|passing|penalty)/$', college_views.team_first_downs_category),
     (r'^college/teams/(?P<team>[-a-z]+)/positions/(?<pos>[a-z][a-z][a-z]?)/$', college_views.team_position_detail),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/$', college_views.team_detail_season),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/rankings/$', college_views.team_rankings_season),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/classes/(?P<cl>[fr|so|jr|sr])/$', college_views.team_by_cls),
#     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/positions/(?<pos>[a-z][a-z][a-z]?)/$', college_views.team_positions),
     (r'^college/teams/(?P<team>[-a-z]+)/opponents/$', college_views.team_opponents),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/players/$', college_views.team_players),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/players/(?P<player>[-a-z]+)/$', college_views.player_detail),
#     (r'^college/teams/(?P<team>[-a-z]+)/recruits/$', recruit_views.team_detail),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/$', college_views.team_vs),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/(?P<outcome>wins|losses|ties)/$', college_views.team_vs),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', college_views.game),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/drives/$', college_views.game_drive),
#    (r'^college/teams/(?P<team>[-a-z]+)/recruits/(?P<year>2\d\d\d)/$', recruit_views.team_detail_year),
#    (r'^college/teams/(?P<team>[-a-z]+)/recruits/(?P<pos>[a-z][a-z]?[a-z]?)/$', recruit_views.team_detail_position),
     (r'^states/$', college_views.state_index),
     (r'^states/(?P<state>[a-z][a-z])/$', college_views.state_detail),
)
<commit_msg>more url futzing<commit_after>from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic import list_detail, date_based, create_update
from fumblerooski.college import views as college_views

admin.autodiscover()

urlpatterns = patterns('',
    # Uncomment this for admin:
     (r'^admin/(.*)', admin.site.root),
     (r'^$', college_views.homepage),
     (r'^blog/', include('fumblerooski.blog.urls')),
     (r'^college/seasons/(?P<season>\d+)/week/(?P<week>\d+)/$', college_views.season_week),
     (r'^college/conferences/$', college_views.conference_index),
     (r'^college/conferences/(?P<conf>[-a-z0-9]+)/(?P<season>\d+)/$', college_views.conference_detail),
     (r'^college/games/$', college_views.game_index),
     (r'^college/coaches/(?P<coach>[-a-z]+)/$', college_views.coach_detail),
     (r'^college/teams/$', college_views.team_index),
     (r'^college/teams/undefeated/(?P<season>\d+)/$', college_views.undefeated_teams),
     (r'^college/teams/(?P<team>[-a-z]+)/$', college_views.team_detail),
     (r'^college/teams/(?P<team>[-a-z]+)/offense/$', college_views.team_offense),
     (r'^college/teams/(?P<team>[-a-z]+)/offense/rushing/$', college_views.team_offense_rushing),
     (r'^college/teams/(?P<team>[-a-z]+)/defense/$', college_views.team_defense),
     (r'^college/teams/(?P<team>[-a-z]+)/penalties/$', college_views.team_penalties),
     (r'^college/teams/(?P<team>[-a-z]+)/first-downs/$', college_views.team_first_downs),
     (r'^college/teams/(?P<team>[-a-z]+)/first-downs/(?P<category>rushing|passing|penalty)/$', college_views.team_first_downs_category),
     (r'^college/teams/(?P<team>[-a-z]+)/positions/(?<pos>[a-z][a-z][a-z]?)/$', college_views.team_position_detail),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/$', college_views.team_detail_season),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/rankings/$', college_views.team_rankings_season),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/classes/(?P<cl>[fr|so|jr|sr])/$', college_views.team_by_cls),
#     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/positions/(?<pos>[a-z][a-z][a-z]?)/$', college_views.team_positions),
     (r'^college/teams/(?P<team>[-a-z]+)/opponents/$', college_views.team_opponents),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/players/$', college_views.team_players),
     (r'^college/teams/(?P<team>[-a-z]+)/(?P<season>\d+)/players/(?P<player>[-a-z]+)/$', college_views.player_detail),
#     (r'^college/teams/(?P<team>[-a-z]+)/recruits/$', recruit_views.team_detail),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/$', college_views.team_vs),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/(?P<outcome>wins|losses|ties)/$', college_views.team_vs),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', college_views.game),
     (r'^college/teams/(?P<team1>[-a-z]+)/vs/(?P<team2>[-a-z]+)/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/drives/$', college_views.game_drive),
#    (r'^college/teams/(?P<team>[-a-z]+)/recruits/(?P<year>2\d\d\d)/$', recruit_views.team_detail_year),
#    (r'^college/teams/(?P<team>[-a-z]+)/recruits/(?P<pos>[a-z][a-z]?[a-z]?)/$', recruit_views.team_detail_position),
     (r'^states/$', college_views.state_index),
#     (r'^states/(?P<state>[a-z][a-z])/$', college_views.state_detail),
)
<|endoftext|>


<commit_before>print "I will now count my chickens:"

print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4

print "Now I will count the eggs:"

print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

print "Is it true that 3 + 2 < 5 - 7?"

print 3 + 2 < 5 - 7

print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7

print "Oh, that's why it's False."

print "How about some more."

print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
<commit_msg>Adding comments to explain each block, as per the Exercise 3 Study Drills.<commit_after># Prints something.
print "I will now count my chickens:"

# Prints some things and does maths with some other things.
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4

# Prints more things.
print "Now I will count the eggs:"

# More math. Useful but there's a reason I wasn't a math major.
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

# Printing a question this time.
print "Is it true that 3 + 2 < 5 - 7?"

# MOAR MATHS
print 3 + 2 < 5 - 7

# Now it's starting to look like I'm doubting my ability to maths.
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7

# I'm helping myself talk to myself with the program as an intermediary?
print "Oh, that's why it's False."

# Printing about printing/computing some more.
print "How about some more."

# Triple checking the maths.
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
<|endoftext|>


<commit_before>
# This module gives easy access to fitting functions and supports
# the quantities module.

# Known issue, to be investigated:
#   In test_linear the boostrap algorithm almost always finds a
#   too shallow slope, whereas ODR gives a better result.
#   It matches curve_fit for y errors only.

import inspect
import numpy as np
import numpy.random as random
import quantities as pq

import scipy.optimize as opt
import scipy.odr as odr
import scipy.stats as stats

from physics.fmt import *

# see http://stackoverflow.com/a/21844726
def bootstrap(fun, p0, xdata, ydata,
              xerr=None, yerr=None,
              runs=1000, pprint=''):
    """Estimate parameters and their standard deviation from
      given data with uncertainty using boostrap Monte-Carlo method.
      Works on pure numbers without units.

      When xerr and yerr are None, scipy's leastsq is used for an initial fit.
      The standard deviation of residuals is then used to scatter the ydata
      points for boostrapping.

      Arguments:
        fun: The model function `ys = f(xs, *params)`
        p0: Initial parameters.
        runs: The number of data sets to generate
        pprint: When bool(pprint) is True some explaining output is generated
          and printed to stdout prepended with pprint (so you can use it
          to add indentation).

      Returns: `(params, std)`
        Where params is a list of fitted parameters and std their
        standard deviation.

      Raises:
        RuntimeError: If a leastsq run didn't find a solution.
    """
    if pprint: print(pprint+"Bootstrapping with %d runs"%runs)
    errfunc = lambda p, x, y: fun(x, *p) - y
    if xerr is None and yerr is None:
        if pprint: print(pprint+"    Estimating std dev of residuals")
        params, pcov, info, msg, ier =\
            opt.leastsq(errfunc, p0, args=(xdata, ydata),
                        full_output=1)
        if not (1 <= ier <= 4):
            raise RuntimeError("Could not estimate residuals: %s"%msg)
        s_res = np.std(errfunc(params, xdata, ydata))
        if pprint:
            print(pprint+"        parameters: "+repr(param))
            print(pprint+"        std dev of residuals: %f"+s_res)
    ps = []
    for i in range(runs):
        if xerr is None and yerr is None:
            xs = xdata
            ys = np.random.normal(ydata, s_res)
        else:
            if xerr is not None: xs = random.normal(xdata, xerr)
            else: xs = xdata
            if yerr is not None: ys = random.normal(ydata, yerr)
            else: ys = ydata
        rparam, rcov, info, msg, ier =\
            opt.leastsq(errfunc, p0, args=(xs, ys),
                        full_output=1)
        if not (1 <= ier <= 4):
            raise RuntimeError("No solution found for all data sets: %s"%s)
        ps.append(rparam)
    ps = np.array(ps)
    params = np.mean(ps, 0)
    std = np.std(ps, 0)
    if pprint:
        print(pprint+"    parameters: "+repr(params))
        print(pprint+"    std dev: "+repr(std))
    return (params, std)

def fit(fun, xdata, ydata, p0,
        xerr=None, yerr=None,
        usebootstrap=False, pprint=True):
    """This is a helper function dealing with the quantities and is handling
      over the real math to other fit functions.

      Arguments:
        xdata: The x data points as Quantity or simple ndarray (dimensionless).
        ydata: The y data points as Quantity or simple ndarray (dimensionless),
            Has to have same length as xdata.
        p0: Initial parameters, used to determine number of free parameters when
            present.  The model function will receive the paramesters in the
            same units, and results will be displayed in these units.
        xerr: Uncertainty for xdata, either a single value for all points, or
            an array of same length as xdata.  Will be rescaled to same unit as
            xdata before fitting.
        yerr: Uncertainty for ydata.
        usebootstrap: Use bootstrapping instead of some scipy fitting algorithm.
            Bootstrapping works for all types of uncertainties.
        pprint: Set True to see some more information about fit.

      Returns:
        params: A list of parameters as pq.Quantity
        std: Standard deviations of parameters in same units
        info: A dict with the following keys:
          'method': 'curve_fit' or 'odr'
          'ok': True when the fit was probably successful
          'cov' (optional): the covariance matrix
          'res_var': residual variance / reduced chi squared
          'msg' (optional): some information about fit in english
    """
    assert len(np.shape(xdata)) is 1
    assert len(np.shape(ydata)) is 1
    n = len(xdata)
    assert n == len(ydata)
    dof = n - len(p0)
    assert dof > 0
    # inspect model function for parameter names
    argspec = inspect.getargspec(fun)
    paramnames = None
    if argspec.varargs is None:
        if len(p0) != len(argspec.args) - 1:
            raise ValueError("Number of arguments of model function"
                             " is not matching length of p0.")
        paramnames = argspec.args[1:]
    else:
        paramnames = ["param%d"%(i+1) for i in range(dof)]
    # strip units
    assert isinstance(xdata, np.ndarray)
    assert isinstance(ydata, np.ndarray)
    if isinstance(xdata, pq.Quantity):
        xunits = xdata.units
        xdata = xdata.magnitude
    else: xunits = 1 * pq.dimensionless
    if isinstance(ydata, pq.Quantity):
        yunits = ydata.units
        ydata = ydata.magnitude
    else: yunits = 1 * pq.dimensionless
    if xerr is not None:
        if isinstance(xerr, pq.Quantity):
            xerr = xerr.rescale(xunits).magnitude
        assert len(np.shape(xerr)) == 0 or np.shape(xerr) == (len(xdata),)
        if np.amin(xerr) <= 0:
            raise ValueError("Zeros / neg values in x-uncert not allowed")
    if yerr is not None:
        if isinstance(yerr, pq.Quantity):
            yerr = yerr.rescale(yunits).magnitude
        assert len(np.shape(yerr)) == 0 or np.shape(yerr) == (len(ydata),)
        if np.amin(yerr) <= 0:
            raise ValueError("Zeros / neg values in y-uncert not allowed")
    p0 = [p if isinstance(p, pq.Quantity) else p * pq.dimensionless
                for p in p0]
    p0units = [p.units for p in p0]
    p0 = [p.magnitude for p in p0]
    # wrap function appending units again
    def func(x, *params):
        params2 = [p*u for p,u in zip(params, p0units)]
        return fun(x * xunits, *params2).rescale(yunits).magnitude

    # fit
    if pprint:
        print("Fitting [%s] depending on [%s]"%(repr(yunits)[13:],
                                                repr(xunits)[13:]))
        print("    N=%d, params=%d, dof=%d"%(n, len(p0), dof))
    params = None # estimated parameters
    std = None    # standard deviation
    info = {}     # additional information
    if usebootstrap:
        if pprint: print("    Method: bootstrap")
        info['method'] = 'bootstrap'
        try:
            if pprint: ppprint = '    '
            else: ppprint = False
            params, std = bootstrap(fun, p0, xdata, ydata, xerr, yerr,
                                    pprint=ppprint)
        except RuntimeError as e:
            info['ok'] = False
            info['msg'] = str(e)
        else:
            info['ok'] = True
            if xerr is None and yerr is None:
                info['res_var'] = np.sum((func(xdata, *params)-ydata)**2) / dof
            elif xerr is None:
                info['res_var'] = (np.sum((func(xdata, *params)-ydata)**2
                                         / yerr**2) / dof)
    elif xerr is None and yerr is None:
        if pprint: print("    Method: scipy leastsq")
        info['method'] = 'leastsq'
        errfunc = lambda p, x, y: fun(x, *p) - y
        params, pcov, inf, msg, ier =\
            opt.leastsq(errfunc, p0,
                        args=(xdata, ydata),
                        full_output=1)
        if not (1 <= ier <= 4):
            info['ok'] = False
            info['msg'] = msg
        else:
            info['ok'] = pcov is not None
            info['res_var'] = np.sum((func(xdata, *params)-ydata)**2) / dof
            info['msg'] = msg
            if pcov is not None:
                # multiply by residual variance because leastsq
                # returns the reduced covariance matrix
                info['cov'] = pcov * info['res_var']
                std = [np.sqrt(pcov[i][i]) for i in range(len(p0))]
            else: std = [np.inf] * len(p0)
    elif xerr is None:
        if pprint: print("    Method: scipy curve_fit")
        info['method'] = 'curve_fit'
        try:
            params, pcov, inf, msg, ier =\
                opt.curve_fit(func, xdata, ydata, p0,
                            sigma=yerr, #absolute_sigma=True,
                            full_output=1)
        except RuntimeError as e:
            info['ok'] = False
            info['msg'] = str(e)
        else:
            info['ok'] = not np.any(np.isinf(pcov))
            info['msg'] = msg
            info['cov'] = pcov
            info['res_var'] = (np.sum((func(xdata, *params)-ydata)**2 / yerr**2)
                               / dof)
            std = [np.sqrt(pcov[i][i]) for i in range(len(p0))]
    else:
        if pprint: print("    Method: scipy ODR")
        info['method'] = 'odr'
        # change function signature again
        def odrf(B, x):
            return fun(x, *B)
        # run ODR
        model = odr.Model(odrf)
        data = odr.RealData(xdata, ydata, sx=xerr, sy=yerr)
        regr = odr.ODR(data, model, beta0=p0)
        out = regr.run()
        # evaluate
        info['ok'] = (1 <= out.info <= 3)
        info['cov'] = out.cov_beta
        info['res_var'] = out.res_var
        info['msg'] = out.stopreason
        params = out.beta
        std = out.sd_beta

    # append units
    params = [p*u for p,u in zip(params, p0units)]
    std = [s*u for s,u in zip(std, p0units)]
    # pretty print
    if pprint:
        print("    successful: %s"%info['ok'])
        if 'msg' in info:
            print("   ", info['msg'])
        if 'res_var' in info:
            print("    Residual variance: %f"%info['res_var'])
            p = stats.chi2.cdf(info['res_var']*dof, dof)
            print("    Probability of fit: {:.1f}%".format((1-p)*100))
        if params and std:
            print("    Parameters:")
            for n,p,s in zip(paramnames, params, std):
                print("      %s: %s"%(n, fmtquant(p, s, unit=True)))
    return params, std, info

def distribute(xs, xerr):
    """Add normal distributed error to all values in `xs`
      according to `xerr`.  Rescale xerr to units of xs.
    """
    if isinstance(xs, pq.Quantity):
        unit = xs.units
        xs = xs.magnitude
        assert isinstance(xerr, pq.Quantity)
        xerr = xerr.rescale(unit).magnitude
    else: unit = 1
    dist = random.normal(xs, xerr)
    return dist * unit

def draw_samples(fun, xs, params, xerr=None, yerr=None):
    """Calculate function values using `params` and then distribute
      `xs` and `ys` according to `xerr` and `yerr`.

      Returns: (xdata, ydata)
    """
    ys = fun(xs, *params)
    if xerr: xs = distribute(xs, xerr)
    if yerr: ys = distribute(ys, yerr)
    return (xs, ys)

def test_model(fun, p0, xs, xerr, yerr):
    xdata, ydata = draw_samples(fun, xs, p0, xerr=xerr, yerr=yerr)
    pinit = [p * random.normal(1, 0.1) for p in p0]
    # fit
    p1, std1, info1 = fit(fun, xdata, ydata, pinit,
                          yerr=yerr, xerr=xerr)
    # bootstrap
    p2, std2, info2 = fit(fun, xdata, ydata, pinit,
                          yerr=yerr, xerr=xerr,
                          usebootstrap=True)
    # compare
    print("Comparison: %s <-> %s (showing deviation from model"
          " parameter)"%(info1['method'], info2['method']))
    for i in range(len(p0)):
        print("    Parameter {:d}: {} <-> {} (model: {})".format(i,
                fmtquant(np.absolute(p1[i]-p0[i])/std1[i]),
                fmtquant(np.absolute(p2[i]-p0[i])/std2[i]),
                fmtquant(p0[i])))
    print()
    # plot
    import matplotlib.pyplot as plt
    plt.figure()
    if xerr or yerr:
        plt.errorbar(xdata, ydata, xerr=xerr, yerr=yerr, fmt=' ', label='data')
    else:
        plt.plot(xdata, ydata, '.', label='data')
    plt.plot(xs, fun(xs, *p0), label='model')
    plt.plot(xs, fun(xs, *p1), label=info1['method'])
    plt.plot(xs, fun(xs, *p2), label=info2['method'])
    plt.legend(loc='best', numpoints=1)
    plt.show()

def test_linear():
    a = -0.5 * pq.nm / pq.s
    b = 5 * pq.nm
    def f(xs, a, b):
        return xs * a + b
    xbase = np.linspace(0, 16, 101) * pq.s
    test_model(f, (a,b), xbase, None, 1*pq.nm)
    test_model(f, (a,b), xbase,
               1/np.sqrt(2)*pq.s, 1/np.sqrt(2)*pq.nm)

def test_exp():
    a = 5 * pq.nm
    b = -0.1 / pq.s
    c = 0.5 * pq.nm
    def f(xs, a, b, c):
        return a * np.exp(b * xs) + c
    xbase = np.linspace(0, 30, 101) * pq.s
    test_model(f, (a,b,c), xbase, None, 0.5*pq.nm)
    test_model(f, (a,b,c), xbase,
               0.3 * pq.s, 0.3 * pq.nm)

def test_chi2(N=300, n=101,
              xerr=None, #0.2*pq.s,
              yerr=0.1*pq.nm):
    a = 10 * pq.nm / pq.s
    b = 5 * pq.nm
    def f(xs, a, b):
        return xs * a + b
    chi2rs = []
    print("Chi2_red distribution")
    print("    Fitting %d points %d times, ..."%(n, N))
    xbase = np.linspace(0, 50, n) * pq.s
    for i in range(N):
        xdata, ydata = draw_samples(f, xbase, (a,b), xerr=xerr, yerr=yerr)
        pinit = [p * random.normal(1, 0.1) for p in (a, b)]
        param, std, info = fit(f, xdata, ydata, pinit,
                               yerr=yerr, xerr=xerr,
                               pprint=False)
        chi2rs.append(info['res_var'])
    chi2rs = np.array(chi2rs)
    print("    Mean:",np.mean(chi2rs))
    print("    Std dev:",np.std(chi2rs))

if __name__ == '__main__':
    test_chi2(n=100)
    #test_linear()
    #test_exp()
<commit_msg>remove bootstrapping, change rename fit functions<commit_after>
# This module gives easy access to fitting functions and supports
# the quantities module.

import warnings
import inspect
import numpy as np
import numpy.random as random
import quantities as pq

import scipy.optimize as opt
import scipy.odr as odr
import scipy.stats as stats

from martha.fmt import fmtquant

# show warnings every time
class FitWarning(Warning):
    pass

warnings.simplefilter('always', FitWarning)

def autofit(fun, xdata, ydata, p0,
            xerr=None, yerr=None):
    """This function selects one of the SciPy fit functions leastsq, curve_fit
      or ODR depending on given uncertainties.  This function does not work with
      Quantities.

      xerr and yerr are None: use `scipy.optimize.leastsq`,
      xerr is None: use `scipy.optimize.curve_fit`,
      both given: use `scipy.odr.odr`

      Arguments:
        fun: the model function `fun(x, param1, param2, ...)`.  It has to work
            on single values and numpy.ndarrays for x.
        xdata: the xdata as 1-dim array
        ydata: the ydata as 1-dim array
        p0: The initial guess for parameters.
        xerr: the uncertainty for xdata (scalar or of same length as xdata)
        yerr: the uncertainty for ydata (scalar or of same length as ydata)

      Returns: a 3-tuple of
        params: An array of estimated parameters
        stdev: An array of estimated standard deviations for parameters,
            may be `inf` if fit failed.
        infodict: dict with keys (optional keys may be undefined)
          'method': 'leastsq', 'curve_fit' or 'odr'
          'ok': True when the fit was probably successful (converged)
          'res_var': residual variance / reduced chi squared
          'cov' (optional): the covariance matrix
          'msg' (optional): some information about fit in english
          'out' (optional): the full output of the used algorithm
    """
    # check data
    if isinstance(xdata, pq.Quantity) or isinstance(ydata, pq.Quantity):
        warnings.warn("xdata or ydata is a Quantity.  Use fitquant.",
                      category=FitWarning)
    if isinstance(xerr, pq.Quantity) or isinstance(yerr, pq.Quantity):
        warnings.warn("xerr or yerr is a Quantity.  Use fitquant.",
                      category=FitWarning)
    if len(np.shape(xdata)) != 1 or len(np.shape(ydata)) != 1:
        raise ValueError("xdata and ydata have to be 1-dimensional arrays")
    if len(ydata) != len(xdata):
        raise ValueError("xdata and ydata not of same length")
    if xerr is not None:
        if not np.isscalar(xerr):
            if np.shape(xerr) != np.shape(xdata):
                raise ValueError("xerr not of same shape as xdata")
        if np.min(xerr) <= 0:
            warnings.warn("xerr contains data points <= 0",
                          category=FitWarning)
    if yerr is not None and not np.isscalar(yerr):
        if np.shape(yerr) != np.shape(ydata):
            raise ValueError("yerr not of same shape as ydata")
        if np.min(yerr) <= 0:
            warnings.warn("yerr contains data points <= 0",
                          category=FitWarning)

    n = len(xdata)    # number of data points
    dof = n - len(p0) # degrees of freedom
    params = None # estimated parameters
    std = None    # standard deviation
    info = {}     # additional information

    # fit
    if xerr is None and yerr is None:
        info['method'] = 'leastsq'
        errfunc = lambda p, x, y: fun(x, *p) - y
        params, pcov, fullout, msg, ier =\
            opt.leastsq(errfunc, p0,
                        args=(xdata, ydata),
                        full_output=1)
        info['out'] = fullout
        if not (1 <= ier <= 4):
            info['ok'] = False
            info['msg'] = msg
        else:
            info['ok'] = pcov is not None
            info['res_var'] = np.sum((fun(xdata, *params)-ydata)**2) / dof
            info['msg'] = msg
            if pcov is not None:
                # multiply by residual variance because leastsq
                # returns the reduced covariance matrix
                info['cov'] = pcov * info['res_var']
                std = [np.sqrt(pcov[i][i]) for i in range(len(p0))]
            else: std = [np.inf] * len(p0)
    elif xerr is None:
        info['method'] = 'curve_fit'
        try:
            params, pcov, fullout, msg, ier =\
                opt.curve_fit(fun, xdata, ydata, p0,
                            sigma=yerr, #absolute_sigma=True,
                            full_output=1)
        except RuntimeError as e:
            info['ok'] = False
            info['msg'] = str(e)
        else:
            info['out'] = fullout
            info['ok'] = not np.any(np.isinf(pcov))
            info['msg'] = msg
            info['cov'] = pcov
            info['res_var'] = (np.sum((fun(xdata, *params)-ydata)**2 / yerr**2)
                               / dof)
            std = [np.sqrt(pcov[i][i]) for i in range(len(p0))]
    else:
        info['method'] = 'odr'
        # change function signature
        def odrf(B, x):
            return fun(x, *B)
        # run ODR
        model = odr.Model(odrf)
        data = odr.RealData(xdata, ydata, sx=xerr, sy=yerr)
        regr = odr.ODR(data, model, beta0=p0)
        out = regr.run()
        # evaluate
        info['ok'] = (1 <= out.info <= 3)
        info['cov'] = out.cov_beta
        info['res_var'] = out.res_var
        info['msg'] = out.stopreason
        info['out'] = out
        params = out.beta
        std = out.sd_beta
    return params, std, info

def fitquant(fun, xdata, ydata, p0,
             xerr=None, yerr=None,
             pprint=True, full_output=False):
    """This is a helper function dealing with the quantities and then
      calling `autofit`.

      Arguments:
        fun: A function like `f(x, param1, param2, ...)` returning `y`.  It
            must be able to work with `np.ndarray`s as input for x.
        xdata: The x data points as Quantity or simple ndarray (dimensionless).
        ydata: The y data points as Quantity or simple ndarray (dimensionless),
            Has to have same length as xdata.
        p0: Initial parameters, used to determine number of free parameters when
            present.  The model function will receive the paramesters in the
            same units, and results will be displayed in these units.
        xerr: Uncertainty for xdata, either a single value for all points, or
            an array of same length as xdata.  Will be rescaled to same unit as
            xdata before fitting.
        yerr: Uncertainty for ydata.
        pprint: Set True to see some more information about fit.
        full_output: Set True to get 3-tuple instead of 2-tuple as return value
            containing the infodict as third element

      Returns:
        params: A list of parameters as pq.Quantity
        stddev: Standard deviations of parameters in same units
        infodict (only with full_output=True): same as in autofit
    """
    n = len(xdata)
    dof = n - len(p0)
    # strip units
    if isinstance(xdata, pq.Quantity):
        xunits = xdata.units
        xdata = xdata.magnitude
    else:
        xunits = 1 * pq.dimensionless
        ydata = np.array(xdata)
    if isinstance(ydata, pq.Quantity):
        yunits = ydata.units
        ydata = ydata.magnitude
    else:
        yunits = 1 * pq.dimensionless
        ydata = np.array(ydata)
    if xerr is not None and isinstance(xerr, pq.Quantity):
        try: xerr = xerr.rescale(xunits).magnitude
        except ValueError as e:
            raise ValueError("Dimension of xerr not matching xdata: "+str(e))
    if yerr is not None and isinstance(yerr, pq.Quantity):
        try: yerr = yerr.rescale(yunits).magnitude
        except ValueError as e:
            raise ValueError("Dimension of yerr not matching ydata: "+str(e))
    p0 = [p if isinstance(p, pq.Quantity) else p * pq.dimensionless for p in p0]
    p0units = list([p.units for p in p0])
    p0 = list([p.magnitude for p in p0])
    # inspect model function for parameter names
    argspec = inspect.getargspec(fun)
    if argspec.varargs is None:
        if len(p0) != len(argspec.args) - 1:
            raise ValueError("Number of arguments of model function"
                             " is not matching length of p0.")
        paramnames = argspec.args[1:]
    else:
        paramnames = ["param%d"%(i+1) for i in range(len(p0))]
    # wrap function appending units
    def func(x, *params):
        params2 = [p*u for p,u in zip(params, p0units)]
        return fun(x * xunits, *params2).rescale(yunits).magnitude

    if pprint:
        print("Fitting [%s] depending on [%s]"%(repr(yunits)[13:],
                                                repr(xunits)[13:]))
        print("    N=%d, params=%d, dof=%d"%(n, len(p0), dof))
    params, std, info = autofit(func, xdata, ydata, p0, xerr, yerr)
    params = [p*u for p,u in zip(params, p0units)]
    std = [s*u for s,u in zip(std, p0units)]
    if pprint: # pretty print
        print("    Method:", info['method'])
        print("    successful:", info['ok'])
        if 'msg' in info:
            print("   ", info['msg'])
        if 'res_var' in info:
            print("    Residual variance:", info['res_var'])
            p = stats.chi2.cdf(info['res_var']*dof, dof)
            print("    Probability of fit: {:.1f}%".format((1-p)*100))
        if params and std:
            print("    Parameters:")
            for n,p,s in zip(paramnames, params, std):
                print("      {:s}: {:s}".format(n, fmtquant(p, s, unit=True)))
    if full_output:
        return params, std, info
    else:
        return params, std
<|endoftext|>


<commit_before>#/usr/bin/env python

GREEN_COLOR = '\033[92m'
RED_COLOR = '\033[91m'
END_COLOR = '\033[0m'

class Machine(object):
    def __init__(self, states, alphabet, transitions, start, accept_states):
        """Constructor for this state machine. Do not invoke directly, instead
        use the from_arguments classmethod ie;

        machine = Machine.from_arguments(states, alphabet, transitions, start, end)
        machine.run()
        """

        self._states = states
        self._alphabet = alphabet
        self._transitions = transitions
        self._start = start
        self._accept_states = accept_states

    def run(self, input, console_output=True):
        """Takes an input string, and runs it against the machine's states,
        and transitions.

        Args:
            input -- the input string to test.

        Keyword Args:
            console_output -- Set this to False if you do not want
                to print to the console. (Defaults to True).

        Returns:
            A boolean representing if the input passes through the state machine
            and

        """
        if not isinstance(input, str):
            if console_output:
                print RED_COLOR + "Error: input is not a string" + END_COLOR

            return False

        current_state = self._start

        for value in input:
            # If the value doesn't exist in the alphabet, break.
            if value not in self._alphabet:
                break

            # Get the transitions available from the current state.
            transition_map = self._transitions.get(current_state)

            # If there are no transitions available from the current state,
            # break the run loop.
            if not transition_map:
                break

            # Get the next state.
            next_state = transition_map.get(value)

            # If there is no next state, or the next state isn't in
            if not next_state or (next_state not in self._states):
                break

            # Otherwise, transition.
            current_state = next_state

        if current_state in self._accept_states:
            if console_output:
                print GREEN_COLOR + "PASS" + END_COLOR

            return True
        else:
            if console_output:
                print RED_COLOR + "FAIL" + END_COLOR
                acceptable_states_string = ''.join(self._accept_states)
                print "Ended with state: {0} with acceptable end states: {1}".format(
                    current_state,
                    acceptable_states_string
                )

            return False

    @classmethod
    def from_arguments(cls, states, alphabet, transitions, start, end):
        """Main classmethod for building a machin.

        Arguments:
            states - a list of states within the machine.
            alphabet - a list defining the language the machine speaks.
            transitions - a map of maps that define state transitions.
            start - a start state.
            end - a list of acceptable end states.

        Returns:
            A Machine instance. Call .run on it with an input against
            the machine.
        """
        assert isinstance(states, list), "States is not a list"
        assert isinstance(alphabet, list), "Alphabet is not a list"

        # Make sure the start state is valid.
        assert start in states, \
                "Start state {0} is not within defined states".format(start)

        # Make sure the accept states are valid.
        for accept_state in end:
            assert accept_state in states, \
                    "Accept state {0} is not within defined states".format(accept_state)

        assert isinstance(transitions, dict), "Transitions is not a dict"

        return cls(states, alphabet, transitions, start, end)
<commit_msg>more doc changes.<commit_after>#/usr/bin/env python

GREEN_COLOR = '\033[92m'
RED_COLOR = '\033[91m'
END_COLOR = '\033[0m'

class Machine(object):
    def __init__(self, states, alphabet, transitions, start, accept_states):
        """Constructor for this state machine. Do not invoke directly, instead
        use the from_arguments classmethod ie;

        >>> machine = Machine.from_arguments(states, alphabet, transitions, start, end)
        >>> machine.run()
        """

        self._states = states
        self._alphabet = alphabet
        self._transitions = transitions
        self._start = start
        self._accept_states = accept_states

    def run(self, input, console_output=True):
        """Takes an input string, and runs it against the machine's states,
        and transitions.

        Args:
            input -- the input string to test.

        Keyword Args:
            console_output -- Set this to False if you do not want
                to print to the console. (Defaults to True).

        Returns:
            A boolean representing if the input passes through the state machine
            and

        """
        if not isinstance(input, str):
            if console_output:
                print RED_COLOR + "Error: input is not a string" + END_COLOR

            return False

        current_state = self._start

        for value in input:
            # If the value doesn't exist in the alphabet, break.
            if value not in self._alphabet:
                break

            # Get the transitions available from the current state.
            transition_map = self._transitions.get(current_state)

            # If there are no transitions available from the current state,
            # break the run loop.
            if not transition_map:
                break

            # Get the next state.
            next_state = transition_map.get(value)

            # If there is no next state, or the next state isn't in the list of
            # available states, break.
            if not next_state or (next_state not in self._states):
                break

            # Otherwise, transition.
            current_state = next_state

        if current_state in self._accept_states:
            if console_output:
                print GREEN_COLOR + "PASS" + END_COLOR

            return True
        else:
            if console_output:
                print RED_COLOR + "FAIL" + END_COLOR
                acceptable_states_string = ''.join(self._accept_states)
                print "Ended with state: {0} with acceptable end states: {1}".format(
                    current_state,
                    acceptable_states_string
                )

            return False

    @classmethod
    def from_arguments(cls, states, alphabet, transitions, start, end):
        """Main classmethod for building a machine.

        Arguments:
            states - a list of states within the machine.
            alphabet - a list defining the language the machine speaks.
            transitions - a map of maps that define state transitions.
            start - a start state.
            end - a list of acceptable end states.

        Returns:
            A Machine instance. Call .run on it with an input against
            the machine.
        """
        assert isinstance(states, list), "States is not a list"
        assert isinstance(alphabet, list), "Alphabet is not a list"

        # Make sure the start state is valid.
        assert start in states, \
                "Start state {0} is not within defined states".format(start)

        # Make sure the accept states are valid.
        for accept_state in end:
            assert accept_state in states, \
                    "Accept state {0} is not within defined states".format(accept_state)

        assert isinstance(transitions, dict), "Transitions is not a dict"

        return cls(states, alphabet, transitions, start, end)
<|endoftext|>