예제 #1
0
파일: utils.py 프로젝트: frecar/focus
def send_update_mails(ticket, ticket_update):
    """
    Sends email to all users who commented or created ticket
    """
    assigned_sent = check_assigned_to(ticket)

    recipients = set([])

    if not ticket.mailbox_hash:

        ticket.mailbox_hash = hashlib.sha224("ticket-%s"%ticket.id).hexdigest()
        ticket.save()

    if ticket.assigned_to:
        if ticket.assigned_to.email:
            recipients.add(ticket.assigned_to.email)

    if not assigned_sent and ticket.assigned_to:
        if ticket.assigned_to.email in recipients:
            recipients.remove(ticket.assigned_to.email)

    for recipient in ticket.get_recipients():
        if recipient.email:
            recipients.add(recipient.email)

    if Core.current_user().email:
        if Core.current_user().email in recipients:
            recipients.remove(Core.current_user().email)

    if ticket_update.public and ticket_update.comment:
        _send_to_clients(ticket, ticket_update)

    msg = _create_msg(ticket, ticket_update)
    send_mail(_("Ticket update"), msg, "support+"+ticket.mailbox_hash+"@focustime.no", recipients)
예제 #2
0
파일: seed.py 프로젝트: frecar/focus
    def handle(self, *args, **kwargs):
        randomCompanyIdentifier = str(int(random.random() * 99999))

        company, user = createNewCustomer(
            "Ledere",
            "Bjarte Hatlenes",
            "superadmin" + randomCompanyIdentifier,
            "superadmin" + randomCompanyIdentifier,
            "Ansatte",
            "Focus Security AS" + randomCompanyIdentifier,
        )

        self.company = company
        self.user = user

        Core.set_test_user(user)
        password = generate_new_password_for_user(user)
        print "Company: %s " % company
        print "Current user is: %s " % Core.current_user()
        print "Current user is: %s " % Core.current_user().username
        print "Current users password: %s " % password

        self.customers = []
        self.projects = []

        self.seed_customers()
        self.seed_contacts()
        self.seed_projects()
        self.seed_orders()
        self.seed_offers()
        self.seed_tickets()
        self.seed_suppliers()
        self.seed_products()
class Azure(ShowBase):
    def __init__(self):
        """Program entry point."""
        # TODO(Nemesis#13): rewrite ShowBase to not use globals.

        # This basically sets up our rendering node-tree, some builtins and
        # the master loop (which iterates each frame).
        ShowBase.__init__(self)

        # Turn off Panda3D's standard camera handling.
        self.disableMouse()

        self.setBackgroundColor(0,0,0,1)

        # Start our Core Finite State Machine
        self.core = Core()
        if (options.scenario):
            # Scenario was specified at command line.
            self.core.demand("Loading", options.scenario)
        else:
            self.core.demand("Menu", "MainMenu")

        #base.bufferViewer.toggleEnable()

		# Start the master loop.
        self.run()
예제 #4
0
파일: group.py 프로젝트: frecar/focus
def form (request, id=False):
    if id:
        instance = Core.current_user().get_permitted_objects("VIEW", Group).get(id=id)
        msg = _("Successfully edited group")
    else:
        instance = Group()
        msg = _("Successfully added new group")

    #Save and set to active, require valid form
    if request.method == 'POST':
        form = GroupForm(request.POST, instance=instance)
        if form.is_valid():
            o = form.save(commit=False)
            o.company = Core.current_user().get_company()
            o.save()
            form.save_m2m()

            request.message_success(msg)
            return redirect(overview)

    else:
        form = GroupForm(instance=instance)

    return render(request, "admin/groups/form.html",
                  {'title': _("Group"), 'group': instance, 'form': form})
예제 #5
0
    def is_authenticated(self, request):
        #Check if already logged in, for use inside the application
        if Core.current_user() and Core.current_user().is_authenticated():
            return True

        #If not, then use basic auth
        else:
            auth_string = request.META.get('HTTP_AUTHORIZATION', None)

            if not auth_string:
                return False

            (authmeth, auth) = auth_string.split(" ", 1)

            if not authmeth.lower() == 'basic':
                return False

            auth = auth.strip().decode('base64')
            (username, password) = auth.split(':', 1)

            if Core.login(request, username, password):
                user = User.objects.get(username=username)
                return user.canLogin

        return False
예제 #6
0
class Omr:
    '''
    This module parses the options from comand line and starts the process
    '''
    def __init__(self,options):
        '''
        Constructor
        @param options : program options
        '''
        self.core=None
        self.appfilepath=options.appfilepath
        self.datafilepath=options.datafilepath
        self.inputfolder=options.inputfolder
        self.extension=options.extension
        self.threshold=options.threshold
    
    def scan(self):
        '''
        Starts the processing. Supported image formats: all supported by OpenCV and PIL
        '''
        if self.inputfolder!=None and self.appfilepath!=None and self.datafilepath!=None:
            self.core=Core(glob.glob(self.inputfolder+'/*.'+self.extension),self.appfilepath,self.datafilepath,self.threshold)
            self.core.run()
        else:
            print("Por favor, forneça a pasta de entrada, o arquivo de aplicação e o arquivo de dados")
