<commit_before>from pprint import pprint

from django.shortcuts import render
from django.urls import reverse
from django.views import View

from fo2.connections import db_cursor_so

from base.views import O2BaseGetPostView
from utils.views import totalize_data

import contabil.forms as forms
import contabil.queries as queries
from contabil.queries import nf_rec_info
from contabil.functions.nf import nf_situacao_descr

class NFRecebida(O2BaseGetPostView):

    def __init__(self, *args, **kwargs):
        super(NFRecebida, self).__init__(*args, **kwargs)
        self.Form_class = forms.NotaFiscalForm
        self.template_name = 'contabil/nf_recebida.html'
        self.title_name = "Nota fiscal recebida"
        self.get_args = ['nf', 'empresa']
        self.cleaned_data2self = True

    def mount_context(self):
        cursor = db_cursor_so(self.request)
        self.context = {
            'titulo': self.title_name,
        }

        data = nf_rec_info.query(
            cursor, self.nf, self.empresa)
        if len(data) == 0:
            self.context.update({
                'msg_erro': "Nota fiscal recebida não encontrada",
            })
        else:
            self.context.update({
                'headers': [
                    "Data",
                    "cnpj9",
                    "cnpj4",
                    "cnpj2",
                    "nome",
                    "NF",
                    "SERIE",
                    "nat_op",
                    "nat_uf",
                    'nat_cod',
                    'nat_of',
                    "nat_descr",
                    "tran_est",
                    "tran_descr",
                    "hist_cont",
                    "hist_descr",
                ],
                'fields': [
                    'dt',
                    'cnpj9',
                    'cnpj4',
                    'cnpj2',
                    'nome',
                    'nf',
                    'serie',
                    'nat_op',
                    'nat_uf',
                    'nat_cod',
                    'nat_of',
                    'nat_descr',
                    'tran_est',
                    'tran_descr',
                    'hist_cont',
                    'hist_descr',
                ],
                'data': data,
            })

            i_data = queries.nf_itens(cursor, self.nf, especiais=True, empresa=self.empresa)
            max_digits = 0
            for row in i_data:
                if row['PEDIDO_VENDA'] == 0:
                    row['PEDIDO_VENDA'] = '-'
                else:
                    row['PEDIDO_VENDA|LINK'] = reverse(
                        'producao:pedido__get', args=[row['PEDIDO_VENDA']])
                num_digits = str(row['QTDE_ITEM_FATUR'])[::-1].find('.')
                max_digits = max(max_digits, num_digits)
                row['VALOR_UNITARIO'] = \
                    row['VALOR_CONTABIL'] / row['QTDE_ITEM_FATUR']

            if i_data:
                totalize_data(i_data, {
                    'sum': ['QTDE_ITEM_FATUR', 'VALOR_CONTABIL'],
                    'descr': {'NARRATIVA': "Totais:"},
                    'row_style': 'font-weight: bold;',
                })

            for row in i_data:
                row['QTDE_ITEM_FATUR|DECIMALS'] = max_digits
                row['VALOR_UNITARIO|DECIMALS'] = 2
                row['VALOR_CONTABIL|DECIMALS'] = 2

            self.context.update({
                'i_headers': [
                    "Seq.",
                    "Nível",
                    "Referência",
                    "Tamanho",
                    "Cor",
                    "Descrição",
                    "Quantidade",
                    "Valor unitário",
                    "Valor total",
                    "Pedido de venda",
                ],
                'i_fields': [
                    'SEQ_ITEM_NFISC',
                    'NIVEL_ESTRUTURA',
                    'GRUPO_ESTRUTURA',
                    'SUBGRU_ESTRUTURA',
                    'ITEM_ESTRUTURA',
                    'NARRATIVA',
                    'QTDE_ITEM_FATUR',
                    'VALOR_UNITARIO',
                    'VALOR_CONTABIL',
                    'PEDIDO_VENDA',
                ],
                'i_data': i_data,
                'i_style': {
                    7: 'text-align: right;',
                    8: 'text-align: right;',
                    9: 'text-align: right;',
                    10: 'text-align: right;',
                },
            })
<commit_msg>view NFRecebida versão inicial que mostra itens<commit_after>from pprint import pprint

from django.shortcuts import render
from django.urls import reverse
from django.views import View

from fo2.connections import db_cursor_so

from base.views import O2BaseGetPostView
from utils.views import totalize_data

import contabil.forms as forms
from contabil.queries import (
    nf_rec_info,
    nf_rec_itens,
)
from contabil.functions.nf import nf_situacao_descr

class NFRecebida(O2BaseGetPostView):

    def __init__(self, *args, **kwargs):
        super(NFRecebida, self).__init__(*args, **kwargs)
        self.Form_class = forms.NotaFiscalForm
        self.template_name = 'contabil/nf_recebida.html'
        self.title_name = "Nota fiscal recebida"
        self.get_args = ['nf', 'empresa']
        self.cleaned_data2self = True

    def mount_context(self):
        cursor = db_cursor_so(self.request)
        self.context = {
            'titulo': self.title_name,
        }

        data = nf_rec_info.query(
            cursor, self.nf, self.empresa)
        if len(data) == 0:
            self.context.update({
                'msg_erro': "Nota fiscal recebida não encontrada",
            })
        else:
            self.context.update({
                'headers': [
                    "Data",
                    "cnpj9",
                    "cnpj4",
                    "cnpj2",
                    "nome",
                    "NF",
                    "SERIE",
                    "nat_op",
                    "nat_uf",
                    'nat_cod',
                    'nat_of',
                    "nat_descr",
                    "tran_est",
                    "tran_descr",
                    "hist_cont",
                    "hist_descr",
                ],
                'fields': [
                    'dt',
                    'cnpj9',
                    'cnpj4',
                    'cnpj2',
                    'nome',
                    'nf',
                    'serie',
                    'nat_op',
                    'nat_uf',
                    'nat_cod',
                    'nat_of',
                    'nat_descr',
                    'tran_est',
                    'tran_descr',
                    'hist_cont',
                    'hist_descr',
                ],
                'data': data,
            })

            i_data = nf_rec_itens.query(cursor, self.nf, self.empresa)

            if i_data:
                totalize_data(i_data, {
                    'sum': ['qtd'],
                    'descr': {'ref': "Total:"},
                    'row_style': 'font-weight: bold;',
                })

            self.context.update({
                'i_headers': [
                    "Nível",
                    "ref",
                    "tam",
                    "cor",
                    "qtd",
                ],
                'i_fields': [
                    'niv',
                    'ref',
                    'tam',
                    'cor',
                    'qtd',
                ],
                'i_data': i_data,
                'i_style': {
                    5: 'text-align: right;',
                },
            })
<|endoftext|>


<commit_before>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import wx
try:
    from wx.lib.agw import flatnotebook as fnb
except ImportError:
    from wx.lib import flatnotebook as fnb

from robotide.editors import RideEventHandler
from robotide.errors import PluginPageNotFoundError
from robotide.publish import RideNotebookTabchange, RideSavingDatafile,\
                           RideSavedDatafiles
from robotide import utils
from robotide import context

from actions import Actions
from dialogs import KeywordSearchDialog, AboutDialog
from filedialogs import NewProjectDialog, NewResourceDialog, ChangeFormatDialog
from pluginmanager import PluginManager
from suitetree import SuiteTree

class RideFrame(wx.Frame, RideEventHandler, utils.OnScreenEnsuringFrame):

    def __init__(self, application, keyword_filter):
        wx.Frame.__init__(self, None, -1, 'RIDE',
                          pos=context.SETTINGS["mainframe position"],
                          size=context.SETTINGS["mainframe size"])
        self._application = application
        self._create_decorations()
        self.ensure_on_screen()
        self._create_containers()
        self._plugin_manager = PluginManager(self.notebook)
        self._kw_search_dialog = KeywordSearchDialog(self, keyword_filter)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Show()

    def _create_containers(self):
        splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)
        # for now, hide the tabs if there's only one. Until there are
        # at least two tabs there's no point in taking up the screen
        # real estate. Eventually this should be a user preference.
        self.notebook = NoteBook(splitter, self._application)
        self.tree = SuiteTree(splitter) #, self._editor_panel)
        splitter.SplitVertically(self.tree, self.notebook, 300)

    def _create_decorations(self):
        # We need to define some standard toolbar buttons. For
        # now, create an empty toolbar so plugins have a place to
        # put their buttons.
        actions = Actions(self)
        self.SetMenuBar(actions.get_menubar())
        self.SetToolBar(actions.get_toolbar())
        self.CreateStatusBar()

    def populate_tree(self, model):
        self.tree.populate_tree(model)

    def show_page(self, panel):
        """Shows the notebook page that contains the given panel.

        Throws a PluginPageNotFoundError exception if the page can't be found.
        """
        if self.notebook.GetCurrentPage() != panel:
            page = self.notebook.GetPageIndex(panel)
            if page >= 0:
                self.notebook.SetSelection(page)
            else:
                raise PluginPageNotFoundError("unable to find a notebook page for the given panel")

    def delete_page(self, panel):
        page = self.notebook.GetPageIndex(panel)
        self.notebook.DeletePage(page)

    def _get_active_item(self):
        return self.tree.get_active_item()

    def OnClose(self, event):
        self._save_mainframe_size_and_position()
        if self._application.ok_to_exit():
            self.Destroy()
        else:
            wx.CloseEvent.Veto(event)

    def _save_mainframe_size_and_position(self):
        context.SETTINGS["mainframe size"] = self.GetSizeTuple()
        context.SETTINGS["mainframe position"] = self.GetPositionTuple()

    #File Menu

    def OnNewSuite(self, event):
        if not self._application.ok_to_open_new():
            return
        dlg = NewProjectDialog(self, self._default_dir)
        if dlg.ShowModal() == wx.ID_OK:
            dirname = os.path.dirname(dlg.get_path())
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            self._default_dir = dirname
            self._application.open_suite(dlg.get_path())
            self.tree.populate_tree(self._application.model)
        dlg.Destroy()

    # TODO: Are properties ok in here? Settings are saved when frame is closed.
    def _set_default_dir(self, dirname):
        context.SETTINGS["default directory"] = dirname

    def _get_default_dir(self):
        return os.path.abspath(context.SETTINGS["default directory"])

    _default_dir = property(_get_default_dir, _set_default_dir)

    def OnNewResource(self, event):
        dlg = NewResourceDialog(self, self._default_dir)
        if dlg.ShowModal() == wx.ID_OK:
            self._default_dir = os.path.dirname(dlg.get_path())
            self._application.open_resource(dlg.get_path())
        dlg.Destroy()

    def OnOpen(self, event):
        if not self._application.ok_to_open_new():
            return
        path = self._get_path()
        if path:
            self.open_suite(path)

    def OnOpenResource(self, event):
        path = self._get_path()
        if path:
            self._application.open_resource(path)

    def _get_path(self):
        wildcard = ('All files|*.*|Robot data (*.html)|*.*htm*|'
                    'Robot data (*.tsv)|*.tsv|Robot data (*txt)|*.txt')
        dlg = wx.FileDialog(self, message='Open', wildcard=wildcard,
                            defaultDir=self._default_dir, style=wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self._default_dir = os.path.dirname(path)
        else:
            path = None
        dlg.Destroy()
        return path

    def open_suite(self, path):
        self._application.open_suite(path)
        self.tree.populate_tree(self._application.model)

    def OnOpenDirectory(self, event):
        if not self._application.ok_to_open_new():
            return
        path = wx.DirSelector(message='Choose a directory containing Robot files',
                              defaultPath=self._default_dir)
        if path:
            self._default_dir = os.path.dirname(path)
            self.open_suite(path)
        event.Skip()

    def OnSave(self, event):
        self._save(self._get_active_item())

    def OnSaveAll(self, event):
        self._save()

    def _save(self, datafile=None):
        files_without_format = self._application.get_files_without_format(datafile)
        for f in files_without_format:
            self._show_format_dialog_for(f)
        RideSavingDatafile(datafile=datafile).publish()
        saved = self._application.save(datafile)
        self._report_saved_files(saved)
        self.tree.unset_dirty()

    def _show_format_dialog_for(self, file_without_format):
        help = 'Please provide format of initialization file for directory suite\n"%s".' %\
                file_without_format.source
        dlg = ChangeFormatDialog(self, 'HTML', help_text=help)
        if dlg.ShowModal() == wx.ID_OK:
            file_without_format.set_format(dlg.get_format())
        dlg.Destroy()

    def _report_saved_files(self, saved):
        if not saved:
            return
        RideSavedDatafiles(datafiles=saved).publish()
        s = len(saved) > 1 and 's' or ''
        self.SetStatusText('Wrote file%s: %s' %
                          (s, ', '.join(item.source for item in saved)))

    def OnExit(self, event):
        self.Close()
        event.Skip()

    # Edit Menu
    #FIXME: How these should be handled? We should have one active component
    #always like tree, tab, etc.. -> plugin interface should have abstract
    #methods for handling the events.

    def OnCut(self, event):
        self._editor_panel.handle_event('cut')

    def OnCopy(self, event):
        self._editor_panel.handle_event('copy')

    def OnPaste(self, event):
        self._editor_panel.handle_event('paste')

    def OnDelete(self, event):
        self._editor_panel.handle_event('delete')

    def OnUndo(self, event):
        self._editor_panel.handle_event('undo')

    def OnComment(self, event):
        self._editor_panel.handle_event('comment')
        event.Skip()

    def OnUncomment(self, event):
        self._editor_panel.handle_event('uncomment')
        event.Skip()

    # Tools Menu

    def OnManagePlugins(self, event):
        self._plugin_manager.show(self._application.get_plugins())

    def OnSearchKeywords(self, event):
        if not self._kw_search_dialog.IsShown():
            self._kw_search_dialog.Show()

    # Navigate Menu

    def OnGoBack(self, event):
        self.tree.go_back()

    def OnGoForward(self, event):
        self.tree.go_forward()

    # About Menu

    def OnAbout(self, event):
        dlg = AboutDialog(self)
        dlg.ShowModal()
        dlg.Destroy()

class NoteBook(fnb.FlatNotebook):

    def __init__(self, parent, app):
        self._app = app
        style = fnb.FNB_NODRAG|fnb.FNB_HIDE_ON_SINGLE_TAB|fnb.FNB_VC8
        fnb.FlatNotebook.__init__(self, parent, style=style)
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnPageClosing)
        self._page_closing = False

    def OnPageClosing(self, event):
        self._page_closing = True

    def OnPageChanging(self, event):
        if not self._page_changed():
            self._page_closing = False
            return
        oldtitle = self.GetPageText(event.GetOldSelection())
        newindex = event.GetSelection()
        if newindex <= self.GetPageCount() - 1:
            newtitle = self.GetPageText(event.GetSelection())
        else:
            newtitle = None
        RideNotebookTabchange(oldtab=oldtitle, newtab=newtitle).publish()

    def _page_changed(self):
        """Change event is send even when no tab available or tab is closed"""
        if not self.GetPageCount() or self._page_closing:
            return False
        return True
