예제 #1
0
파일: _NSTree.py 프로젝트: sysdeep/DNote
    def remove_node(self, node_uuid):
        """удаление заданной ноды из дерева"""
        log.debug("удаление заданной ноды из дерева: " + node_uuid)
        node = self.find_node_by_uuid(node_uuid)

        if node:
            self.__remove(node)
예제 #2
0
def get_investment_knowledge():
    page_index = request.values.get('page_index', default=1, type=int)
    page_size = request.values.get('page_size', default=10, type=int)

    page = []

    total_size = 0

    try:
        total_size = db.session.query(InvestmentKnowledge).count()

        result = db.session.query(InvestmentKnowledge).order_by(
            InvestmentKnowledge.priority).limit(page_size).offset(
                (page_index - 1) * page_size)

        for rec in result:
            item = {}
            item['id'] = rec.id
            item['title'] = rec.title
            item['category'] = rec.category
            item['content'] = rec.content

            page.append(item)

    except Exception as e:
        print("could not get investment knowledge, {}, {}, {}".format(
            page_index, page_size, repr(e)))

    ret = {"total": total_size, "page": page}

    log.debug(ret)

    return jsonify(ret)
예제 #3
0
def get_exam_questions():
    questions = []

    total_size = 0

    try:
        total_size = db.session.query(ExamQuestion).count()

        result = db.session.query(ExamQuestion).all()

        for rec in result:
            item = {}
            item['id'] = rec.id
            item['title'] = rec.title
            item['type'] = rec.type
            item['score'] = rec.score
            item['right_answer'] = rec.right_answer
            item['option_a'] = rec.option_a
            item['option_b'] = rec.option_b
            item['option_c'] = rec.option_c
            item['option_d'] = rec.option_d
            item['option_e'] = rec.option_e
            item['option_f'] = rec.option_f

            questions.append(item)

    except Exception as e:
        print("could not get exam questions, {}".format(repr(e)))

    ret = {"total": total_size, "questions": questions}

    log.debug(ret)

    return jsonify(ret)
예제 #4
0
def edit_favorite_thing(user_id, favorite_id):
    try:

        title = request.json.get("title")
        description = request.json.get("description")
        ranking = request.json.get("ranking")
        meta_data = request.json.get("meta_data")
        category = request.json.get("category")

        log.info(f"Editing new favorite thing:{favorite_id} for user:{user_id}")
        updates = {
            "title": title,
            "description": description,
            "ranking": ranking,
            "category": category,
            "meta_data": meta_data
        }
        filtered = {k: v for k, v in updates.items() if v is not None}
        updates.clear()
        updates.update(filtered)

        log.debug("Got item to update:{}".format(updates))

        favorite = core.update_favorite_thing(user_id, favorite_id, updates)

        resp = Response(json.dumps({"favorite": favorite}, default=str), status=200, mimetype='application/json')
    except Exception as ex:
        log.exception(ex)
        resp = Response(json.dumps(getattr(ex, "args", ex)), status=400, mimetype='application/json')
    return resp
예제 #5
0
파일: Tree.py 프로젝트: sysdeep/DNote
	def __make_tree(self):
		"""строим дерево"""
		log.debug("__make_tree")
		self.blockSignals(True)

		#--- все элементы корня
		root_items = self.tree.get_nodes_level(1)
		root_items.sort(key=lambda node: node.tree_lk)


		#--- запуск обхода дерева(рекурсия)
		for item in root_items:
			self.__wnode(item, self.tmodel)



		#--- выбираем элемент у которого флаг current
		if self.current_index:
			self.setCurrentIndex(self.current_index)
			self.__on_select(self.current_index)
		#--- если текущего нет - первый
		else:
			index = self.tmodel.index(0, 0)
			self.setCurrentIndex(index)
			self.__on_select(index)



		#--- разворачиваем элементы, у которых стоит флаг expanded
		for i in self.expand_indexes:
			self.expand(i)
		self.expand_indexes = []

		self.blockSignals(False)