예제 #7
0
파일: omr.py 프로젝트: romualdoandre/myomr
class Omr:
    '''
    This module parses the options from comand line and starts the process
    '''
    def __init__(self,options):
        '''
        Constructor
        @param options : program options
        '''
        self.core=None
        self.appfilepath=options.appfilepath
        self.datafilepath=options.datafilepath
        self.inputfolder=options.inputfolder
        self.threshold=options.threshold
        self.zbar=options.zbar
    
    def scan(self):
        '''
        Starts the processing. Supported image formats: all supported by OpenCV and PIL
        '''
        if self.inputfolder!=None and self.appfilepath!=None and self.datafilepath!=None:
            self.core=Core(glob.glob(self.inputfolder),self.appfilepath,self.datafilepath,self.threshold,self.zbar)
            self.core.run()
        else:
            print "usage: python omr.py -i regex -o output -a config -t threshold [-z]"
예제 #8
0
파일: views.py 프로젝트: frecar/focus
def products(request, id):
    supplier = Core.current_user().get_permitted_objects("VIEW", Supplier).get(id=id)
    products = Core.current_user().get_permitted_objects("VIEW", Product).filter(supplier=supplier)

    return render(request, 'suppliers/products.html', {'title': _("Products"),
                                                       'supplier': supplier,
                                                       'products': products})
예제 #9
0
파일: middleware.py 프로젝트: frecar/focus
    def process_request (self, request):

        # Save the current thread with the current user
        Core.attach_user(request)
        request.user = Core.current_user()

        return None
예제 #10
0
파일: managers.py 프로젝트: frecar/focus
    def filter_current_company(self):

        #Check if no current_user
        if not Core.current_user():
            return None
        
        return super(PersistentManager, self).get_query_set().filter(deleted=False,
                                                                     company=Core.current_user().get_company())
예제 #11
0
    def on_request(self, text, author):
        text = re.sub(self.regexp, '', text)
        text = re.sub(r'\s+$', '', text)

        lang = get_language(text, key=u'startword')

        if lang is not None:
            core = Core(lang)
            self.send_message(core.send_message(), author)
예제 #12
0
def start(daemon=True):
    if running_process.is_running():
        messages.abort(messages.WAS_RUNNING)

    core = Core()

    if daemon:
        daemonize()

    core.start()
예제 #13
0
파일: base.py 프로젝트: averrin/Darknessers
class WinterApp(object):
    """
        Main non-gui application class
    """
    __apiclass__ = WinterAPI
    __pmclass__ = WinterPM

    def getMethod(self, key, module='main'):
        if not key.startswith('_'):
            try:
                if module == 'core':
                    return getattr(self.core, key)
                elif module == 'main':
                    return getattr(self, key)
                else:
                    return getattr(WinterPlugin.objects.get(name=module), key)
            except Exception as e:
                pass
        return False

    def __getitem__(self, key):
        return self.getMethod('main', key)

    def loadConfigs(self):
        """
            Load configuration from file
        """
        self.config = WinterConfig(open(self.api.CWD + 'config/main.cfg'))
        self.p_config = WinterConfig(open(self.api.CWD + 'config/plugins.cfg'))
        self.schema = WinterConfig(open(self.api.CWD + 'config/schema.cfg'))

    def onSubsChange(self, key, value):
        print('%s changed to %s' % (key, value))

    def __init__(self):
        self.api = self.__class__.__apiclass__()

        global API
        API = self.__class__.__apiclass__
        self.loadConfigs()
        self.api.config = self.config
        self.api.ex = self.getMethod

        self.beforeCore()
        from core import Core

        self.core = Core()
        self.core.app = self
        self.core._afterInit()
        if self.config.options.plugins:
            WinterPlugin()
            self.pm = self.__class__.__pmclass__(self.p_config)

    def beforeCore(self):
        pass
    def __init__(self, position, buttonName):
        # Inicia os objetos
        pygame.sprite.Sprite.__init__(self)
        core = Core()

        # Insere as imagens
        self.image, self.rect = core.loadImage(buttonName)

        # Define a posicao do botao
        self.rect.centerx = position[0]
        self.rect.centery = position[1]
예제 #15
0
파일: models.py 프로젝트: frecar/focus
    def save(self, *args, **kwargs):
        self.date = datetime.now()

        if 'user' in kwargs:
            self.creator = kwargs['user']
        else:
            self.creator = Core.current_user()

        if Core.current_user() and Core.current_user().get_company():
            self.company = Core.current_user().get_company()
            
        super(Log, self).save()
예제 #16
0
파일: handlers.py 프로젝트: frecar/focus
    def update(self, request, id=None):

        if id:
            trackers = [Core.current_user().get_permitted_objects("EDIT", TimeTracker).get(id=id)]
        else:
            trackers = Core.current_user().get_permitted_objects("EDIT", TimeTracker).all()
        for tracker in trackers:
            try:
                self._do_update(request, tracker)
            except ValueError as e:
                return {'error': str(e)}

        return {'success': True}