<commit_msg>setting focus helps to decide active container with menu entries/shortcuts<commit_after>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import wx
try:
    from wx.lib.agw import flatnotebook as fnb
except ImportError:
    from wx.lib import flatnotebook as fnb

from robotide.editors import RideEventHandler
from robotide.errors import PluginPageNotFoundError
from robotide.publish import RideNotebookTabchange, RideSavingDatafile,\
                           RideSavedDatafiles
from robotide import utils
from robotide import context

from actions import Actions
from dialogs import KeywordSearchDialog, AboutDialog
from filedialogs import NewProjectDialog, NewResourceDialog, ChangeFormatDialog
from pluginmanager import PluginManager
from suitetree import SuiteTree

class RideFrame(wx.Frame, RideEventHandler, utils.OnScreenEnsuringFrame):

    def __init__(self, application, keyword_filter):
        wx.Frame.__init__(self, None, -1, 'RIDE',
                          pos=context.SETTINGS["mainframe position"],
                          size=context.SETTINGS["mainframe size"])
        self._application = application
        self._create_decorations()
        self.ensure_on_screen()
        self._create_containers()
        self._plugin_manager = PluginManager(self.notebook)
        self._kw_search_dialog = KeywordSearchDialog(self, keyword_filter)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Show()

    def _create_containers(self):
        splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)
        # for now, hide the tabs if there's only one. Until there are
        # at least two tabs there's no point in taking up the screen
        # real estate. Eventually this should be a user preference.
        self.notebook = NoteBook(splitter, self._application)
        self.tree = SuiteTree(splitter) #, self._editor_panel)
        splitter.SplitVertically(self.tree, self.notebook, 300)

    def _create_decorations(self):
        # We need to define some standard toolbar buttons. For
        # now, create an empty toolbar so plugins have a place to
        # put their buttons.
        actions = Actions(self)
        self.SetMenuBar(actions.get_menubar())
        self.SetToolBar(actions.get_toolbar())
        self.CreateStatusBar()

    def populate_tree(self, model):
        self.tree.populate_tree(model)

    def show_page(self, panel):
        """Shows the notebook page that contains the given panel.

        Throws a PluginPageNotFoundError exception if the page can't be found.
        """
        if self.notebook.GetCurrentPage() != panel:
            page = self.notebook.GetPageIndex(panel)
            if page >= 0:
                self.notebook.SetSelection(page)
            else:
                raise PluginPageNotFoundError("unable to find a notebook page for the given panel")

    def delete_page(self, panel):
        page = self.notebook.GetPageIndex(panel)
        self.notebook.DeletePage(page)

    def _get_active_item(self):
        return self.tree.get_active_item()

    def OnClose(self, event):
        self._save_mainframe_size_and_position()
        if self._application.ok_to_exit():
            self.Destroy()
        else:
            wx.CloseEvent.Veto(event)

    def _save_mainframe_size_and_position(self):
        context.SETTINGS["mainframe size"] = self.GetSizeTuple()
        context.SETTINGS["mainframe position"] = self.GetPositionTuple()

    #File Menu

    def OnNewSuite(self, event):
        if not self._application.ok_to_open_new():
            return
        dlg = NewProjectDialog(self, self._default_dir)
        if dlg.ShowModal() == wx.ID_OK:
            dirname = os.path.dirname(dlg.get_path())
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            self._default_dir = dirname
            self._application.open_suite(dlg.get_path())
            self.tree.populate_tree(self._application.model)
        dlg.Destroy()

    # TODO: Are properties ok in here? Settings are saved when frame is closed.
    def _set_default_dir(self, dirname):
        context.SETTINGS["default directory"] = dirname

    def _get_default_dir(self):
        return os.path.abspath(context.SETTINGS["default directory"])

    _default_dir = property(_get_default_dir, _set_default_dir)

    def OnNewResource(self, event):
        dlg = NewResourceDialog(self, self._default_dir)
        if dlg.ShowModal() == wx.ID_OK:
            self._default_dir = os.path.dirname(dlg.get_path())
            self._application.open_resource(dlg.get_path())
        dlg.Destroy()

    def OnOpen(self, event):
        if not self._application.ok_to_open_new():
            return
        path = self._get_path()
        if path:
            self.open_suite(path)

    def OnOpenResource(self, event):
        path = self._get_path()
        if path:
            self._application.open_resource(path)

    def _get_path(self):
        wildcard = ('All files|*.*|Robot data (*.html)|*.*htm*|'
                    'Robot data (*.tsv)|*.tsv|Robot data (*txt)|*.txt')
        dlg = wx.FileDialog(self, message='Open', wildcard=wildcard,
                            defaultDir=self._default_dir, style=wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self._default_dir = os.path.dirname(path)
        else:
            path = None
        dlg.Destroy()
        return path

    def open_suite(self, path):
        self._application.open_suite(path)
        self.tree.populate_tree(self._application.model)

    def OnOpenDirectory(self, event):
        if not self._application.ok_to_open_new():
            return
        path = wx.DirSelector(message='Choose a directory containing Robot files',
                              defaultPath=self._default_dir)
        if path:
            self._default_dir = os.path.dirname(path)
            self.open_suite(path)
        event.Skip()

    def OnSave(self, event):
        self._save(self._get_active_item())

    def OnSaveAll(self, event):
        self._save()

    def _save(self, datafile=None):
        files_without_format = self._application.get_files_without_format(datafile)
        for f in files_without_format:
            self._show_format_dialog_for(f)
        RideSavingDatafile(datafile=datafile).publish()
        saved = self._application.save(datafile)
        self._report_saved_files(saved)
        self.tree.unset_dirty()

    def _show_format_dialog_for(self, file_without_format):
        help = 'Please provide format of initialization file for directory suite\n"%s".' %\
                file_without_format.source
        dlg = ChangeFormatDialog(self, 'HTML', help_text=help)
        if dlg.ShowModal() == wx.ID_OK:
            file_without_format.set_format(dlg.get_format())
        dlg.Destroy()

    def _report_saved_files(self, saved):
        if not saved:
            return
        RideSavedDatafiles(datafiles=saved).publish()
        s = len(saved) > 1 and 's' or ''
        self.SetStatusText('Wrote file%s: %s' %
                          (s, ', '.join(item.source for item in saved)))

    def OnExit(self, event):
        self.Close()
        event.Skip()

    # Edit Menu
    #FIXME: How these should be handled? We should have one active component
    #always like tree, tab, etc.. -> plugin interface should have abstract
    #methods for handling the events.

    def OnCut(self, event):
        self._editor_panel.handle_event('cut')

    def OnCopy(self, event):
        self._editor_panel.handle_event('copy')

    def OnPaste(self, event):
        self._editor_panel.handle_event('paste')

    def OnDelete(self, event):
        self._editor_panel.handle_event('delete')

    def OnUndo(self, event):
        self._editor_panel.handle_event('undo')

    def OnComment(self, event):
        self._editor_panel.handle_event('comment')
        event.Skip()

    def OnUncomment(self, event):
        self._editor_panel.handle_event('uncomment')
        event.Skip()

    # Tools Menu

    def OnManagePlugins(self, event):
        self._plugin_manager.show(self._application.get_plugins())

    def OnSearchKeywords(self, event):
        if not self._kw_search_dialog.IsShown():
            self._kw_search_dialog.Show()

    # Navigate Menu

    def OnGoBack(self, event):
        self.tree.go_back()

    def OnGoForward(self, event):
        self.tree.go_forward()

    # About Menu

    def OnAbout(self, event):
        dlg = AboutDialog(self)
        dlg.ShowModal()
        dlg.Destroy()

class NoteBook(fnb.FlatNotebook):

    def __init__(self, parent, app):
        self._app = app
        style = fnb.FNB_NODRAG|fnb.FNB_HIDE_ON_SINGLE_TAB|fnb.FNB_VC8
        fnb.FlatNotebook.__init__(self, parent, style=style)
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnPageClosing)
        self._page_closing = False

    def OnPageClosing(self, event):
        self._page_closing = True

    def OnPageChanging(self, event):
        if not self._page_changed():
            self._page_closing = False
            return
        oldtitle = self.GetPageText(event.GetOldSelection())
        newindex = event.GetSelection()
        if newindex <= self.GetPageCount() - 1:
            newtitle = self.GetPageText(event.GetSelection())
            self.GetPage(event.GetSelection()).SetFocus()
        else:
            newtitle = None
        RideNotebookTabchange(oldtab=oldtitle, newtab=newtitle).publish()

    def _page_changed(self):
        """Change event is send even when no tab available or tab is closed"""
        if not self.GetPageCount() or self._page_closing:
            return False
        return True