예제 #6
0
 def __init__(self, **state):
     super().__init__(**state)
     class_full_name = str(self.__class__.__module__) + '.' + str(
         self.__class__.__name__)
     log.debug(
         'Successfully created Controller object from class: {}.'.format(
             class_full_name))
예제 #7
0
    def fetch_volume_files(self, volime_id):
        log.debug("fetch volume files")
        if not self.is_open:
            return []

        files = self.db.get_volume_root_files(volime_id)
        return files
예제 #8
0
    def handle_quit(self, action, parameter):
        log.debug("Emitting quit...")

        emit('quit')
        self.quit()

        log.debug("Goodbye! Application terminated.")
예제 #9
0
def main_function(config_file):
    # create and run the application, exit with the value returned by
    # running the program
    log.debug("Initializing services...")

    from app.config import config  # noqa

    config.load_config_file(config_file)

    from app.widgets import application  # noqa
    import app.style  # noqa

    log.debug("Loading Widgets usig GtkBuilder...")
    from app.builder import builder  # noqa

    builder.set_application(application)  # works without it
    builder.add_from_file(os.path.join(CURRENT_DIR, "layout.glade"))

    __.main_window = builder.get_object("main_window")
    __.welcome_sign = builder.get_object("welcome_sign")

    from app.layout_events import Layout_events

    builder.connect_signals(Layout_events)

    log.debug("Importing stories...")
    import app.stories  # noqa

    log.debug("Starting1 the Application...")
    exit_status = application.run(sys.argv)

    log.debug("Returning exit status value...")
    return exit_status
예제 #10
0
def login():
    if request.method == POST:
        form = request.form
        username = form["username"]
        password = form.get("password").encode("utf-8")
        res = db.hexists(username, "data")
        if res == 0:
            return render_template("login.html"), 404
        salt = db.hget(username, "passwd_salt").encode("utf-8")
        for i in range(10):
            hashed_passwd = bcrypt.hashpw(password, salt)
            password = hashed_passwd
        password = str(hashed_passwd)
        cor_password = db.hget(username, "passwd_hash")
        if password == cor_password:
            response = make_response(redirect(url_for('home')))
            sessionid = uuid.uuid4().hex
            response.set_cookie("app_session",
                                sessionid,
                                secure=True,
                                httponly=True,
                                samesite="Strict")
            db.hset("sessions_app", sessionid, username)
            log.debug("session is set ")
            threading.Thread(target=removeUserSession, args=(
                sessionid,
                600,
            )).start()
            time.sleep(0.2)
            return response, 200
        else:
            return render_template("login.html"), 403
    else:
        return render_template("login.html"), 200
예제 #11
0
def edit_info(slug):
    photo = Photo.query.filter(Photo.id == slug).first()
    form = PhotoForm(formdata=request.form, obj=photo)

    if form.validate_on_submit():
        photo.photo_title = form.photo_title.data
        photo.photo_description = form.photo_description.data
        try:
            photo.tags.append(Tag.query.filter_by(name=form.tags.data).first())
            log.debug("Photo before db '%s'." % (photo))
            db.session.commit()
            flash('Your photo edited')

            photo = Photo.query.filter(Photo.id == slug).first()
            log.debug("Photo after db '%s'." % (photo))
            tags = photo.tags
            log.info("User '%s' edit photo info '%s'." %
                     (current_user.username, photo.photo_title))
            return render_template('photos/photo_detail.html',
                                   photo=photo,
                                   tags=tags,
                                   user=current_user)
        except:
            redirect('photos.index')
    form = PhotoForm(obj=photo)
    return render_template('photos/edit_info.html', form=form)