예제 #17
0
파일: tests.py 프로젝트: frecar/focus
    def setUp(self):

        self.group1 = Group.objects.get_or_create(name="group1")[0]
        company = Company.objects.get_or_create(name="TestFirma", admin_group = self.group1)[0]

        self.user1 = User.objects.get_or_create(username="******", company=company)[0]
        self.user2 = User.objects.get_or_create(username="******", company=company)[0]
        self.user3 = User.objects.get_or_create(username="******", company=company)[0]

        Core.set_test_user(self.user1)

        self.contact1 = Contact.objects.get_or_create(name="Customer1")[0]

        self.group1.add_member(self.user2)
예제 #18
0
def main():
    #cherrypy.config.update({'error_page.404': error_page_404})
    cherrypy.config.update('webapiner.ini')
    
    core = Core(current_dir)
    core.loadConfig("")
    core.initManagers()
    rest_service = RESTService(core)

    cherrypy.tree.mount(rest_service, "/api/", config = {'/':{'request.dispatch':cherrypy.dispatch.MethodDispatcher()}})
    
    conf = {
        '/static':
        { 'tools.staticdir.on':True,
          'tools.staticdir.dir': current_dir + "/static"
        },
    }
    

    Root._cp_config = {'tools.staticdir.on' : True,
                  'tools.staticdir.dir' : os.path.join(current_dir, "static"),
                  'tools.staticdir.index' : 'index.html',
                  'tools.caching.on' :False}

    with open("webapiner.pid","w") as f:
        f.write(str(os.getpid()))
    
    cherrypy.engine.subscribe("stop", core.getManager("asset").stop)
    core.getManager("asset").start()
    #core.getManager("kb").autoload()
    cherrypy.quickstart(Root(core), config = conf)
예제 #19
0
	def __init__( self ):

		self.core = Core( 60, 1024, 768, "Ninja" )

		self.intro = Intro()

		self.menu_background = Texture( "menu/background.png" )
		self.menu_title = Menu_title()
		self.menu_play_button = Menu_play_button()
		self.menu_git_button = Menu_link_button( "menu/git.png", "https://github.com/Adriqun" )
		self.menu_google_button = Menu_link_button( "menu/google.png", "https://en.wikipedia.org/wiki/Ninja" )
		self.menu_facebook_button = Menu_link_button( "menu/facebook.png", "nothing", True )
		self.menu_twitter_button = Menu_link_button( "menu/twitter.png", "nothing", True )
		self.menu_music_button = Menu_music_button( "menu/music.png" )
		self.menu_chunk_button = Menu_music_button( "menu/chunk.png", 1 )
		self.menu_exit_log = Menu_exit_log()
		self.menu_author_log = Menu_author_log()
		self.menu_game_log = Menu_link_button( "menu/game.png", "nothing", True )
		self.menu_settings_log = Menu_link_button( "menu/settings.png", "nothing", True )
		self.menu_score_log = Menu_score_log()
		self.menu_music = Menu_music( "menu/Rayman Legends OST - Moving Ground.mp3" )
		
		self.wall = Wall()
		self.hero = Hero()
		self.menu_log = Menu_log()
		self.map = Map()
예제 #20
0
파일: views.py 프로젝트: frecar/focus
def edit(request, id):
    ticket = Core.current_user().get_permitted_objects("VIEW", Ticket).get(id=id)
    updates = TicketUpdate.objects.filter(ticket=ticket).order_by("-id")

    #ticket.visited_by_since_last_edit.add((Core.current_user()))

    if request.method == "POST":
        old_ticket = copy.copy(ticket)
        ticket_form = EditTicketForm(request.POST, request.FILES, instance=ticket)

        if ticket_form.is_valid():
            ticket = create_update_for_ticket(old_ticket, ticket_form)

            ticket.invalidate_cache()

            request.message_success(_("Ticket updated"))

            return redirect(edit, ticket.id)

    else:
        ticket_form = EditTicketForm(instance=ticket)

    return render(request, "tickets/edit.html", {'title': _('Update Ticket'),
                                                 'ticket': ticket,
                                                 'updates': updates,
                                                 'form': ticket_form,
                                                 })
예제 #21
0
 def start(self):
     self.core = Core()
     self.db = self.core.db()
     self.auth = self.context.auth = self.core.auth
     self.session = self.core.session
     #self.db._check_update('document', 'designer')
     self.get()
예제 #22
0
파일: views.py 프로젝트: frecar/focus
def disbursements(request, id=None):
    instance = Disbursement()
    disb = Disbursement.objects.filter(trashed=False, creator=Core.current_user())

    if id:
        instance = get_object_or_404(Disbursement, id=id)

    #Save and set to active, require valid form
    if request.method == 'POST':
        form = DisbursementForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            o = form.save(commit=False)
            o.save()

            request.message_success("Success")

            instance = Disbursement()
            form = DisbursementForm(instance=instance, initial={'attachment': None})

    else:
        form = DisbursementForm(instance=instance, initial={'attachment': None})


    return render(request, "hourregistrations/disbursements.html",
            {'title': _("Disbursements"), 'disbursements': disb, 'disbursement': instance, 'form': form})