<|endoftext|>


<commit_before>import datetime
import logging
import os
import shutil

from azure.storage.file import FileService

from exporters.bypasses.s3_bypass_state import S3BypassState
from exporters.default_retries import retry_long
from exporters.export_formatter.json_export_formatter import JsonExportFormatter
from exporters.export_managers.base_bypass import RequisitesNotMet, BaseBypass
from exporters.readers.s3_reader import get_bucket
from exporters.utils import TmpFile
from exporters.writers.azure_file_writer import AzureFileWriter

class AzureFileS3Bypass(BaseBypass):
    """
    Bypass executed by default when data source is an S3 bucket and data destination is an Azure share.
    It should be transparent to user. Conditions are:

        - S3Reader and AzureFileWriter are used on configuration.
        - No filter modules are set up.
        - No transform module is set up.
        - No grouper module is set up.
        - AzureFileWriter has not a items_limit set in configuration.
        - AzureFileWriter has default items_per_buffer_write and size_per_buffer_write per default.
    """

    def __init__(self, config, metadata):
        super(AzureFileS3Bypass, self).__init__(config, metadata)
        self.tmp_folder = None
        self.bypass_state = None
        self.logger = logging.getLogger('bypass_logger')
        self.logger.setLevel(logging.INFO)

    def _raise_conditions_not_met(self, reason):
        self.logger.warning('Skipping Azure file copy optimization bypass because of %s' % reason)
        raise RequisitesNotMet

    def meets_conditions(self):
        if not self.config.reader_options['name'].endswith('S3Reader') or not self.config.writer_options['name'].endswith('AzureFileWriter'):
            raise RequisitesNotMet
        if not self.config.filter_before_options['name'].endswith('NoFilter'):
            self._raise_conditions_not_met('custom filter configured')
        if not self.config.filter_after_options['name'].endswith('NoFilter'):
            self._raise_conditions_not_met('custom filter configured')
        if not self.config.transform_options['name'].endswith('NoTransform'):
            self._raise_conditions_not_met('custom transform configured')
        if not self.config.grouper_options['name'].endswith('NoGrouper'):
            self._raise_conditions_not_met('custom grouper configured')
        if self.config.writer_options['options'].get('items_limit'):
            self._raise_conditions_not_met('items limit configuration (items_limit)')
        if self.config.writer_options['options'].get('items_per_buffer_write'):
            self._raise_conditions_not_met('buffer limit configuration (items_per_buffer_write)')
        if self.config.writer_options['options'].get('size_per_buffer_write'):
            self._raise_conditions_not_met('buffer limit configuration (size_per_buffer_write)')

    def _get_filebase(self, writer_options):
        dest_filebase = writer_options['filebase'].format(datetime.datetime.now())
        dest_filebase = datetime.datetime.now().strftime(dest_filebase)
        return dest_filebase

    def _fill_config_with_env(self):
        if 'aws_access_key_id' not in self.config.reader_options['options']:
            self.config.reader_options['options']['aws_access_key_id'] = os.environ.get('EXPORTERS_S3READER_AWS_KEY')
        if 'aws_secret_access_key' not in self.config.reader_options['options']:
            self.config.reader_options['options']['aws_secret_access_key'] = os.environ.get('EXPORTERS_S3READER_AWS_SECRET')

    def bypass(self):
        from copy import deepcopy
        reader_options = self.config.reader_options['options']
        writer_options = self.config.writer_options['options']
        self.share = writer_options['share']
        self.filebase = self.create_filebase_name(writer_options['filebase'])
        self.azure_service = FileService(writer_options['account_name'], writer_options['account_key'])
        self._fill_config_with_env()
        self.bypass_state = S3BypassState(self.config, self.metadata)
        self.total_items = self.bypass_state.stats['total_count']
        source_bucket = get_bucket(**reader_options)
        pending_keys = deepcopy(self.bypass_state.pending_keys())
        try:
            for key in pending_keys:
                self._copy_key(source_bucket, key)
                self.bypass_state.commit_copied_key(key)
                logging.log(logging.INFO,
                            'Copied key {}'.format(key.name))
        finally:
            if self.tmp_folder:
                shutil.rmtree(self.tmp_folder)

    def create_filebase_name(self, filebase):
        formatted_filebase = datetime.datetime.now().strftime(filebase)
        filebase_path, prefix = os.path.split(formatted_filebase)
        return filebase_path

    def _ensure_path(self, filebase):
        path = filebase.split('/')
        folders_added = []
        for sub_path in path:
            folders_added.append(sub_path)
            parent = '/'.join(folders_added)
            self.azure_service.create_directory(
                    self.share,
                    parent,
            )

    @retry_long
    def _copy_key(self, source_bucket, key_name):
        akey = source_bucket.get_key(key_name)
        if akey.get_metadata('total'):
            self.increment_items(int(akey.get_metadata('total')))
            self.bypass_state.increment_items(int(akey.get_metadata('total')))
        else:
            self.valid_total_count = False
        key = source_bucket.get_key(key_name)
        with TmpFile() as tmp_filename:
            file_name = key_name.split('/')[-1]
            key.get_contents_to_filename(tmp_filename)
            self._ensure_path(self.filebase)
            self.azure_service.put_file_from_path(
                self.share,
                self.filebase,
                file_name,
                tmp_filename,
                max_connections=5,
            )

    def close(self):
        self.bypass_state.delete()
<commit_msg>Fix logging<commit_after>import datetime
import logging
import os
import shutil

from azure.storage.file import FileService

from exporters.bypasses.s3_bypass_state import S3BypassState
from exporters.default_retries import retry_long
from exporters.export_formatter.json_export_formatter import JsonExportFormatter
from exporters.export_managers.base_bypass import RequisitesNotMet, BaseBypass
from exporters.readers.s3_reader import get_bucket
from exporters.utils import TmpFile
from exporters.writers.azure_file_writer import AzureFileWriter

class AzureFileS3Bypass(BaseBypass):
    """
    Bypass executed by default when data source is an S3 bucket and data destination is an Azure share.
    It should be transparent to user. Conditions are:

        - S3Reader and AzureFileWriter are used on configuration.
        - No filter modules are set up.
        - No transform module is set up.
        - No grouper module is set up.
        - AzureFileWriter has not a items_limit set in configuration.
        - AzureFileWriter has default items_per_buffer_write and size_per_buffer_write per default.
    """

    def __init__(self, config, metadata):
        super(AzureFileS3Bypass, self).__init__(config, metadata)
        self.tmp_folder = None
        self.bypass_state = None
        self.logger = logging.getLogger('bypass_logger')
        self.logger.setLevel(logging.INFO)

    def _raise_conditions_not_met(self, reason):
        self.logger.warning('Skipping Azure file copy optimization bypass because of %s' % reason)
        raise RequisitesNotMet

    def meets_conditions(self):
        if not self.config.reader_options['name'].endswith('S3Reader') or not self.config.writer_options['name'].endswith('AzureFileWriter'):
            raise RequisitesNotMet
        if not self.config.filter_before_options['name'].endswith('NoFilter'):
            self._raise_conditions_not_met('custom filter configured')
        if not self.config.filter_after_options['name'].endswith('NoFilter'):
            self._raise_conditions_not_met('custom filter configured')
        if not self.config.transform_options['name'].endswith('NoTransform'):
            self._raise_conditions_not_met('custom transform configured')
        if not self.config.grouper_options['name'].endswith('NoGrouper'):
            self._raise_conditions_not_met('custom grouper configured')
        if self.config.writer_options['options'].get('items_limit'):
            self._raise_conditions_not_met('items limit configuration (items_limit)')
        if self.config.writer_options['options'].get('items_per_buffer_write'):
            self._raise_conditions_not_met('buffer limit configuration (items_per_buffer_write)')
        if self.config.writer_options['options'].get('size_per_buffer_write'):
            self._raise_conditions_not_met('buffer limit configuration (size_per_buffer_write)')

    def _get_filebase(self, writer_options):
        dest_filebase = writer_options['filebase'].format(datetime.datetime.now())
        dest_filebase = datetime.datetime.now().strftime(dest_filebase)
        return dest_filebase

    def _fill_config_with_env(self):
        if 'aws_access_key_id' not in self.config.reader_options['options']:
            self.config.reader_options['options']['aws_access_key_id'] = os.environ.get('EXPORTERS_S3READER_AWS_KEY')
        if 'aws_secret_access_key' not in self.config.reader_options['options']:
            self.config.reader_options['options']['aws_secret_access_key'] = os.environ.get('EXPORTERS_S3READER_AWS_SECRET')

    def bypass(self):
        from copy import deepcopy
        reader_options = self.config.reader_options['options']
        writer_options = self.config.writer_options['options']
        self.share = writer_options['share']
        self.filebase = self.create_filebase_name(writer_options['filebase'])
        self.azure_service = FileService(writer_options['account_name'], writer_options['account_key'])
        self._fill_config_with_env()
        self.bypass_state = S3BypassState(self.config, self.metadata)
        self.total_items = self.bypass_state.stats['total_count']
        source_bucket = get_bucket(**reader_options)
        pending_keys = deepcopy(self.bypass_state.pending_keys())
        try:
            for key in pending_keys:
                self._copy_key(source_bucket, key)
                self.bypass_state.commit_copied_key(key)
                logging.log(logging.INFO,
                            'Copied key {}'.format(key))
        finally:
            if self.tmp_folder:
                shutil.rmtree(self.tmp_folder)

    def create_filebase_name(self, filebase):
        formatted_filebase = datetime.datetime.now().strftime(filebase)
        filebase_path, prefix = os.path.split(formatted_filebase)
        return filebase_path

    def _ensure_path(self, filebase):
        path = filebase.split('/')
        folders_added = []
        for sub_path in path:
            folders_added.append(sub_path)
            parent = '/'.join(folders_added)
            self.azure_service.create_directory(
                    self.share,
                    parent,
            )

    @retry_long
    def _copy_key(self, source_bucket, key_name):
        akey = source_bucket.get_key(key_name)
        if akey.get_metadata('total'):
            self.increment_items(int(akey.get_metadata('total')))
            self.bypass_state.increment_items(int(akey.get_metadata('total')))
        else:
            self.valid_total_count = False
        key = source_bucket.get_key(key_name)
        with TmpFile() as tmp_filename:
            file_name = key_name.split('/')[-1]
            key.get_contents_to_filename(tmp_filename)
            self._ensure_path(self.filebase)
            self.azure_service.put_file_from_path(
                self.share,
                self.filebase,
                file_name,
                tmp_filename,
                max_connections=5,
            )

    def close(self):
        self.bypass_state.delete()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Created on Fri Oct 24 18:14:50 2014

@author: richard

at each time index:
    generate intensity values x,y,z
    where is mozzie x y t
    intensity at x,y,t
    sensor neuron responds to stimulus.
        if it fires, saves the spike in [(time_index, 1)] and
        amplitude control neuron recompute y_targ
    mosquito moves.