예제 #12
0
    def pop(self, id):
        '''
        Removes the record identified by id from the dataset.
        Returns the data (if found) or None.
        '''
        if(not self.db_exists):
            return None
        url = self.url + '/' + self.db_name + '/' + id
        # first get it from the DB
        resp = self.ses.get(url)
        log.debug('ses.get(%s) => %d', url, resp.status_code)
        if(resp.status_code != 200):
            return None
        res = resp.json()
        del res['_id']
        rev = res.pop('_rev', None)
        if rev is None:
            return None

        # now let's delete it!
        url = url + '?rev=' + rev
        resp = self.ses.delete(url)
        log.debug('ses.delete(%s) => %d', url, resp.status_code)
        log.info('pop(%s) => %s', id, str(res))
        return res 
예제 #13
0
    def __new__(cls, clsname, superclasses, dict_):
        """
        Function reponsible for creating classes.
        
        In general every Gripy class is created on application startup.
        This method adjust attributes heritance, for example combining 
        class properties with parent classes ones.
        
        _ATTRIBUTES:
            * default_value --  As the name says.
            * type:             Valid type (e.g. int, str).
            * label:            Friendly name for attribute (used in a pg_property or Tree).
            * pg_property:      Kind of pg_property which deals with this attribute.
            * options_labels:   Options shown as valid for attribute (as shown in a wx.ComboBox).
            * options_values:   The truly options valid for attribute (returned from wx.ComboBox selection event).
            * 25/8/2018:        The least 4 above occours only in ui/mvc_classes/track_object.py and ui/mvc_classes/propgrid.py.
            
        _READ_ONLY:
            Properties that must be setted only during object initialization. 
            They cannot be deleted or changed (e.g. oid).
            
        """
        # Initializing class dictionary for _ATTRIBUTES and _READ_ONLY keys, if
        # they were not setted.
        if '_ATTRIBUTES' not in dict_:
            dict_['_ATTRIBUTES'] = OrderedDict()
        if '_READ_ONLY' not in dict_:
            dict_['_READ_ONLY'] = []
        # The method GripyObject.is_initialised is setted below.
        # The idea is deal with GripyObject._GripyMeta__initialised only in
        # this metaclass.
        dict_['is_initialised'] = lambda self: self.__dict__.get( \
                                            '_GripyMeta__initialised', False)
        # Time to create the new class...
        ret_class = super().__new__(cls, clsname, superclasses, dict_)

        # By default, _ATTRIBUTES and _READ_ONLY are incremented with every
        # superclass _ATTRIBUTES and _READ_ONLY.
        # If this behavior is not desired for _ATTRIBUTES, the key must be
        # setted with None as value.

        #        print('\n\n', clsname)
        #        print('\tATTR:', ret_class.__dict__['_ATTRIBUTES'])
        for superclass in superclasses:
            #            print('\t\tSUPER:', superclass)
            if '_ATTRIBUTES' in superclass.__dict__:
                for key, value in superclass.__dict__['_ATTRIBUTES'].items():
                    if key not in ret_class.__dict__['_ATTRIBUTES']:
                        #                        print('\t\t\tkv:', key, value)
                        ret_class.__dict__['_ATTRIBUTES'][key] = value
            if '_READ_ONLY' in superclass.__dict__:
                for item in superclass.__dict__['_READ_ONLY']:
                    if item not in ret_class.__dict__['_READ_ONLY']:
                        ret_class.__dict__['_READ_ONLY'].append(item)


#        print('\tTOTAL ATTR:', ret_class.__dict__['_ATTRIBUTES'])
        log.debug('Successfully created class: {}.'.format(clsname))
        return ret_class
예제 #14
0
def get_filter():
    if request.method == "POST":
        log.debug("call filter with argument")
        return render_template("filter.html",
                               payments=funcs.get_filtered_payments(
                                   request.form))
    log.debug("call filter without arg")
    return render_template("filter.html", payments=funcs.get_all_payments())
 def run(self):
     """Listens for new messages in Redis, and sends them to clients."""
     while True:
         for message in self.queue:
             for client in self.users:
                 gevent.spawn(self.send, client, message)
                 log.debug("sending %s, msg: %s", client, message)
         gevent.sleep(0.1)