예제 #23
0
파일: models.py 프로젝트: frecar/focus
    def save(self, *args, **kwargs):
        new = False
        if not self.id:
            new = True

        super(Project, self).save()

        self.invalidate_cache()
        
        #Give the user who created this ALL permissions on object
        if new:
            Core.current_user().grant_role("Owner", self)
            admin_group = Core.current_user().get_company_admingroup()

            if admin_group:
                admin_group.grant_role("Admin", self)
예제 #24
0
파일: views.py 프로젝트: frecar/focus
def assigned_to_user(request):
    tickets = Core.current_user().get_permitted_objects("VIEW", Ticket).\
    filter(trashed=False, assigned_to=request.user).order_by("status", "-priority", "-date_edited")

    return render(request, 'tickets/list.html', {"title": "Tickets",
                                                 "assigned_to": True,
                                                 'tickets': tickets})
예제 #25
0
 def _parse_dump_only(self):
     self.dump = Core(self.ctl_transact, self.cfg)
     self.dump.code = 'test_' + ''.join(random.SystemRandom().
                                        choice('abcdefgijklmnoprstuvwxyz1234567890') for _ in range(8))
     History.create(requestCode=self.dump.code, date=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
     self.dump.code_id = History.get(History.requestCode == self.dump.code).id
     self.dump.parse_dump()
예제 #26
0
파일: views.py 프로젝트: frecar/focus
def overview_trashed(request):
    tickets = Core.current_user().get_permitted_objects("VIEW", Ticket).filter(trashed=True).order_by("status",
                                                                                                      "-priority",
                                                                                                      "-date_edited")

    return render(request, 'tickets/list.html',
            {"title": "Tickets", 'tickets': tickets})
예제 #27
0
파일: base.py 프로젝트: anndream/next2web
class Document(Base):
    def start(self):
        self.core = Core()
        self.db = self.core.db()
        self.auth = self.context.auth = self.core.auth
        self.session = self.core.session
        self.get()
        
    def get(self):
        self.context.document = self.db.get_document(*self.request.args[:2])
                     
    def create(self):
        self.before_create()
        self.context.form = DocumentPage(self.context.document)
        self.after_create()
        
    def edit(self):
        self.context.form = DocumentPage(self.context.document)

    def delete(self):
        self.db.send_to_trash(self.request.args[0], self.request.args[1])
        
    def show(self):
        self.context.form = DocumentPage(self.context.document, readonly=True)

    def render(self, view=None):
        viewfile = "%s.%s" % (view, self.request.extension)
        return self.response.render(viewfile, self.context)
예제 #28
0
파일: forms.py 프로젝트: frecar/focus
    def __init__(self, *args, **kwargs):
        super(HourRegistrationForm, self).__init__(*args, **kwargs)

        self.fields['time_start'].widget.attrs['class'] = 'time_input'
        self.fields['time_end'].widget.attrs['class'] = 'time_input'

        self.fields['type'].queryset = HourRegistrationType.objects.filter(trashed=False,
                                                                           company=Core.current_user().get_company())

        #self.fields['order'].queryset = Core.current_user().get_permitted_objects("VIEW", Order).filter(trashed=False)

        self.fields['order'].queryset = Order.objects.all().filter(trashed=False,
                                                                   company=Core.current_user().get_company())

        if 'instance' in kwargs:
            self.id = kwargs['instance'].id
예제 #29
0
파일: form.py 프로젝트: chrmorais/next2web
 def __init__(self, document, docset, extra=4, *args, **kwargs):
     
     if not 'hidden' in kwargs:
         kwargs['hidden'] = self._get_hidden_fields()
         
     FORM.__init__(self, *args, **kwargs)
     
     self.document = document
     self.docset = docset
     self.db = Core().db()
     
     self.extra = extra
     
     self._template_fields = filter(lambda df: df.type not in ('sectionbreak', 'columnbreak') or \
                                    df.property('visibility', 'is_writable')!='NEVER', self.document.META.DOCFIELDS)
     
     self._cols = self.document.property('type', 'listable_columns') or \
         [df.df_name for df in filter(lambda x: x.property('policy','is_readable')=='ALWAYS', self.DOCUMENT.META.DOCFIELDS)]
     self._cols = [filter(lambda x: x.df_name == column, self.document.META.DOC_FIELDS)[0] for column in self._cols]
     self._head = TR([TH()]+[TH(df.df_title, **{'_data-metatype': df.df_type}) for df in self._cols])
     
     components = [self._head, self._construct_documents()]
     for i in xrange(self.extra):
         components.append(self._get_empty_document((self.get_total_document_count()-self.extra)+i))
     self.components = [components]
예제 #30
0
파일: handlers.py 프로젝트: frecar/focus
 def delete(self, request, id):
     try:
         tracker = Core.current_user().get_permitted_objects("EDIT", TimeTracker).get(id=id)
         tracker.trash()
         return rc.DELETED
     except TimeTracker.DoesNotExist:
         return rc.NOT_FOUND
예제 #31
0
파일: models.py 프로젝트: bopopescu/focus
    def save(self, **kwargs):
        if 'update' in kwargs:
            send_update_mails(self, kwargs['update'])
        action = 'EDIT'
        if not self.id:
            action = 'ADD'

        if self.id:
            self.visited_by_since_last_edit = []
            if Core.current_user():
                self.visited_by_since_last_edit.add(Core.current_user())

        super(Ticket, self).save()

        if action == 'ADD':
            if self.assigned_to:
                send_assigned_mail(self.assigned_to, self, assigned=True)
            if self.company:
                if self.company.admin_group:
                    self.company.admin_group.grant_role('Admin', self)
                if self.company.all_employees_group:
                    self.company.all_employees_group.grant_role('Member', self)

        self.invalidate_cache()
예제 #32
0
def main(argv):
    base = 'Required'
    current = 'Required'
    try:
        opts, args = getopt.getopt(argv, "hb:c:", ["base=", "current="])
    except getopt.GetoptError:
        print(
            'update_files_service.py -r <base_directory> -c <current_directory>'
        )
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            sys.exit()
        elif opt in ("-b", "--base"):
            base = arg
        elif opt in ("-c", "--current"):
            current = arg

    print('Base folder is "', base)
    print('Current is "', current)

    core = Core(base, current)

    core.run()
예제 #33
0
파일: mars.py 프로젝트: cadulceus/yeet_wars
 def __init__(self, core=None, minimum_separation=100, max_processes=10, players={}, seconds_per_tick=0, \
     runtime_event_handler=lambda *args: None, update_thread_event_handler=lambda *args: None, \
     kill_thread_event_handler=lambda *args: None):
     self.core = core if core else Core()
     self.minimum_separation = minimum_separation
     self.max_processes = max_processes if max_processes else len(self.core)
     self.thread_pool = []
     self.next_tick_pool = []
     self.tick_count = 0
     self.players = players
     self.thread_counter = 0
     self.seconds_per_tick = seconds_per_tick
     self.runtime_event_handler = runtime_event_handler
     self.update_thread_event_handler = update_thread_event_handler
     self.kill_thread_event_handler = kill_thread_event_handler
예제 #34
0
파일: main.py 프로젝트: TheAshen1/AI-Labs
def main(argv):
    try:
        opt_list, args = getopt.getopt(argv, ":h", ["file=", 'help'])
    except getopt.GetoptError:
        print("main.py: getopterror")
        exit(2)

    for opt, arg in opt_list:
        if opt == "-h":
            print("--file <input file>")
            exit(1)
        elif opt == "--file":
            Core(file_path=arg)
        else:
            exit(1)
예제 #35
0
    def delete(self, request, id):
        try:
            contact = Core.current_user().get_permitted_objects(
                "DELETE", Contact).filter(trashed=False).get(id=id)
        except Contact.DoesNotExist:
            return rc.NOT_FOUND

        if not contact.can_be_deleted()[0]:
            response = rc.FORBIDDEN  #Maybe better to return 200 OK with error information?
            for reason in contact.can_be_deleted()[1]:
                response.write(reason)
            return response
        else:
            contact.trash()
            return rc.DELETED
예제 #36
0
def overview(request, id):
    """
    id is order_id
    """
    order = Core.current_user().get_permitted_objects("VIEW",
                                                      Order).all().get(id=id)

    #Set URL for edit for files in order
    edit_file_url = "/orders/%s/files/" % order.id

    return render(request, "orders/files/list.html", {
        'order': order,
        'file_manager': order,
        'edit_file_url': edit_file_url
    })
예제 #37
0
def main():
    """Initialize the framework."""
    core = Core(modules=[LeakHunter])

    parser = argparse.ArgumentParser()
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="Prints more about what's happening.")
    parser.add_argument(
        "--honeyfile",
        help="Path to honeyfile.  The docx file to be used as bait.")
    parser.add_argument("--targetfile",
                        help="Path to target file.  One name per line")
    parser.add_argument("--allowlist",
                        help="Path to allowlist file.  Internal IPs to ignore")
    parser.add_argument("--campaign", help="Campaign name")

    args = parser.parse_args()

    if args.honeyfile:
        core.modules.leak_hunter.honeyfile = args.honeyfile

    if args.targetfile:
        core.modules.leak_hunter.targetfile = args.targetfile

    if args.allowlist:
        core.modules.leak_hunter.allowlist = args.allowlist

    if args.campaign:
        core.modules.leak_hunter.campaign = args.campaign

    if args.verbose:
        core.verbose = True

    core.bootstrap(BANNER, WELCOME_MSG)