"""
import numpy as np
from numpy import pi, sin, cos
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
from matplotlib import cm

flight_dur = 100.0
timestep = 1

BOX_SIZE = (10.0,10.0,1.0)

current_time_index = -1

class Plume(object):
    def __init__(self, time = 0):
        """Our odor plume in x,y, z
        Currenty 0 everywhere at all timesteps
        TODO: feed plume a time parameter, which then calcs all the intensities
        """
        self.res = 100.0      #Split into 100 straight segments
        self.X = np.linspace(0, BOX_SIZE[0], self.res) #X locs of plume
        self.Y = np.linspace(0, BOX_SIZE[1],self.res) #Y of odor slices
        self.xx, self.yy = np.meshgrid(self.X, self.Y, sparse=True)
        #self.source = list(source) #Y/Z of the source
        #self.original = source #Initial source location
        #self.cross = np.zeros((2, len(self.X)))
    def current_plume(self,curr_time): #uses current time, not index
        """given the timeindex, return plume intensity values
        currently always returns 0
        input curr_time
        output plume at that frame
        TODO: make vary over time"""
        self.zz = 0 * (self.xx + self.yy) # odor intensity at x,y, set to 0 everywhere
        plume_curr = self.xx, self.yy, self.zz
        return plume_curr
    def intensity_val(self, plume_curr, location):
        """
        given a plume at a certain frame and x,y coords, give intensity at that coord
        input plume, (x,y) coords
        output: plume intensity at x,y
        """
        x, y = location
        intensitygrid = plume_curr[2]
        return intensitygrid[x][y]

class Mozzie(object):
    """our brave mosquito
    """
    def __init__(self):
        self.pos =  0, 0
        self.loc_history = []
    def where(self, time):
        """ where the mozzie is right now
        input: time in seconds
        output: x,y coords
        TODO: make real"""
        return self.pos
    def move(self,time):
        """move the mosquito in a cast, add to location history
        input: time in secs
        output: none (location history updates)
        TODO: put in sin equations
        """
        self.loc_history.append(time,self.pos)
    # def _xspeedcalc

class Neuron(object):
    def __init__(self, tau_e = 1.2, spikethresh = 3.0):
        self.voltage_history = []
        self.spike_history = []
        self.spiketime_index = []
        #if spiking, return true

class Sensor_neuron(Neuron):
    def __init__(self):
        pass
    def spiker(self,time, intensity_now):
        '''evaluator leaky integrate and fire neuron. stimulus intensity -> cellular voltages -> spikes

        TODO: feed in intensities
        '''
        if len(self.voltage_history) == 0:
            self.voltage_history.append(0)
           # spike_history.append(0)
        else:
            if self.voltage_history[-1] > spikethresh: #crossing threshold discharges neuron
                self.voltage_history.append(0)
                self.spike_history.append(0)
            else:
                self.voltage = (1/tau_e) * self.voltage_history[-1] + intensity_now #intensity at this timestep + weighted past intensity
                self.voltage_history.append(self.voltage)
                if self.voltage > spikethresh:
                    self.spike_history.append(1)
                else:
                    self.spike_history.append(0)
        for timepoint, value in enumerate(self.spike_history):
            if value == 1:
                spiketime_index.append(timepoint)

def sensor_neuron_old(tau_e = 1.2, spikethresh = 3.0, plotting = 'off'):
    voltages = []
    spikes = []
    time = 0
    for intensity in intensities: #TODO change to for time_curr in times:
        if len(voltages) == 0:
            voltages.append(0)
            spikes.append(0)
        else:
            if voltages[-1] > spikethresh: #crossing threshold discharges neuron
                voltages.append(0)
                spikes.append(0)
            else:
                voltage = (1/tau_e) * voltages[-1] + intensity #intensity at this timestep + weighted past intensity
                voltages.append(voltage)
                if voltage > spikethresh:
                    spikes.append(1)
                else:
                    spikes.append(0)
        time += 1
    if plotting == 'on':
        sensor_neuron_plotter(spikes, voltages)
    for timepoint, value in enumerate(spikes):
        if value == 1:
            spiketime_index.append(timepoint)
    return

#def agentflight(total_velo_max = 5, total_velo_min = 1, wind_velo = 0, y_offset_curr = 0, angular_velo = 0.1, tau_y = 1, plotting = 'off'):
#    """
#    plots the mosquito's path in space
#    input: total_velo_max, total_velo_min, wind_velo, y_offset_curr, angular_velo, flight_dur, timestep
#    output: times, agent_y_pos, x_velocities, y_velocities
#    TODO: impliment agent_x_pos using velocity max and min
#    TODO: implement y offset, and wind velocity
#    TODO: make agent_pos list where each item is an (x,y) coord
#    TODO: make sensor_neuron control agent flight
#    """
#    amplitude_max = 10 # TODO: impliment the amplitude fxn
#    agent_y_pos = []
#    y_velocities = []
#    x_velocities = []
#    for time_curr in times:
#        y_pos_curr = amplitude_max * sin (angular_velo * time_curr) #+ y_offset_curr #disabled
#        agent_y_pos.append(y_pos_curr)
#        y_offset_prev = y_offset_curr #test this with print statements
#        if time_curr == 0:
#            time_prev = 0
#            y_pos_prev = 0
#            time_index = 0
#        y_velocity = (y_pos_curr - y_pos_prev) / timestep
#        y_velocities.append(y_velocity)
#        ## TODO: make x_velocities as in Sharri's
#        x_velocities.append((time_curr - time_prev)/ timestep)
#        if time_index in spiketime_index:         # if we spiked at this time_curr, set y_aim = y_post_cur
#            y_aim = y_pos_curr
#            y_offset_curr = (y_aim - y_offset_prev) / tau_y
#        time_prev = time_curr
#        y_pos_prev = y_pos_curr
#        time_index += 1
#    if plotting == "on":
#        agentflightplotter(agent_y_pos, x_velocities, y_velocities)
#    return times, agent_y_pos, x_velocities, y_velocities

#def agentflightplotter(agent_y_pos, x_velocities, y_velocities):
#    """
#    TODO: animate this, using def update_mozzie and FuncAnimation
#    """
#    fig = plt.figure(2)
#    plot(times,agent_y_pos,'k',label= 'agent y_pos over time' )
#    plot(times,y_velocities, 'b',label= 'y velocity')
#    plot(times,x_velocities, 'r',label= 'x velocity')
#    xlabel('time')
#    ylabel('Y position')
#    legend()
#    title("Flying mosquito")
#    plt.show()

def plume_plotter(plume, plotting = False):
    if plotting == False:
        pass
    else:
        # Set up a figure
        fig = plt.figure(0, figsize=(6,6))
        ax = axes3d.Axes3D(fig)
        x, y, z = plume.xx, plume.yy, plume.zz
        ax.plot_wireframe(x , y , z, rstride=10, cstride=10)
        ax.set_xlim3d([0.0, BOX_SIZE[0]])
        ax.set_ylim3d([0.0, BOX_SIZE[1]])
        ax.set_zlim3d([0.0, BOX_SIZE[2]])
        ax.set_xlabel('X')
        ax.set_ylabel('Y')
        ax.set_zlabel('intensity')
        ax.set_title("robomozzie")
        plt.show()

def timestepper():
    times = np.arange(0, flight_dur, timestep)
    time_indexes = list(enumerate(times))
    for time in time_indexes:
        plume_curr = plume.current_plume(time[1]) #intensity value of plume at this time
        loc = mozzie.where(time[1])
        intensity_now = plume.intensity_val(plume_curr,loc)
        if sensor_neuron.spiker(time[1], intensity_now) == True: #if sensor neuron spikes
            amplitude_neuron(time[1])
        mozzie.move(time[1])

if __name__ == "__main__":
    plume = Plume()
    sensor_neuron = Sensor_neuron()
    amplitude_neuron = Neuron()
    mozzie = Mozzie()
    timestepper()
    plume_plotter(plume, plotting = False)
#    agentflightplotter() <commit_msg>fixed self errors<commit_after># -*- coding: utf-8 -*-
"""
Created on Fri Oct 24 18:14:50 2014

@author: richard

at each time index:
    generate intensity values x,y,z
    where is mozzie x y t
    intensity at x,y,t
    sensor neuron responds to stimulus.
        if it fires, saves the spike in [(time_index, 1)] and
        amplitude control neuron recompute y_targ
    mosquito moves.

"""
import numpy as np
from numpy import pi, sin, cos
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
from matplotlib import cm

flight_dur = 100.0
timestep = 1

BOX_SIZE = (10.0,10.0,1.0)

current_time_index = -1

class Plume(object):
    def __init__(self, time = 0):
        """Our odor plume in x,y, z
        Currenty 0 everywhere at all timesteps
        TODO: feed plume a time parameter, which then calcs all the intensities
        """
        self.res = 100.0      #Split into 100 straight segments
        self.X = np.linspace(0, BOX_SIZE[0], self.res) #X locs of plume
        self.Y = np.linspace(0, BOX_SIZE[1],self.res) #Y of odor slices
        self.xx, self.yy = np.meshgrid(self.X, self.Y, sparse=True)
        #self.source = list(source) #Y/Z of the source
        #self.original = source #Initial source location
        #self.cross = np.zeros((2, len(self.X)))
    def current_plume(self,curr_time): #uses current time, not index
        """given the timeindex, return plume intensity values
        currently always returns 0
        input curr_time
        output plume at that frame
        TODO: make vary over time"""
        self.zz = 0 * (self.xx + self.yy) # odor intensity at x,y, set to 0 everywhere
        plume_curr = self.xx, self.yy, self.zz
        return plume_curr
    def intensity_val(self, plume_curr, location):
        """
        given a plume at a certain frame and x,y coords, give intensity at that coord
        input plume, (x,y) coords
        output: plume intensity at x,y
        """
        x, y = location
        intensitygrid = plume_curr[2]
        return intensitygrid[x][y]

class Mozzie(object):
    """our brave mosquito
    """
    def __init__(self):
        self.pos =  0, 0
        self.loc_history = []
    def where(self, time):
        """ where the mozzie is right now
        input: time in seconds
        output: x,y coords
        TODO: make real"""
        return self.pos
    def move(self,time):
        """move the mosquito in a cast, add to location history
        input: time in secs
        output: none (location history updates)
        TODO: put in sin equations
        """
        self.loc_history.append((time,self.pos))
    # def _xspeedcalc

class Neuron(object):
    def __init__(self, tau_e = 1.2, spikethresh = 3.0):
        self.spikethresh = spikethresh
        self.tau_e = tau_e
        self.voltage_history = []
        self.spike_history = []
        self.spiketime_index = []
        #if spiking, return true

class Sensor_neuron(Neuron):
    def spiker(self,time, intensity_now):
        '''evaluator leaky integrate and fire neuron. stimulus intensity -> cellular voltages -> spikes

        TODO: feed in intensities
        '''
        if len(self.voltage_history) == 0:
            self.voltage_history.append(0)
           # spike_history.append(0)
        else:
            if self.voltage_history[-1] > self.spikethresh: #crossing threshold discharges neuron
                self.voltage_history.append(0)
                self.spike_history.append(0)
            else:
                self.voltage = (1/self.tau_e) * self.voltage_history[-1] + intensity_now #intensity at this timestep + weighted past intensity
                self.voltage_history.append(self.voltage)
                if self.voltage > self.spikethresh:
                    self.spike_history.append(1)
                else:
                    self.spike_history.append(0)
        for timepoint, value in enumerate(self.spike_history):
            if value == 1:
                spiketime_index.append(timepoint)