예제 #16
0
def inbox(ws):
    """Receives incoming chat messages, inserts them into Redis."""
    while not ws.closed:
        # Sleep to prevent *constant* context-switches.
        gevent.sleep(0.1)
        message = ws.receive()
        log.debug(u'Inserting message: {}'.format(message))
        if message:
            chatRoom.add(message)
예제 #17
0
def validate_updateuserform(form):
    res = True
    msg = ""

    # Check firstname
    firstname = form.get("firstName")
    log.debug(firstname)
    firstname_regex = re.search(
        "[A-Z,a-z,Ą,Ć,Ę,Ł,Ń,Ó,Ś,Ź,Ż,ą,ć,ę,ł,ń,ó,ś,ź,ż]+", firstname)
    if firstname_regex == None or firstname_regex.group() != firstname:
        msg += "Imię jest niepoprawne! Powinno się składać z samych liter.\n"
        res = False

    # Check lastname
    lastname = form.get("lastName")
    log.debug(lastname)
    lastname_regex = re.search(
        "[A-Z,a-z,Ą,Ć,Ę,Ł,Ń,Ó,Ś,Ź,Ż,ą,ć,ę,ł,ń,ó,ś,ź,ż]+", lastname)
    if lastname_regex == None or lastname_regex.group() != lastname:
        msg += "Nazwisko jest niepoprawne! Powinno się składać z samych liter (może być dwu członowe oddzielone znakiem -).\n"
        res = False

    # Check phone
    phone = form.get("phone")
    phone_regex = re.search("[0-9]+", phone)
    if phone_regex == None or phone_regex.group() != phone or len(phone) < 9:
        msg += "Podany numer jest niepoprawny! Powinien być liczba, miec min 9 znakow oraz nie posiadac znakow bialych!\n"
        res = False

    # Check street
    street = form.get("street")
    if street == None or street == "":
        msg += "Ulica nie może być pusta!\n"
        res = False

    # Check streetNumber
    streetNumber = form.get("streetNumber")
    if streetNumber == None or streetNumber == "":
        msg += "Numer ulicy/mieszkania nie może być pusty!\n"
        res = False
    # Check postalCode
    postalCode = form.get("postalCode")
    postalCode_regex = re.search("[0-9]{2}-{1}[0-9]{3}", postalCode)
    if postalCode_regex == None or postalCode_regex.group() != postalCode:
        msg += "Podany kod pocztowy jest niepoprawny! Jego format to: XX-XXX! .\n"
        res = False
    # Check city
    city = form.get("city")
    if city == None or city == "":
        msg += "Miasto nie może być puste!\n"
        res = False
    # Check country
    country = form.get("country")
    if country == None or country == "":
        msg += "Kraj nie może być pusty!\n"
        res = False
    return res, msg
예제 #18
0
	def open_storage(self, path):
		"""
			открыть хранилище по заданному пути
		"""
		log.debug("SManager - open storage")
		self.storage_path = path
		self.storage = Storage(self.storage_path)
		# sevents.storage_opened()
		dbus.emit(dbus.STORAGE_OPENED, self.storage_path)
예제 #19
0
    def remove_node(self, node_uuid):
        """удаление заданной ноды из дерева"""
        log.debug("удаление заданной ноды из дерева: " + node_uuid)
        node = self.get_node(node_uuid)

        if node:
            return self.__remove(node)
        else:
            return False
예제 #20
0
 def create_node(self, parent_node_uuid, node_uuid, name=""):
     """создание новой ноды от родителя"""
     log.debug("создание новой ноды для родителя: " + parent_node_uuid)
     parent_node = self.nodes_map[parent_node_uuid]
     new_node = NSNode()
     new_node.uuid = node_uuid
     new_node.name = name
     self.__insert_node(parent_node, new_node)
     return new_node
예제 #21
0
    def do_startup(self):
        log.debug("Startup...")

        Gtk.Application.do_startup(self)

        # important part when using GtkWindow with GtkBuilder
        self.add_window(__.main_window)
        __.main_window.show_all()

        log.debug('Menu loaded...')