예제 #38
0
파일: forms.py 프로젝트: bopopescu/focus
 def __init__(self, *args, **kwargs):
     super(TicketForm, self).__init__(*args, **kwargs)
     self.fields[
         'assigned_to'].queryset = User.objects.filter_current_company()
     self.fields['attachment'].required = False
     self.fields['customer'].widget = SelectWithPop(Customer)
     self.fields[
         'customer'].queryset = Customer.objects.filter_current_company()
     self.fields['order'].queryset = Order.objects.filter_current_company()
     self.fields['type'].widget = SelectWithPop(TicketType)
     self.fields['type'].queryset = TicketType.objects.filter(
         company=Core.current_user().get_company())
     self.fields['due_date'].required = False
     self.fields['due_date'].widget = DatePickerField(format="%d.%m.%Y")
     self.fields['due_date'].input_formats = ["%d.%m.%Y"]
예제 #39
0
def add_file(request, id):
    """
    id = customer_id
    """
    customer = Core.current_user().get_permitted_objects(
        "VIEW", Customer).all().get(id=id)
    file = File()

    additional_data = {'customer': customer}

    return file_form(request,
                     customer,
                     file,
                     redirect(overview, id),
                     additional_data,
                     template="customers/files/form.html")
예제 #40
0
파일: files.py 프로젝트: bopopescu/focus
def add_file(request, id):
    """
    id = project_id
    """
    project = Core.current_user().get_permitted_objects(
        "VIEW", Project).all().get(id=id)
    file = File()

    additional_data = {'project': project}

    return file_form(request,
                     project,
                     file,
                     redirect(overview, id),
                     additional_data,
                     template="projects/files/form.html")