def sensor_neuron_old(tau_e = 1.2, spikethresh = 3.0, plotting = 'off'):
    voltages = []
    spikes = []
    time = 0
    for intensity in intensities: #TODO change to for time_curr in times:
        if len(voltages) == 0:
            voltages.append(0)
            spikes.append(0)
        else:
            if voltages[-1] > spikethresh: #crossing threshold discharges neuron
                voltages.append(0)
                spikes.append(0)
            else:
                voltage = (1/tau_e) * voltages[-1] + intensity #intensity at this timestep + weighted past intensity
                voltages.append(voltage)
                if voltage > spikethresh:
                    spikes.append(1)
                else:
                    spikes.append(0)
        time += 1
    if plotting == 'on':
        sensor_neuron_plotter(spikes, voltages)
    for timepoint, value in enumerate(spikes):
        if value == 1:
            spiketime_index.append(timepoint)
    return

#def agentflight(total_velo_max = 5, total_velo_min = 1, wind_velo = 0, y_offset_curr = 0, angular_velo = 0.1, tau_y = 1, plotting = 'off'):
#    """
#    plots the mosquito's path in space
#    input: total_velo_max, total_velo_min, wind_velo, y_offset_curr, angular_velo, flight_dur, timestep
#    output: times, agent_y_pos, x_velocities, y_velocities
#    TODO: impliment agent_x_pos using velocity max and min
#    TODO: implement y offset, and wind velocity
#    TODO: make agent_pos list where each item is an (x,y) coord
#    TODO: make sensor_neuron control agent flight
#    """
#    amplitude_max = 10 # TODO: impliment the amplitude fxn
#    agent_y_pos = []
#    y_velocities = []
#    x_velocities = []
#    for time_curr in times:
#        y_pos_curr = amplitude_max * sin (angular_velo * time_curr) #+ y_offset_curr #disabled
#        agent_y_pos.append(y_pos_curr)
#        y_offset_prev = y_offset_curr #test this with print statements
#        if time_curr == 0:
#            time_prev = 0
#            y_pos_prev = 0
#            time_index = 0
#        y_velocity = (y_pos_curr - y_pos_prev) / timestep
#        y_velocities.append(y_velocity)
#        ## TODO: make x_velocities as in Sharri's
#        x_velocities.append((time_curr - time_prev)/ timestep)
#        if time_index in spiketime_index:         # if we spiked at this time_curr, set y_aim = y_post_cur
#            y_aim = y_pos_curr
#            y_offset_curr = (y_aim - y_offset_prev) / tau_y
#        time_prev = time_curr
#        y_pos_prev = y_pos_curr
#        time_index += 1
#    if plotting == "on":
#        agentflightplotter(agent_y_pos, x_velocities, y_velocities)
#    return times, agent_y_pos, x_velocities, y_velocities

#def agentflightplotter(agent_y_pos, x_velocities, y_velocities):
#    """
#    TODO: animate this, using def update_mozzie and FuncAnimation
#    """
#    fig = plt.figure(2)
#    plot(times,agent_y_pos,'k',label= 'agent y_pos over time' )
#    plot(times,y_velocities, 'b',label= 'y velocity')
#    plot(times,x_velocities, 'r',label= 'x velocity')
#    xlabel('time')
#    ylabel('Y position')
#    legend()
#    title("Flying mosquito")
#    plt.show()

def plume_plotter(plume, plotting = False):
    if plotting == False:
        pass
    else:
        # Set up a figure
        fig = plt.figure(0, figsize=(6,6))
        ax = axes3d.Axes3D(fig)
        x, y, z = plume.xx, plume.yy, plume.zz
        ax.plot_wireframe(x , y , z, rstride=10, cstride=10)
        ax.set_xlim3d([0.0, BOX_SIZE[0]])
        ax.set_ylim3d([0.0, BOX_SIZE[1]])
        ax.set_zlim3d([0.0, BOX_SIZE[2]])
        ax.set_xlabel('X')
        ax.set_ylabel('Y')
        ax.set_zlabel('intensity')
        ax.set_title("robomozzie")
        plt.show()

def timestepper():
    times = np.arange(0, flight_dur, timestep)
    time_indexes = list(enumerate(times))
    for time in time_indexes:
        plume_curr = plume.current_plume(time[1]) #intensity value of plume at this time
        loc = mozzie.where(time[1])
        intensity_now = plume.intensity_val(plume_curr,loc)
        if sensor_neuron.spiker(time[1], intensity_now) == True: #if sensor neuron spikes
            amplitude_neuron(time[1])
        mozzie.move(time[1])

if __name__ == "__main__":
    plume = Plume()
    sensor_neuron = Sensor_neuron()
    amplitude_neuron = Neuron()
    mozzie = Mozzie()
    timestepper()
    plume_plotter(plume, plotting = False)
#    agentflightplotter() <|endoftext|>


<commit_before>from __future__ import print_function

from util import *
import nbtencoder as nbt

import re
import argparse
import sys, os

cprintconf.name = "Generator"
cprintconf.color = bcolors.PEACH

parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mode", help="Choose activation mode for system", dest="mode", default="", choices=["m", "i"])
parser.add_argument("-f", "--command_file", help="File to load commands from", dest="filepath",
	default=None)
parser.add_argument("-C", "--no-copy", help="Don't copy the output command", dest="nocopy", action="store_true")
parser.add_argument("-q", "--quiet", help="Silence output", dest="quiet", action="store_true")
parser.add_argument("-v", "--verbose", help="Detailed output", dest="loud", action="store_true")
parser.add_argument("-O", "--no-output", help="Don't dump cmd to STDOUT", dest="nostdout", action="store_true")

class Command:
	def __init__(self, cmd, init=False, conditional=False, variables=[]):
		self.cmd = cmd
		self.cond = conditional
		self.init = init
		for i in variables:
			self.cmd = i.sub(self.cmd)
	def __str__(self):
		return self.cmd
	def prettystr(self):
		return format("{cmd}{init}{cond}",
			cmd = self.cmd,
			init = "\n  - Initialization" if self.init else "",
			cond = "\n  - Conditional" if self.cond else "")

class CmdVariable:
	def __init__(self, name, replacewith):
		self.name = name
		self.replacewith = replacewith
		self.regex = re.compile("\\$"+name.lower()+"\\b", re.IGNORECASE)
	def sub(self, string):
		return self.regex.sub(self.replacewith, string)

def generate_sand(command_obj, direction, block="chain_command_block"):
	tag = {
		"Block": block,
		"Time": 1,
		"TileEntityData": {
			"Command": str(command_obj),
			"TrackOutput": nbt.int_b(0)
		},
		"id": "FallingSand"
	}
	data = direction+8 if command_obj.cond else direction
	if data:
		tag["Data"] = data
	return tag

def normal_sand(block, data=0):
	tag = {
		"Block": block,
		"Time": 1,
		"id": "FallingSand"
	}
	if data:
		tag["Data"] = data
	return tag

def gen_stack(init_commands, clock_commands, mode, loud=False):
	final_command_obj = None
	if clock_commands or init_commands:
		command_sands = []

		for command in init_commands:
			if loud:
				cprint(command.prettystr())
			if command is init_commands[0]:
				topsand = generate_sand(command, 0, "command_block")
				topsand["TileEntityData"]["auto"] = 1
				command_sands.append(topsand)
			else:
				command_sands.append(generate_sand(command, 0))

		if mode == 'i' and clock_commands:
			block = "command_block" if not init_commands else "chain_command_block"
			offset = len(clock_commands) + 2
			blockdata = Command(format("blockdata ~ ~-{offset} ~ {auto:1b}", offset = offset), init=True)
			if loud:
				cprint(blockdata.prettystr())
			sand = generate_sand(blockdata, 0, block)
			if not init_commands:
				sand["TileEntityData"]["auto"] = 1
			command_sands.append(sand)

		offset = len(init_commands) + int(bool(mode == 'i' and clock_commands))
		if offset:
			fill = Command(format("fill ~ ~-1 ~ ~ ~{offset} ~ air", offset = offset), init=True)
			if loud:
				cprint(fill.prettystr())
			command_sands.append(generate_sand(fill, 0))
			command_sands.append(normal_sand("barrier"))

		for command in clock_commands[::-1]:
			if loud:
				cprint(command.prettystr())
			if command is clock_commands[0]:
				command_sands.append(generate_sand(command, 1, "repeating_command_block"))
			else:
				command_sands.append(generate_sand(command, 1))
		final_command_obj = nbt.cmd("summon FallingSand ~ ~1 ~ ", ride(command_sands, False))

	final_command = nbt.JSON2Command(final_command_obj)

	return final_command

def parse_commands(commands):
	init_commands = []
	clock_commands = []
	variables = []
	varnames = []
	# do all INIT and COND checking
	for command in commands:
		command = command.strip().rstrip()
		if not command: continue
		if command[0] == "#":
			continue

		if command.lower()[:7] == "define:":
				command_split = command[7:].split()
				while not command_split[0]:
					command_split = command_split[1:]
				while not command_split[1]:
					command_split = command_split[:1] + command_split[2:]
				if len(command_split) < 2: continue
				name = command_split[0]
				contents = " ".join(command_split[1:])
				for i in variables:
					name = i.sub(name)
					contents = i.sub(contents)

				if name in varnames:
					cprint("WARNING: Duplicate variable {var}. Using first definition.", color=bcolors.YELLOW, var=name)
				else:
					varnames.append(name)
					variables.append(CmdVariable(name, contents))

		init = False
		conditional = False
		while command[:5].lower() in ["init:","cond:"]:
			if command[:5].lower() == "cond:": conditional = True
			elif command[:5].lower() == "init:": init = True
			command = command[5:]
		command = command.strip().rstrip()
		command_obj = Command(command, conditional=conditional, init=init, variables=variables)
		if init:
			init_commands.append(command_obj)
		else:
			clock_commands.append(command_obj)
	return init_commands, clock_commands

def ride(entities, have_id=True):
	topmost = None
	absoluteTopmost = None

	for entity in entities:
		if topmost == None:
			absoluteTopmost = entity
		else:
			topmost["Riding"] = entity
		topmost = entity
	if not have_id: del absoluteTopmost["id"]
	return absoluteTopmost