예제 #22
0
    def write_file(self):
        log.debug("write project: " + self.file_path)

        tree_data = self.tree.export()

        data = {"name": self.name, "tree": tree_data}

        data_json = json.dumps(data, indent=4)

        with open(self.file_path, "w", encoding="utf-8") as fd:
            data = fd.write(data_json)
예제 #23
0
 def deactivatePluginByName(self, name):
     # TODO: Comments
     """
     Desactivate a plugin corresponding to a given name.
     """
     plugin_to_deactivate = self.getPluginByName(name)
     if plugin_to_deactivate is not None:
         log.debug("Deactivating plugin: %s" % (name))
         plugin_to_deactivate.deactivate()
         return plugin_to_deactivate
     return None
예제 #24
0
    def move_node(self, node_uuid, dest_uuid):
        """перемещение заданной ноды(ветви) в указнного родителя"""
        log.debug("перемещение ноды")

        node = self.get_node(node_uuid)
        parent_node = self.get_node(dest_uuid)

        #--- remove node(branch)
        nodes_branch = self.__remove_branch(node)

        #--- insert node(branch)
        self.__insert_branch(parent_node, nodes_branch)
예제 #25
0
파일: Nodes.py 프로젝트: sysdeep/DNote
	def create_node(self, content=""):
		log.debug("создание новой ноды")

		node_uuid = str(uuid.uuid1())
		node_dir_path = os.path.join(self.nodes_path, node_uuid)
		os.mkdir(node_dir_path)

		node = Node(node_uuid, node_dir_path)

		node.make(content)

		return node
예제 #26
0
파일: Storage.py 프로젝트: sysdeep/DNote
    def create_node(self, parent_node_uuid, name, ntype="text", content=""):
        """создать новую ноду"""
        log.debug("создание новой ноды")

        #--- создание файлов ноды
        self.nnode = self.nmanager.create_node(content)

        #--- создание ноды в файле проекта
        self.pnode = self.pmanager.create_node(parent_node_uuid,
                                               self.nnode.uuid, name, ntype)

        sevents.node_created()
        sevents.project_updated()
예제 #27
0
파일: NSTree.py 프로젝트: sysdeep/DNote
    def move_node_up(self, node_uuid):
        """перемещение ноды вверх"""

        prev_node = self.find_prev_node(node_uuid)

        if prev_node is None:
            log.debug("prev node is None")
            return False

        node = self.get_node(node_uuid)

        self.__swap_nodes(node, prev_node)
        return True
예제 #28
0
	def run(self):
		log.debug("starting WalkerDispatcher")

		while True:

			data = QUE_WALKER.get()
			if data is None:
				break


			# print(data)
			# QApplication.postEvent(self.parent, Event(data))
			self.msg.emit(data)
예제 #29
0
    def load(self):
        """загрузка данных проекта по указанному пути"""
        # self.project_path = project_path
        log.debug("загрузка проекта: " + self.project_path)
        self.file_path = os.path.join(self.project_path, self.file_name)

        with open(self.file_path, "r", encoding="utf-8") as fd:
            data_json = fd.read()

        data = json.loads(data_json)

        #--- set data
        self.name = data["name"]
        self.tree.load(data["tree"])
예제 #30
0
파일: Tree.py 프로젝트: sysdeep/DNote
	def __remake_tree(self):
		log.debug("remake tree")

		self.tree = storage.get_tree()

		# print(self.storage)

		self.current_uuid 	= None			# текущий uuid элемента
		self.current_index 	= None			# элемент с флагом current = True - для автоматического выбора(modelIndex)
		self.expand_indexes = []			# список элементов, которые необходимо раскрыть


		# print(self.storage.project_path)
		self.__update_tree()
예제 #31
0
파일: models.py 프로젝트: Kellel/reports
 def save(self, session):
     session.add(self)
     log.debug("SAVING OBJECT %s COMPLETE", self.id)