예제 #41
0
파일: files.py 프로젝트: bopopescu/focus
def edit_file(request, id, file_id):
    """
    id = project_id
    file_id = file_id
    """
    instance = Core.current_user().get_permitted_objects(
        "VIEW", Product).all().get(id=id)
    file = instance.files.get(id=file_id)
    additional_data = {'product': instance}

    return file_form(request,
                     instance,
                     file,
                     redirect(overview, id),
                     additional_data,
                     template="stock/files/form.html")
예제 #42
0
def edit_file(request, id, file_id):
    """
    id = order_id
    file_id = file_id
    """
    order = Core.current_user().get_permitted_objects("VIEW",
                                                      Order).all().get(id=id)
    file = order.files.get(id=file_id)
    additional_data = {'order': order}

    return file_form(request,
                     order,
                     file,
                     redirect(overview, id),
                     additional_data,
                     template="orders/files/form.html")
예제 #43
0
    def __init__(self, *args, **kwargs):
        existing_contacts = Q()

        if 'existing_contacts' in kwargs:
            existing_contacts = kwargs.get('existing_contacts')
            del kwargs['existing_contacts']

        super(ContactParticipantToCustomerForm, self).__init__(*args, **kwargs)
        qs = Core.current_user().get_permitted_objects("VIEW", Contact).filter(
            trashed=False)


        if existing_contacts:
            qs = qs.exclude(id__in=[contact.id for contact in existing_contacts])

        self.fields['contact'].queryset = qs
예제 #44
0
파일: files.py 프로젝트: bopopescu/focus
def overview(request, id):
    """
    id is project_id
    """
    project = Core.current_user().get_permitted_objects(
        "VIEW", Project).all().get(id=id)

    #Set URL for edit for files in project
    edit_file_url = "/projects/%s/files/" % project.id

    return render(
        request, "projects/files/list.html", {
            'project': project,
            'file_manager': project,
            'edit_file_url': edit_file_url
        })
예제 #45
0
 def add(cls, client_msg: ClientMessage, course: str):
     with session_maker() as session:
         heartbeat = cls()
         heartbeat.student_code = client_msg.student_code
         heartbeat.course = course
         heartbeat.device = client_msg.device.dumps()
         heartbeat.device_id = client_msg.auth_license
         calc_device_id = Core.machine_code_auth(
             stu_code=client_msg.student_code,
             mac_addr=client_msg.device.mac_addr,
             c_volume_serial_number=client_msg.device.
             c_volume_serial_number,
             hostname=client_msg.device.hostname)
         if calc_device_id != client_msg.auth_license:
             Log.add(client_msg)
         heartbeat.created_time = datetime.datetime.now()
         session.add(heartbeat)
예제 #46
0
def dbSetup(self, dbConnection):
    print("\n\n-------------------------\nnew day: " + str(date.today()))
    print(Core.getTime(self),
          "setting up new database [stats and quality] (daily-based)")
    dbCursor = dbConnection.cursor()
    # saving table names in self
    self.airqtable = "air_quality"
    self.airstable = "air_stats"
    # creating sql tables
    dbCursor.execute(
        "CREATE TABLE IF NOT EXISTS " + self.airstable +
        " (timestamp TEXT, temperature FLOAT, temperature_raw FLOAT, humidity FLOAT, pressure FLOAT, cpu_usage FLOAT, ram_usage FLOAT, cpu_temp FLOAT)"
    )
    dbCursor.execute("CREATE TABLE IF NOT EXISTS " + self.airqtable +
                     " (timestamp TEXT, air_2_5 FLOAT, air_10 FLOAT)")
    dbConnection.commit()
    self.db = dbConnection
예제 #47
0
    def __init__(self, c=Core(), interact=None):
        # core init
        self.core = c

        # GUI init
        self.root = tkinter.Tk()
        self.root.title('2048')
        self.root.geometry('600x800+10+10')
        # self.root.overrideredirect(True)

        # canvas init
        self.canvas_root = tkinter.Canvas(self.root, width=600, height=800)
        im_root = self._get_image('2048bkg.png', 600, 800)
        self.canvas_root.create_image(300, 400, image=im_root)
        self.canvas_root.place(x=0, y=0)

        # frame init
        self.frame = tkinter.Frame(self.root)
        self.frame.bind('<KeyRelease>', self._key_callback)

        self.frame.focus_set()
        self.frame.pack()

        # button init
        im_button = self._get_image('btn.png', 128, 39)
        self.btn = tkinter.Button(self.canvas_root,
                                  bd=0,
                                  image=im_button,
                                  width=128,
                                  height=39,
                                  command=self._new_game)
        self.btn.place(x=419, y=138)

        # last labels
        self.labels = []

        self.first_win = False

        # show
        self._show()

        # interaction
        if interact != None:
            self.root.after(1000, interact(self))

        self.root.mainloop()