if __name__ == "__main__":
	args = parser.parse_args()
	if args.quiet:
		def cprint(*args, **kwargs):
			pass

	if args.nocopy:
		class pyperclip:
			@staticmethod
			def copy(*args, **kwargs): pass
			@staticmethod
			def paste(*args, **kwargs): pass
	else:
		import pyperclip

	cprint("""{peach}----------------------------------------{endc}
	  {cyan}TheDestruc7i0n{endc} and {golden}Wire Segal{endc}'s 1.9 One Command Generator
	 {green}Prepend your command with `#` to comment it out.{endc}
	 {green}Prepend your command with `DEFINE:` to make it a variable definition.{endc}
	        Example: `DEFINE:world hello` and `say $world` would say `hello`.
	 {green}Prepend your command with `INIT:` to make it only run when the structure is deployed.{endc}
	 {green}Prepend your command with `COND:` to make it a conditional command.{endc}
	        Please report any bugs at the GitHub repo: {line}{blue}https://github.com/destruc7i0n/OneCommand/issues{endc}
	        {peach}----------------------------------------{endc}""", strip=True)

	# get mode if not specified by argument
	if not args.mode:
		mode = cinput("Manual (m) or Instant (i)? ").strip().rstrip().lower()
		if mode not in ["m", "i"]:
			raise ValueError("Not manual or instant")
	else:
		mode = args.mode

	commands = []
	# get commands if file not specified
	if not args.filepath:
		x = 1
		command = cinput("Command {num}: ", num=x).strip().rstrip()
		while command:
			x += 1
			commands.append(command)
			command = cinput("Command {num}: ", num=x).strip().rstrip()
	# get commands from specified file
	else:
		if os.path.exists(args.filepath):
			commands = open(args.filepath).read().split("\n")
		else:
			raise IOError(format("File {file} not found.", file=args.filepath))

	init_commands, clock_commands = parse_commands(commands)

	final_command = gen_stack(init_commands, clock_commands, mode, args.loud)

	if len(final_command) <= 32500 and final_command:
		pyperclip.copy(final_command)
		if args.nocopy:
			cprint("{bold}Final command{endc}", func=sys.stderr.write)
		else:
			cprint("{bold}Copied to clipboard{endc}", func=sys.stderr.write)
		if not args.nostdout:
			sys.stdout.write(final_command + "\n")
		else:
			sys.stderr.write(format("{bold}.\n{endc}"))
	elif not final_command:
		cprint("No command generated.", color=bcolors.RED)
	else:
		cprint("Command too large ({length} > 32500)", length=len(final_command), color=bcolors.RED)
<commit_msg>fix top INIT: command not triggering<commit_after>from __future__ import print_function

from util import *
import nbtencoder as nbt

import re
import argparse
import sys, os

cprintconf.name = "Generator"
cprintconf.color = bcolors.PEACH

parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mode", help="Choose activation mode for system", dest="mode", default="", choices=["m", "i"])
parser.add_argument("-f", "--command_file", help="File to load commands from", dest="filepath",
	default=None)
parser.add_argument("-C", "--no-copy", help="Don't copy the output command", dest="nocopy", action="store_true")
parser.add_argument("-q", "--quiet", help="Silence output", dest="quiet", action="store_true")
parser.add_argument("-v", "--verbose", help="Detailed output", dest="loud", action="store_true")
parser.add_argument("-O", "--no-output", help="Don't dump cmd to STDOUT", dest="nostdout", action="store_true")

class Command:
	def __init__(self, cmd, init=False, conditional=False, variables=[]):
		self.cmd = cmd
		self.cond = conditional
		self.init = init
		for i in variables:
			self.cmd = i.sub(self.cmd)
	def __str__(self):
		return self.cmd
	def prettystr(self):
		return format("{cmd}{init}{cond}",
			cmd = self.cmd,
			init = "\n  - Initialization" if self.init else "",
			cond = "\n  - Conditional" if self.cond else "")

class CmdVariable:
	def __init__(self, name, replacewith):
		self.name = name
		self.replacewith = replacewith
		self.regex = re.compile("\\$"+name.lower()+"\\b", re.IGNORECASE)
	def sub(self, string):
		return self.regex.sub(self.replacewith, string)

def generate_sand(command_obj, direction, block="chain_command_block"):
	tag = {
		"Block": block,
		"Time": 1,
		"TileEntityData": {
			"Command": str(command_obj),
			"TrackOutput": nbt.int_b(0)
		},
		"id": "FallingSand"
	}
	data = direction+8 if command_obj.cond else direction
	if data:
		tag["Data"] = data
	return tag

def normal_sand(block, data=0):
	tag = {
		"Block": block,
		"Time": 1,
		"id": "FallingSand"
	}
	if data:
		tag["Data"] = data
	return tag

def gen_stack(init_commands, clock_commands, mode, loud=False):
	final_command_obj = None
	if clock_commands or init_commands:
		command_sands = []

		filloffset = len(init_commands) + int(bool(mode == 'i' and clock_commands))
		filloffset += 1*int(bool(filloffset))

		if filloffset:
			sand = normal_sand("command_block")
			sand["TileEntityData"] = {
				"auto": 1
			}
			command_sands.append(sand)

		for command in init_commands:
			if loud:
				cprint(command.prettystr())
			command_sands.append(generate_sand(command, 0))

		if mode == 'i' and clock_commands:
			offset = len(clock_commands) + 2
			blockdata = Command(format("blockdata ~ ~-{offset} ~ {auto:1b}", offset = offset), init=True)
			if loud:
				cprint(blockdata.prettystr())
			sand = generate_sand(blockdata, 0)
			if not init_commands:
				sand["TileEntityData"]["auto"] = 1
			command_sands.append(sand)

		if filloffset:
			fill = Command(format("fill ~ ~-1 ~ ~ ~{offset} ~ air", offset = filloffset), init=True)
			if loud:
				cprint(fill.prettystr())
			command_sands.append(generate_sand(fill, 0))
			command_sands.append(normal_sand("barrier"))

		for command in clock_commands[::-1]:
			if loud:
				cprint(command.prettystr())
			if command is clock_commands[0]:
				command_sands.append(generate_sand(command, 1, "repeating_command_block"))
			else:
				command_sands.append(generate_sand(command, 1))
		final_command_obj = nbt.cmd("summon FallingSand ~ ~1 ~ ", ride(command_sands, False))

	final_command = nbt.JSON2Command(final_command_obj)

	return final_command

def parse_commands(commands):
	init_commands = []
	clock_commands = []
	variables = []
	varnames = []
	# do all INIT and COND checking
	for command in commands:
		command = command.strip().rstrip()
		if not command: continue
		if command[0] == "#":
			continue

		if command.lower()[:7] == "define:":
				command_split = command[7:].split()
				while not command_split[0]:
					command_split = command_split[1:]
				while not command_split[1]:
					command_split = command_split[:1] + command_split[2:]
				if len(command_split) < 2: continue
				name = command_split[0]
				contents = " ".join(command_split[1:])
				for i in variables:
					name = i.sub(name)
					contents = i.sub(contents)

				if name in varnames:
					cprint("WARNING: Duplicate variable {var}. Using first definition.", color=bcolors.YELLOW, var=name)
				else:
					varnames.append(name)
					variables.append(CmdVariable(name, contents))

		init = False
		conditional = False
		while command[:5].lower() in ["init:","cond:"]:
			if command[:5].lower() == "cond:": conditional = True
			elif command[:5].lower() == "init:": init = True
			command = command[5:]
		command = command.strip().rstrip()
		command_obj = Command(command, conditional=conditional, init=init, variables=variables)
		if init:
			init_commands.append(command_obj)
		else:
			clock_commands.append(command_obj)
	return init_commands, clock_commands

def ride(entities, have_id=True):
	topmost = None
	absoluteTopmost = None

	for entity in entities:
		if topmost == None:
			absoluteTopmost = entity
		else:
			topmost["Riding"] = entity
		topmost = entity
	if not have_id: del absoluteTopmost["id"]
	return absoluteTopmost

if __name__ == "__main__":
	args = parser.parse_args()
	if args.quiet:
		def cprint(*args, **kwargs):
			pass

	if args.nocopy:
		class pyperclip:
			@staticmethod
			def copy(*args, **kwargs): pass
			@staticmethod
			def paste(*args, **kwargs): pass
	else:
		import pyperclip

	cprint("""{peach}----------------------------------------{endc}
	  {cyan}TheDestruc7i0n{endc} and {golden}Wire Segal{endc}'s 1.9 One Command Generator
	 {green}Prepend your command with `#` to comment it out.{endc}
	 {green}Prepend your command with `DEFINE:` to make it a variable definition.{endc}
	        Example: `DEFINE:world hello` and `say $world` would say `hello`.
	 {green}Prepend your command with `INIT:` to make it only run when the structure is deployed.{endc}
	 {green}Prepend your command with `COND:` to make it a conditional command.{endc}
	        Please report any bugs at the GitHub repo: {line}{blue}https://github.com/destruc7i0n/OneCommand/issues{endc}
	        {peach}----------------------------------------{endc}""", strip=True)

	# get mode if not specified by argument
	if not args.mode:
		mode = cinput("Manual (m) or Instant (i)? ").strip().rstrip().lower()
		if mode not in ["m", "i"]:
			raise ValueError("Not manual or instant")
	else:
		mode = args.mode

	commands = []
	# get commands if file not specified
	if not args.filepath:
		x = 1
		command = cinput("Command {num}: ", num=x).strip().rstrip()
		while command:
			x += 1
			commands.append(command)
			command = cinput("Command {num}: ", num=x).strip().rstrip()
	# get commands from specified file
	else:
		if os.path.exists(args.filepath):
			commands = open(args.filepath).read().split("\n")
		else:
			raise IOError(format("File {file} not found.", file=args.filepath))

	init_commands, clock_commands = parse_commands(commands)

	final_command = gen_stack(init_commands, clock_commands, mode, args.loud)

	if len(final_command) <= 32500 and final_command:
		pyperclip.copy(final_command)
		if args.nocopy:
			cprint("{bold}Final command{endc}", func=sys.stderr.write)
		else:
			cprint("{bold}Copied to clipboard{endc}", func=sys.stderr.write)
		if not args.nostdout:
			sys.stdout.write(final_command + "\n")
		else:
			sys.stderr.write(format("{bold}.\n{endc}"))
	elif not final_command:
		cprint("No command generated.", color=bcolors.RED)
	else:
		cprint("Command too large ({length} > 32500)", length=len(final_command), color=bcolors.RED)
<|endoftext|>


<commit_before>import os, re, sys, types
sys.path += [os.path.abspath(os.path.dirname(__file__))]
import glob, urllib2
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from xnquery import *

class XNExposedModel(db.Model):
  name = db.StringProperty()
  model_properties = db.StringListProperty()

def expose_model(name, cls):
  exposed_model = XNExposedModel()
  exposed_model.model_properties = cls.properties().keys()
  exposed_model.name = name
  exposed_model.put()

def expose(only=[]):
  loadedfiles = []
  for name, dirs, files in os.walk(os.path.join(__file__, '..', '..')):
    pyfiles = glob.glob('%s/*.py' % name)
    for pyfile in pyfiles:
      pydir, pyfile = os.path.split(pyfile)
      pyfile = os.path.splitext(pyfile)[0]
      if pyfile in ('__init__', 'xn', 'xnquery'): continue
      sys.path += [pydir]
      loadedfiles.append(__import__(pyfile))
      sys.path.remove(pydir)
  if len(only) > 0:
    for model in only:
      if model in sandboxed_globals:
        expose_model(model, sandboxed_globals['model'])
  else:
    for lf in loadedfiles:
      for name in dir(lf):
        obj = getattr(lf, name)
        if type(obj) == type(db.PropertiedClass):
          expose_model(name, obj)

expose()

def retrieve_model_property_list(entity):
  q = db.GqlQuery("SELECT * FROM XNExposedModel WHERE name = 'Car'")#:1", entity)
  return q[0].model_properties

class XNQueryHandler(webapp.RequestHandler):
  def get(self, format, version, query):
    xnquery = XNQueryParser(query, os.environ['QUERY_STRING'])
    self.response.headers['Content-Type'] = 'text/plain'
    #self.response.out.write(repr(expose()))
    #return
    gqlquery = GQLQueryBuilder(xnquery)
    contents = db.GqlQuery(str(gqlquery))
    for content in contents:
      self.response.out.write('$content: %s\n' % repr(content))
    self.response.out.write(retrieve_model_property_list(xnquery.resources.content.selectors.type.rightside))

def main():
  application = webapp.WSGIApplication([('/xn/(.*)/(.*)/(.*)', XNQueryHandler)], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()<commit_msg>ha, it works! basic introspection for models... :)<commit_after>import os, re, sys, types