예제 #48
0
def _get_core(args):
    from core import Core

    sql_conf = SQLConfig(args)
    s3_conf = S3Config(args)
    log_conf = LogConfig(args)
    generic_conf = GenericConfig(args)
    worker_conf = WorkerConfig(args)

    # Build params dictionary to pass to Core.
    core_args = sql_conf.to_dict()
    core_args.update(s3_conf.to_dict())
    core_args.update(log_conf.to_dict())
    core_args.update(generic_conf.to_dict())
    core_args.update(worker_conf.to_dict())

    return Core(**core_args)
예제 #49
0
 def __init__(self, version):
     self.core = Core(self.log)
     master = Tk()
     Frame.__init__(self, master)
     master.title("ArtStation Downloader " + version)  # 定义窗体标题
     self.root_path = StringVar()
     self.root_path.trace_add(
         "write", lambda name, index, mode: self.save_root_path(self.root_path.get())
     )
     root_path_config = self.load_root_path()
     self.root_path.set(
         root_path_config or os.path.join(os.path.expanduser("~"), "ArtStation")
     )
     self.executor_ui = futures.ThreadPoolExecutor(1)
     self.window = master
     self.pack()
     self.createWidgets()
예제 #50
0
    def init_auth(self):
        """
        Initializes a new registration process with the EB registration servers.
        :return:
        """
        if not self.is_auth_needed():
            return 0

        if self.config is None:
            raise ValueError('Configuration is not set')

        if self.eb_config is None:
            self.eb_config = Core.get_default_eb_config()

        client_data_req = {
            'type': self.user_reg_type,
            'method': self.reg_auth_chosen.method,
            'email': self.get_email()
        }

        init_auth_req = InitClientAuthRequest(client_data=client_data_req, env=self.config.env, config=self.eb_config)
        self.audit.audit_request(req_type=init_auth_req.__class__, data=client_data_req)

        try:
            init_auth_resp = init_auth_req.call()
        except Exception as e:
            self.audit.audit_exception(e)
            self.audit.audit_request(api_data=client_data_req,
                                     request=init_auth_req.request, response=init_auth_req.response,
                                     env=self.config.env, config=self.eb_config)
            logger.debug('API req: %s' % client_data_req)
            logger.debug('API req_full: %s' % init_auth_req.request)
            logger.debug('API res: %s' % init_auth_req.response)
            raise

        if 'clientid' not in init_auth_resp:
            raise InvalidResponse('Authentication initialization fails')

        self.config.client_id = init_auth_resp['clientid']
        self.config.two_stage_registration_waiting = True

        if 'authdata' in init_auth_resp:
            self.auth_data = init_auth_resp['authdata']

        return 0
예제 #51
0
def main(argc, argv):
	debug = os.getenv('DEBUG_MODE', None)
	if debug is not None:
		debug = True
	else:
		debug = False
	core = Core()
	port = 8080
	if argc > 1:
		if argv[1] == '-h' or argv[1] == '--help':
			print("usage:  {} <port>".format(argv[0]))
			sys.exit(0)
		port = int(argv[1])
	server = web.Server(core, port, debug=debug)
	try:
		server.run()
	except KeyboardInterrupt:
		pass
예제 #52
0
def test_simulation(nsubjects=256, f_mock=None):
    with Core(f_mock=f_mock) as core:
        response = simulation.run(
            core,
            simulation.Request(
                name='random',
                alternatives=('A', 'B', 'C', 'D', 'E'),
                gen_menus=simulation.GenMenus(
                    generator=simulation.Exhaustive(),
                    defaults=False,
                ),
                gen_choices=simulation.Uniform(
                    forced_choice=True,
                    multiple_choice=False,
                ),
            ))

    assert len(response.subject_packed) == 223
    def __init__(self, protocol, input_file, cache_size, associativity,
                 block_size):

        if protocol.lower() == MESI:
            self.protocol = Mesi
        elif protocol.lower() == DRAGON:
            self.protocol = Dragon
        else:
            sys.exit(WRONG_COMMAND)

        self.caches = [
            self.protocol(cache_size, associativity, block_size, i)
            for i in range(TOTAL_CORES)
        ]
        self.cores = [
            Core(input_file, i, self.caches[i]) for i in range(TOTAL_CORES)
        ]
        self.snooping = Snooping(self.caches)
예제 #54
0
    def run(self):
        self.core = Core(ORG.LSM, self.mem_size, self.block_size,
                         self.blocks_per_ss)
        for seq_seq in self.instruction_sequence_sequences:
            print([id(seq) for seq in seq_seq])

        while len(self.instruction_sequence_sequences) != 0:
            next_inst_seq = self.next_inst_seq()
            inst = next_inst_seq.fetch()
            Logger.trans_id = id(next_inst_seq)

            if next_inst_seq.exec_type == EXEC_TYPE.TRANSACTION:

                can_acquire_lock = self.can_acquire_locks(
                    id(next_inst_seq), inst)
                if (self.lock_manager.detect_deadlock()):
                    print(f"terminating {id(next_inst_seq)}")
                    inst = Instruction(ACTION.ABORT)
                    self.do_lock_stuff(id(next_inst_seq), inst)
                    self.remove_current_seq()
                    self.reset_seq_pc()
                    continue

                if can_acquire_lock:
                    self.do_lock_stuff(id(next_inst_seq), inst)
                else:
                    self.incr_seq_pc()
                    continue

            self.run_inst(inst, id(next_inst_seq))
            next_inst_seq.exec()

            # remove completed instruction sequences
            if next_inst_seq.completed():
                self.remove_current_seq()
                self.reset_seq_pc()
                continue

            self.incr_seq_pc()

        self.core.mem.print_cache()
        self.core.mem.flush()
        self.core.disk.kill_all_compaction_threads()
        Logger.write_log()
예제 #55
0
    def test_sys_write(self):
        LOG.debug("Testing sys_write() ...")
        core = Core()
        kernel = Kernel(core=core)

        msg = [ord(c) for c in "Hello!"]
        msg.append(0x00)
        LOG.debug(len(msg))
        addr = stdlib.malloc(len(msg))
        length = len(msg)

        core.EAX = 4  # sys_write
        core.EBX = 2  # stderr
        core.ECX = addr
        core.EDX = length
        core.set_memory_range(addr, msg)

        kernel.interrupt(0x80)  # handover to kernel

        stdlib.free(addr)
예제 #56
0
파일: seed.py 프로젝트: bopopescu/focus
    def seed_tickets(self):
        status, created = TicketStatus.objects.get_or_create(name="standard",
                                                             order_priority=1)
        priority, created = TicketPriority.objects.get_or_create(
            name="standard")
        type, created = TicketType.objects.get_or_create(name="Type",
                                                         company=self.company)

        print "tickets"
        for i in range(1, 10):
            ticket, created = Ticket.objects.get_or_create(
                title="Ticket %s" % i,
                description="dummy text",
                type=type,
                company=self.company,
                priority=priority,
                status=status)
            ticket.set_user(Core.current_user())
            ticket.save()
예제 #57
0
    def valid_permission(self, permissions, action, object, id=None, any=False):
        if isinstance(object, str):
            raise Exception(
                'Argument 2 in user.has_permission_to was a string; The proper syntax is has_permission_to(action, object)!')

        if Core.current_user().id == 1 and settings.DEBUG == True:
            return True

        object_id = 0

        if not isclass(object):
            object_id = object.id

        content_type = get_content_type_for_model(object)

        try:
            permissions[content_type.name][object_id]
        except  Exception, e:
            pass
예제 #58
0
 def decrypt_auth2object(cls, machine_code):
     key = machine_code.replace("9", ")").replace("1", "{")
     key = key.replace(")",
                       "1").replace("{",
                                    "9").replace("&",
                                                 "E").replace("%", "b")
     plain_text = RSAUtils.decrypt(key)
     device_group = plain_text.split("||")
     stu_code = device_group[0]
     c_volume_serial_number = device_group[1]
     mac_addr = device_group[2]
     hostname = device_group[3]
     device = Device(mac_addr=mac_addr,
                     hostname=hostname,
                     c_volume_serial_number=c_volume_serial_number)
     machine_code_auth = Core.machine_code_auth(stu_code,
                                                c_volume_serial_number,
                                                mac_addr, hostname)
     device.add_license(stu_code, machine_code_auth)
     return device
예제 #59
0
def calendar_day_json(request, year, month, day):
    date = datetime.strptime("%s-%s-%s" % (year, month, day), "%Y-%m-%d")

    list_hour_registrations = HourRegistration.objects.filter(
        date=date, creator=Core.current_user())

    registrations = [{
        'id': reg.id,
        'time_start': reg.time_start,
        'time_end': reg.time_end,
        'hours': str(reg.hours),
        'order': reg.order.id,
        'type': str(reg.type.id),
        'customer_name': reg.get_customer_name(),
        'order_name': reg.get_order_name(),
        'description': reg.description
    } for reg in list_hour_registrations]

    return HttpResponse(JSONEncoder().encode(registrations),
                        mimetype='application/json')
예제 #60
0
    def analysis_summary_stats(self, worker: Worker,
                               _config: None) -> ExperimentStats:
        subjects = []
        worker.set_work_size(len(self.subjects))

        with Core() as core:
            worker.interrupt = lambda: core.shutdown()

            for i, subject in enumerate(self.subjects):
                subjects.append(
                    core.call("summary", PackedSubjectC,
                              dataset.experiment_stats.SubjectC, subject))
                worker.set_progress(i + 1)

        ds = ExperimentStats(
            name=self.name + ' (info)',
            alternatives=self.alternatives,
        )
        ds.subjects = subjects
        return ds