sys.path += [os.path.abspath(os.path.dirname(__file__))]
import glob, urllib2
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from xnquery import *

class XNExposedModel(db.Model):
  name = db.StringProperty()
  model_properties = db.StringListProperty()

def expose_model(name, cls):
  exposed_model = XNExposedModel()
  exposed_model.model_properties = cls.properties().keys()
  exposed_model.name = name
  exposed_model.put()

def expose(only=[]):
  loadedfiles = []
  ignorelist = [os.path.splitext(os.path.split(f)[1])[0] for f in
                glob.glob(os.path.join(os.path.abspath(os.path.dirname(__file__)), '*.py'))]
  for name, dirs, files in os.walk(os.path.join(__file__, '..', '..')):
    pyfiles = glob.glob('%s/*.py' % name)
    for pyfile in pyfiles:
      pydir, pyfile = os.path.split(pyfile)
      pyfile = os.path.splitext(pyfile)[0]
      if pyfile in ignorelist: continue
      sys.path += [pydir]
      loadedfiles.append(__import__(pyfile))
      sys.path.remove(pydir)
  if len(only) > 0:
    for model in only:
      for lf in loadedfiles:
        if model in dir(lf):
          obj = getattr(lf, model)
          if type(obj) == db.PropertiedClass:
            expose_model(model, obj)
  else:
    for lf in loadedfiles:
      for name in dir(lf):
        obj = getattr(lf, name)
        if type(obj) == db.PropertiedClass:
          expose_model(name, obj)

expose()

def retrieve_model_property_list(entity):
  q = db.GqlQuery("SELECT * FROM XNExposedModel WHERE name = :1", entity)
  return q[0].model_properties

class XNQueryHandler(webapp.RequestHandler):
  def get(self, format, version, query):
    xnquery = XNQueryParser(query, os.environ['QUERY_STRING'])
    self.response.headers['Content-Type'] = 'text/plain'
    gqlquery = GQLQueryBuilder(xnquery)
    objects = db.GqlQuery(str(gqlquery))
    for object in objects:
      self.response.out.write('$object[type=%s]: %s\n' % (xnquery.resources.content.selectors.type.rightside, repr(content)))
    self.response.out.write('[debug] Entity property list: %s.' % repr(retrieve_model_property_list(xnquery.resources.content.selectors.type.rightside)))

def main():
  application = webapp.WSGIApplication([('/xn/(.*)/(.*)/(.*)', XNQueryHandler)], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()<|endoftext|>


<commit_before>import settings
import datetime
import string
import random

from django.db import models
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

from interval.fields import IntervalField

from libs.models import CommonModel

MAX_LENGTH = 255

MEETING = (
    ('Loop', 'Loop Meeting - 2nd Thursday'),
    ('North', 'North Meeting - 3rd Thursday')
)

class Venue(CommonModel):

    def __unicode__(self):
	return self.name

    name = models.CharField(max_length=MAX_LENGTH)
    email = models.EmailField(max_length=MAX_LENGTH,blank=True,null=True)
    phone = models.CharField(max_length=MAX_LENGTH,blank=True,null=True)
    address = models.TextField(blank=True,null=True)

    def get_latitude(self):
        raise NotImplimented

    def get_longitude(self):
        raise NotImplimented

    longitude = property(get_longitude)
    latitude = property(get_latitude)

    @property
    def jsonLatLng(self):
        '''
        Use the string returned as args for google.maps.LatLng constructor.
	'''
        if self.latitude != None and self.longitude != None:
            return "%.6f,%.6f" % (self.latitude,self.longitude)
        else:
            return None

    directions = models.TextField(blank=True,null=True)
    embed_map = models.TextField(blank=True,null=True)
    link = models.URLField(verify_exists=True, blank=True, null=True)

class Meeting(CommonModel):
    def __unicode__(self):
	if self.where:
	    return "%s at %s" % (self.when.strftime("%A, %B %d %Y at %I:%M %p"), self.where.name)
	return "%s location TBD" % self.when

    when = models.DateTimeField()
    where = models.ForeignKey(Venue,blank=True,null=True)

    def is_future(self):
        return bool( self.when >=  ( datetime.datetime.now() - datetime.timedelta(hours = 3 )))

    def rsvp_user_yes(self):
        raise NotImplimentedError

    def rsvp_user_maybe(self):
        raise NotImplimentedError

    def number_rsvps(self):
        return self.rsvp_set.count()

class Presentor(CommonModel):
    def __unicode__(self):
        return self.name

    user = models.ForeignKey(User, blank = True, null = True)
    name = models.CharField(max_length = MAX_LENGTH)
    email = models.EmailField(max_length = MAX_LENGTH, blank = True, null = True)
    phone = models.CharField(max_length = MAX_LENGTH, blank = True, null = True)
    release = models.BooleanField(default = False)

class Topic(CommonModel):

    def __unicode__(self):
        out = self.title
        if self.presentor:
            out += " By: %s" % self.presentor.name
        return out

    title = models.CharField(max_length=MAX_LENGTH)
    presentor = models.ForeignKey(Presentor,blank=True,null=True)
    meeting = models.ForeignKey( Meeting, blank=True, null=True)
    length = IntervalField(format="M", blank = True, null = True)
    embed_video = models.TextField(blank=True,null=True)
    description = models.TextField(blank=True,null=True)
    slides_link = models.URLField(verify_exists=True, blank=True, null=True)
    start_time = models.DateTimeField(blank = True, null = True)
    approved = models.BooleanField(default = False)

class RSVP(CommonModel):
    RSVP_CHOICES = (
        ('Y', "Yes"),
        ('N', "No"),
        ('M', "Maybe"),
    )

    user = models.ForeignKey(User, blank = True, null = True)
    name = models.CharField(max_length = MAX_LENGTH, blank = True, null = True)
    email = models.EmailField(max_length = 255, blank = True, null = True)
    meeting = models.ForeignKey(Meeting)
    response = models.CharField(max_length = 1, choices = RSVP_CHOICES)
    key = models.CharField(max_length = MAX_LENGTH, blank = True, null = True)

    def clean(self):
        from django.core.exceptions import ValidationError

        if not self.user and not self.name:
            raise ValidationError('User or Name required')

        # Check uniqueness
        if not self.id:
            if self.user:
                if RSVP.objects.filter(meeting = self.meeting, user = self.user).exists():
                    raise ValidationError('User has already RSVPed for meeting')
            else:
                if RSVP.objects.filter(meeting = self.meeting, name = self.name).exists():
                    raise ValidationError('User has already RSVPed for meeting')

    def save(self, *args, **kwargs):
        self.full_clean()

        # If rsvp only has an email and this is a create and not update
        # generate a key and email it to the user
        if not self.pk:
            self.key = ''.join(random.choice(string.digits + string.ascii_lowercase) for x in range(40))
            plaintext = get_template('meetings/rsvp_email.txt')
            htmly     = get_template('meetings/rsvp_email.html')

            d = Context({ 'key': self.key, })

            subject = 'Chipy: Link to Change your RSVP'
            from_email = 'DoNotReply@chipy.org'
            text_content = plaintext.render(d)
            html_content = htmly.render(d)
            msg = EmailMultiAlternatives(subject, text_content, from_email, [self.email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

        return super(RSVP, self).save(*args, **kwargs)

    def __unicode__(self):
        if not self.name:
            self.name = self.user.get_full_name()
        return "{}: {}".format(self.meeting, self.name)<commit_msg>template should have site<commit_after>import settings
import datetime
import string
import random

from django.db import models
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

from interval.fields import IntervalField

from libs.models import CommonModel

MAX_LENGTH = 255

MEETING = (
    ('Loop', 'Loop Meeting - 2nd Thursday'),
    ('North', 'North Meeting - 3rd Thursday')
)

class Venue(CommonModel):

    def __unicode__(self):
	return self.name

    name = models.CharField(max_length=MAX_LENGTH)
    email = models.EmailField(max_length=MAX_LENGTH,blank=True,null=True)
    phone = models.CharField(max_length=MAX_LENGTH,blank=True,null=True)
    address = models.TextField(blank=True,null=True)

    def get_latitude(self):
        raise NotImplimented

    def get_longitude(self):
        raise NotImplimented

    longitude = property(get_longitude)
    latitude = property(get_latitude)

    @property
    def jsonLatLng(self):
        '''
        Use the string returned as args for google.maps.LatLng constructor.
	'''
        if self.latitude != None and self.longitude != None:
            return "%.6f,%.6f" % (self.latitude,self.longitude)
        else:
            return None

    directions = models.TextField(blank=True,null=True)
    embed_map = models.TextField(blank=True,null=True)
    link = models.URLField(verify_exists=True, blank=True, null=True)

class Meeting(CommonModel):
    def __unicode__(self):
	if self.where:
	    return "%s at %s" % (self.when.strftime("%A, %B %d %Y at %I:%M %p"), self.where.name)
	return "%s location TBD" % self.when

    when = models.DateTimeField()
    where = models.ForeignKey(Venue,blank=True,null=True)

    def is_future(self):
        return bool( self.when >=  ( datetime.datetime.now() - datetime.timedelta(hours = 3 )))

    def rsvp_user_yes(self):
        raise NotImplimentedError

    def rsvp_user_maybe(self):
        raise NotImplimentedError

    def number_rsvps(self):
        return self.rsvp_set.count()

class Presentor(CommonModel):
    def __unicode__(self):
        return self.name

    user = models.ForeignKey(User, blank = True, null = True)
    name = models.CharField(max_length = MAX_LENGTH)
    email = models.EmailField(max_length = MAX_LENGTH, blank = True, null = True)
    phone = models.CharField(max_length = MAX_LENGTH, blank = True, null = True)
    release = models.BooleanField(default = False)

class Topic(CommonModel):

    def __unicode__(self):
        out = self.title
        if self.presentor:
            out += " By: %s" % self.presentor.name
        return out

    title = models.CharField(max_length=MAX_LENGTH)
    presentor = models.ForeignKey(Presentor,blank=True,null=True)
    meeting = models.ForeignKey( Meeting, blank=True, null=True)
    length = IntervalField(format="M", blank = True, null = True)
    embed_video = models.TextField(blank=True,null=True)
    description = models.TextField(blank=True,null=True)
    slides_link = models.URLField(verify_exists=True, blank=True, null=True)
    start_time = models.DateTimeField(blank = True, null = True)
    approved = models.BooleanField(default = False)

class RSVP(CommonModel):
    RSVP_CHOICES = (
        ('Y', "Yes"),
        ('N', "No"),
        ('M', "Maybe"),
    )

    user = models.ForeignKey(User, blank = True, null = True)
    name = models.CharField(max_length = MAX_LENGTH, blank = True, null = True)
    email = models.EmailField(max_length = 255, blank = True, null = True)
    meeting = models.ForeignKey(Meeting)
    response = models.CharField(max_length = 1, choices = RSVP_CHOICES)
    key = models.CharField(max_length = MAX_LENGTH, blank = True, null = True)

    def clean(self):
        from django.core.exceptions import ValidationError

        if not self.user and not self.name:
            raise ValidationError('User or Name required')

        # Check uniqueness
        if not self.id:
            if self.user:
                if RSVP.objects.filter(meeting = self.meeting, user = self.user).exists():
                    raise ValidationError('User has already RSVPed for meeting')
            else:
                if RSVP.objects.filter(meeting = self.meeting, name = self.name).exists():
                    raise ValidationError('User has already RSVPed for meeting')

    def save(self, *args, **kwargs):
        self.full_clean()

        # If rsvp only has an email and this is a create and not update
        # generate a key and email it to the user
        if not self.pk and not self.user:
            self.key = ''.join(random.choice(string.digits + string.ascii_lowercase) for x in range(40))
            plaintext = get_template('meetings/rsvp_email.txt')
            htmly     = get_template('meetings/rsvp_email.html')

            d = Context({ 'key': self.key, 'site': Site.objects.get_current(),})

            subject = 'Chipy: Link to Change your RSVP'
            from_email = 'DoNotReply@chipy.org'
            text_content = plaintext.render(d)
            html_content = htmly.render(d)
            msg = EmailMultiAlternatives(subject, text_content, from_email, [self.email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

        return super(RSVP, self).save(*args, **kwargs)

    def __unicode__(self):
        if not self.name:
            self.name = self.user.get_full_name()
        return "{}: {}".format(self.meeting, self.name)<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Created on Fri Oct 24 18:14:50 2014

@author: richard
"""
import numpy as np
from numpy import pi, sin, cos
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
from matplotlib import cm

flight_dur = 100.0
timestep = 0.5
times = np.arange(0, flight_dur, timestep)
time_indexes = list(enumerate(times))

BOX_SIZE = (100.0,10.0,1.0)

class plume(object):
    def __init__(self):
        """A time-evolving odorant for our little guy to flap around in"""
        self.res = 100.0      #Split into 100 straight segments
        self.X = np.linspace(0, BOX_SIZE[0], self.res) #X locs of plume
        self.Y = np.linspace(0, BOX_SIZE[1],self.res) #Y of odor slices
        self.xx, self.yy = np.meshgrid(self.X, self.Y, sparse=True)
        self.Z = 0 * (self.xx + self.yy) #odor intensity at x,y
        #self.source = list(source) #Y/Z of the source
        #self.original = source #Initial source location
        #self.cross = np.zeros((2, len(self.X)))

# Set up a plume
plume = plume()

#def animate_plume(plume):
#    # Set up a figure
#    fig = plt.figure(0, figsize=(6,6))
#    ax = axes3d.Axes3D(fig)
#    lines = []
#    x, y, z = plume.X, plume.Y, plume.Z
#    lines.append(ax.plot(x, y, z)[0])
#    ax.plot_wireframe(x , y , z, rstride=10, cstride=10)
##    def update_plume(num, plumes, lines):
##        for plume, line in zip(plumes, lines):
##            plume.update()
##            x, y, z = plume.X, plume.Y, plume.Z
##            line.set_data(np.array([x,y]))
##            line.set_3d_properties(z)
##        return lines
##    # Make the figure nice
#    ax.set_xlim3d([0.0, BOX_SIZE[0]])
#    ax.set_ylim3d([0.0, BOX_SIZE[1]])
#    ax.set_zlim3d([0.0, BOX_SIZE[2]])
#    ax.set_xlabel('X')
#    ax.set_ylabel('Y')
#    ax.set_zlabel('intensity')
#    ax.set_title("robomozzie")
# #   plume_ani = FuncAnimation(fig, func=update_plume, frames=100,
#  #                           fargs=(plumes,lines), interval=10)
#    plt.show()
#
#animate_plume(plume)

#make this fluctuating
#intensities = ([0] * 5 ) + ([1] * 10 ) + ([0] * 20 ) + ([5] * 15) + ([1] * 150 )
#intensities_indexed = list(enumerate(intensities))
#print intensities_indexed
#def intensity(time_index):
#    pass

##intensities = ([0] * 5 ) + ([1] * 10 ) + ([0] * 20 ) + ([5] * 15) + ([1] * 150 )
#spiketime_index = []
#
#class mozzie(object):
#    pass
#
#class neuron(object):
#    pass
#
#sensor_neuron = neuron()

#def agentflight(total_velo_max = 5, total_velo_min = 1, wind_velo = 0, y_offset_curr = 0, angular_velo = 0.1, tau_y = 1, plotting = 'off'):
#    """
#    plots the mosquito's path in space
#    input: total_velo_max, total_velo_min, wind_velo, y_offset_curr, angular_velo, flight_dur, timestep
#    output: times, agent_y_pos, x_velocities, y_velocities
#    TODO: impliment agent_x_pos using velocity max and min
#    TODO: implement y offset, and wind velocity
#    TODO: make agent_pos list where each item is an (x,y) coord
#    TODO: make eval_neuron control agent flight
#    """
#    amplitude_max = 10 # TODO: impliment the amplitude fxn
#    agent_y_pos = []
#    y_velocities = []
#    x_velocities = []
#    for time_curr in times:
#        y_pos_curr = amplitude_max * sin (angular_velo * time_curr) #+ y_offset_curr #disabled
#        agent_y_pos.append(y_pos_curr)
#        y_offset_prev = y_offset_curr #test this with print statements
#        if time_curr == 0:
#            time_prev = 0
#            y_pos_prev = 0
#            time_index = 0
#        y_velocity = (y_pos_curr - y_pos_prev) / timestep
#        y_velocities.append(y_velocity)
#        ## TODO: make x_velocities as in Sharri's
#        x_velocities.append((time_curr - time_prev)/ timestep)
#        if time_index in spiketime_index:         # if we spiked at this time_curr, set y_aim = y_post_cur
#            y_aim = y_pos_curr
#            y_offset_curr = (y_aim - y_offset_prev) / tau_y
#        time_prev = time_curr
#        y_pos_prev = y_pos_curr
#        time_index += 1
#    if plotting == "on":
#        agentflightplotter(agent_y_pos, x_velocities, y_velocities)
#    return times, agent_y_pos, x_velocities, y_velocities

#def agentflightplotter(agent_y_pos, x_velocities, y_velocities):
#    """
#    TODO: animate this, using def update_mozzie and FuncAnimation
#    """
#    fig = plt.figure(2)
#    plot(times,agent_y_pos,'k',label= 'agent y_pos over time' )
#    plot(times,y_velocities, 'b',label= 'y velocity')
#    plot(times,x_velocities, 'r',label= 'x velocity')
#    xlabel('time')
#    ylabel('Y position')
#    legend()
#    title("Flying mosquito")
#    plt.show()

if __name__ == "__main__":
    #timestepper()
#    agentflightplotter()
    pass<commit_msg>Z meshing<commit_after># -*- coding: utf-8 -*-
"""
Created on Fri Oct 24 18:14:50 2014

@author: richard
"""
import numpy as np
from numpy import pi, sin, cos
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
from matplotlib import cm

flight_dur = 100.0
timestep = 0.5
times = np.arange(0, flight_dur, timestep)
time_indexes = list(enumerate(times))

BOX_SIZE = (100.0,10.0,1.0)

class plume(object):
    def __init__(self):
        """A time-evolving odorant for our little guy to flap around in"""
        self.res = 100.0      #Split into 100 straight segments
        self.X = np.linspace(0, BOX_SIZE[0], self.res) #X locs of plume
        self.Y = np.linspace(0, BOX_SIZE[1],self.res) #Y of odor slices
        self.xx, self.yy = np.meshgrid(self.X, self.Y, sparse=True)
        self.zz = 0 * (self.xx + self.yy) #odor intensity at x,y
        #self.source = list(source) #Y/Z of the source
        #self.original = source #Initial source location
        #self.cross = np.zeros((2, len(self.X)))

# Set up a plume
plume = plume()

def animate_plume(plume):
    # Set up a figure
    fig = plt.figure(0, figsize=(6,6))
    ax = axes3d.Axes3D(fig)
    #lines = []
    x, y, z = plume.xx, plume.yy, plume.zz
    #lines.append(ax.plot(x, y, z)[0])
    ax.plot_wireframe(x , y , z, rstride=10, cstride=10)
#    def update_plume(num, plumes, lines):
#        for plume, line in zip(plumes, lines):
#            plume.update()
#            x, y, z = plume.X, plume.Y, plume.Z
#            line.set_data(np.array([x,y]))
#            line.set_3d_properties(z)
#        return lines
#    # Make the figure nice
    ax.set_xlim3d([0.0, BOX_SIZE[0]])
    ax.set_ylim3d([0.0, BOX_SIZE[1]])
    ax.set_zlim3d([0.0, BOX_SIZE[2]])
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('intensity')
    ax.set_title("robomozzie")
 #   plume_ani = FuncAnimation(fig, func=update_plume, frames=100,
  #                           fargs=(plumes,lines), interval=10)
    plt.show()

animate_plume(plume)

#make this fluctuating
#intensities = ([0] * 5 ) + ([1] * 10 ) + ([0] * 20 ) + ([5] * 15) + ([1] * 150 )
#intensities_indexed = list(enumerate(intensities))
#print intensities_indexed
#def intensity(time_index):
#    pass

##intensities = ([0] * 5 ) + ([1] * 10 ) + ([0] * 20 ) + ([5] * 15) + ([1] * 150 )
#spiketime_index = []
#
#class mozzie(object):
#    pass
#
#class neuron(object):
#    pass
#
#sensor_neuron = neuron()

#def agentflight(total_velo_max = 5, total_velo_min = 1, wind_velo = 0, y_offset_curr = 0, angular_velo = 0.1, tau_y = 1, plotting = 'off'):
#    """
#    plots the mosquito's path in space
#    input: total_velo_max, total_velo_min, wind_velo, y_offset_curr, angular_velo, flight_dur, timestep
#    output: times, agent_y_pos, x_velocities, y_velocities
#    TODO: impliment agent_x_pos using velocity max and min
#    TODO: implement y offset, and wind velocity
#    TODO: make agent_pos list where each item is an (x,y) coord
#    TODO: make eval_neuron control agent flight
#    """
#    amplitude_max = 10 # TODO: impliment the amplitude fxn
#    agent_y_pos = []
#    y_velocities = []
#    x_velocities = []
#    for time_curr in times:
#        y_pos_curr = amplitude_max * sin (angular_velo * time_curr) #+ y_offset_curr #disabled
#        agent_y_pos.append(y_pos_curr)
#        y_offset_prev = y_offset_curr #test this with print statements
#        if time_curr == 0:
#            time_prev = 0
#            y_pos_prev = 0
#            time_index = 0
#        y_velocity = (y_pos_curr - y_pos_prev) / timestep
#        y_velocities.append(y_velocity)
#        ## TODO: make x_velocities as in Sharri's
#        x_velocities.append((time_curr - time_prev)/ timestep)
#        if time_index in spiketime_index:         # if we spiked at this time_curr, set y_aim = y_post_cur
#            y_aim = y_pos_curr
#            y_offset_curr = (y_aim - y_offset_prev) / tau_y
#        time_prev = time_curr
#        y_pos_prev = y_pos_curr
#        time_index += 1
#    if plotting == "on":
#        agentflightplotter(agent_y_pos, x_velocities, y_velocities)
#    return times, agent_y_pos, x_velocities, y_velocities

#def agentflightplotter(agent_y_pos, x_velocities, y_velocities):
#    """
#    TODO: animate this, using def update_mozzie and FuncAnimation
#    """
#    fig = plt.figure(2)
#    plot(times,agent_y_pos,'k',label= 'agent y_pos over time' )
#    plot(times,y_velocities, 'b',label= 'y velocity')
#    plot(times,x_velocities, 'r',label= 'x velocity')
#    xlabel('time')
#    ylabel('Y position')
#    legend()
#    title("Flying mosquito")
#    plt.show()

if __name__ == "__main__":
    #timestepper()
#    agentflightplotter()
    pass<|endoftext|>