コード例 #1
0
    def post(self):
        call_type = self.request.get('call', 'calculate')
        if not self.is_valid_input(call_type, HOME_CALL_TYPE):
            return self.render_json({'error': ERROR_INVALID_PARAM % 'call'})

        if call_type == 'calculate':
            calculation_object = self.request.get('cal_obj', '')
            do_logging(calculation_object)
            value = None
            error = None

            try:
                value = eval(calculation_object)
            except SyntaxError:
                do_logging(traceback.format_exc())
                error = "Invalid Syntax"

            if not error:
                Logs.add_obj(**{'user_name': self.request.cookies.get('user', 'random'),
                                'cal_obj': calculation_object + " = %s" % value,
                                'call_ip': self.request.remote_addr})
            return self.render_json({'error': error,
                                     'value': value,
                                     'cal': calculation_object})

        elif call_type == 'logs':
            cursor = self.request.get('cursor', '')
            logs = Logs.get_logs(cursor)
            return self.render_json(logs)
コード例 #2
0
    def put_unit(self, type_id: int = None, path_id: int = None, base_unit: BaseUnit = None, path: Path = None) -> None:
        fail = False
        if type_id is not None and type(type_id) is not int:
            Logs.show_log("put_unit function called with invalid type_id argument!")
            fail = True
        if path_id is not None and type(path_id) is not int:
            Logs.show_log("put_unit function called with invalid path_id argument!")
            fail = True
        if base_unit is not None and type(base_unit) is not BaseUnit:
            Logs.show_log("put_unit function called with invalid base_unit argument")
            fail = True
        if path is not None and type(path) is not Path:
            Logs.show_log("put_unit function called with invalid path argument")
            fail = True
        if fail is True:
            return

        if base_unit is not None:
            type_id = base_unit.type_id
        if path is not None:
            path_id = path.id
        if path_id is None or type_id is None:
            return None
        if type_id is None:
            Logs.show_log("type_id is None in cast_area spell function call!")
            return

        message = Message(turn=self.get_current_turn(),
                          type="putUnit",
                          info={
                              "typeId": type_id,
                              "pathId": path_id
                          })
        self._queue.put(message)
コード例 #3
0
 def get_area_spell_targets(self,
                            center: Cell = None,
                            row: int = None,
                            col: int = None,
                            spell: Spell = None,
                            type_id: int = None) -> List["Unit"]:
     if spell is None:
         if type_id is not None:
             spell = self.get_cast_spell_by_id(type_id)
         else:
             return []
     if type(spell) is not Spell:
         Logs.show_log("invalid spell chosen in get_area_spell_targets")
         return []
     if not spell.is_area_spell():
         return []
     if center is None:
         center = Cell(row, col)
     ls = []
     for i in range(max(0, center.row - spell.range),
                    min(center.row + spell.range + 1, self._map.row_num)):
         for j in range(
                 max(0, center.col - spell.range),
                 min(center.col + spell.range + 1, self._map.col_num)):
             cell = self._map.get_cell(i, j)
             for u in cell.units:
                 if self._is_unit_targeted(u, spell.target):
                     ls.append(u)
     return ls
コード例 #4
0
ファイル: world.py プロジェクト: princeofpersian137667/saliok
 def get_cell_units(self, cell: Cell = None, row: int = None, col: int = None) -> List[Unit]:
     if cell is None:
         if row is None and col is None:
             Logs.show_log("get_paths_crossing cell function called with no valid argument")
             return []
         cell = self._map.get_cell(row, col)
     if not isinstance(cell, Cell):
         Logs.show_log("Given cell is invalid!")
         return []
     return cell.units
コード例 #5
0
 def get_cell_units(self, cell=None, row=None, col=None):
     if cell is None:
         if row is None and col is None:
             Logs.show_log("get_paths_crossing cell function called with no valid argument")
             return None
         cell = self.map.get_cell(row, col)
     if not isinstance(cell, Cell):
         Logs.show_log("Given cell is invalid!")
         return
     return cell.units
コード例 #6
0
    def upgrade_unit_damage(self, unit: Unit = None, unit_id: int = None):
        if unit is not None:
            unit_id = unit.unit_id

        if unit_id is not None and type(unit_id) is int:
            self._queue.put(
                Message(type="damageUpgrade",
                        turn=self.get_current_turn(),
                        info={"unitId": unit_id}))
        else:
            Logs.show_log("invalid unit or unit_id in upgrade_unit_damage")
コード例 #7
0
 def choose_hand(self, base_units: List[BaseUnit]) -> None:
     message = Message(type="pick", turn=self.get_current_turn(), info=None)
     if base_units is not None:
         for base_unit in base_units:
             if type(base_unit) is not BaseUnit:
                 Logs.show_log("base_units is not an array of BaseUnits")
                 return
         message.info = {"units": [unit.type_id for unit in base_units]}
         self._queue.put(message)
     else:
         Logs.show_log("choose_hand function called with None base_units")
コード例 #8
0
 def _get_friend_by_id(self, player_id):
     if self.player.player_id == player_id:
         return self.player_friend
     elif self.player_friend.player_id == player_id:
         return self.player
     elif self.player_first_enemy.player_id == player_id:
         return self.player_second_enemy
     elif self.player_second_enemy.player_id == player_id:
         return self.player_first_enemy
     else:
         Logs.show_log("get_friend_by_id function no player with given player_id")
         return None
コード例 #9
0
    def choose_hand_by_id(self, type_ids):
        message = Message(type="pick", turn=self.get_current_turn(), info=None)
        if type_ids is not None:
            for type_id in type_ids:
                if type(type_id) is not int:
                    Logs.show_log("type_ids are not int")
                    return

            message.info = {"units": type_ids}
            self.queue.put(message)
        else:
            Logs.show_log("choose_hand_by_id function called with None type_eds")
コード例 #10
0
    def get_paths_crossing_cell(self, cell=None, row=None, col=None):
        if cell is None:
            if row is None or col is None:
                Logs.show_log("get_paths_crossing cell function called with no valid argument")
                return
            cell = self.map.get_cell(row, col)

        if not isinstance(cell, Cell):
            Logs.show_log("Given cell is invalid!")
            return

        paths = []
        for p in self.map.paths:
            if cell in p.cells:
                paths.append(p)
        return paths
コード例 #11
0
ファイル: api.py プロジェクト: ORJIKALU/favourites
 def post(self):
     category_name = request.args.get("category_name").upper()
     item = request.args.get("title").lower()
     if not item:
         abort(404, message="please enter name for item")
     if not category_name:
         abort(404, message="please enter category for item")
     if not request.form.get("ranking"):
         abort(404, message="please a rank for item")
     if request.form.get("description"):
         if len(request.form.get("description")) < 10:
             abort(404, message="please provide more description for item")
     titles = Item.query.filter_by(title=item)
     current_category = Category.query.filter_by(id=category_name).first()
     for title in titles:
         if category_name == current_category.name and title.title == item:
             abort(404, message="{} already exist in {}".format(item, category_name))
     category_row = Category.query.filter_by(name=category_name).first()
     item = Item(title = request.args.get("title").lower(), description = request.args.get("description"), category_name =category_row.name,category_id=category_row.id, rank=request.args.get("ranking"))
     db.session.add(item)
     db.session.commit()
     reorder_priorities(int(category_row.id))
     log = Logs(title=item.title,category=item.category_name, action="added")
     db.session.add(log)
     db.session.commit()
     return jsonify({'Success':"{} added successfully to {}".format(item.title, item.category_name)})
コード例 #12
0
ファイル: application.py プロジェクト: ORJIKALU/favourites
def add_new_fav():
    category_id = int(request.form.get("choose_category"))
    item = request.form.get("title").lower()
    if not item:
        flash("Item must have a name", category="error")
        return redirect("/")
    if not category_id:
        flash("please select a category", category="error")
        return redirect("/")
    if not request.form.get("ranking"):
        flash("Please select a rank for item", category="error")
        return redirect("/")
    if request.form.get("description"):
        if len(request.form.get("description")) < 10:
            flash('please describe the item in more details')
            return redirect("/")
    titles = Item.query.filter_by(title=item)
    current_category = Category.query.filter_by(id=category_id).first()
    for title in titles:
        if category_id == int(current_category.id) and title.title == item:
            flash(title.title + " already exist in " + current_category.name,
                  category="error")
            return redirect("/")
    category_row = Category.query.filter_by(
        id=int(request.form.get("choose_category"))).first()
    item = Item(title=request.form.get("title").lower(),
                description=request.form.get("description"),
                category_name=category_row.name,
                category_id=category_row.id,
                rank=request.form.get("ranking"))
    db.session.add(item)
    db.session.commit()
    reorder_priorities(int(request.form.get("choose_category")))
    titles = Item.query.filter_by(
        title=request.form.get("title").lower()).first()
    if request.form.get("no_of_tags"):
        n = int(request.form.get("no_of_tags"))
        for i in range(n):
            j = i + 1
            key_name = "key" + str(j)
            value_name = "value" + str(j)
            if request.form.get(key_name) and request.form.get(value_name):
                tag = Tags(key=request.form.get(key_name),
                           value=request.form.get(value_name),
                           item_id=titles.id)
                db.session.add(tag)
    log = Logs(title=item.title, category=item.category_name, action="added")
    db.session.add(log)
    db.session.commit()
    flash(request.form.get("title") + " added to " + current_category.name,
          category="message")

    return redirect("/")
コード例 #13
0
ファイル: server.py プロジェクト: inview-team/Owl
def get_logs():
    if request.method == 'POST':
        time = str(request.json.get('time'))
        info = str(request.json.get('info'))

        log_request = Logs(id=None, time=time, info=info)
        db.session.add(log_request)
        db.session.commit()
    else:
        records = Logs.query.all()
        print(records)
        return jsonify({'logs': [record.serialize() for record in records]})
コード例 #14
0
ファイル: lianjia.py プロジェクト: lastcaveman/lianjia
def get_data(url, payload, method='GET', session=None):
    payload['request_ts'] = int(time.time())

    headers = {
        'User-Agent': 'HomeLink7.7.6; Android 7.0',
        'Connection': 'close',
        'Authorization': get_token(payload)
    }

    q = requests.session()
    q.keep_alive = False
    q.adapters.DEFAULT_RETRIES = 30
    if method == 'GET':
        r = q.get(url, params=payload, headers=headers)
    else:
        r = q.post(url, params=payload, data=payload, headers=headers)

    # if session:
    #     if method == 'GET':
    #         r = session.get(url, params=payload, headers=headers)
    #     else:
    #         r = session.post(url, data=payload, headers=headers)
    # else:
    #     if method == 'GET':
    #         r = requests.get(url, params=payload, headers=headers)
    #     else:
    #         r = requests.post(url, params=payload, data=payload, headers=headers)
    log = Logs()
    log.query = r.request.url
    log.result = r.content
    log.save()
    return (r.json())
コード例 #15
0
    def cast_area_spell(self,
                        center: Cell = None,
                        row: int = None,
                        col: int = None,
                        spell: Spell = None,
                        spell_id: int = None) -> None:
        if spell is None:
            if spell_id is None or type(spell_id) is not int:
                Logs.show_log("no valid spell selected in cast_area_spell!")
                return
            spell = self.get_spell_by_id(spell_id)
        if type(spell) is not Spell:
            Logs.show_log("no valid spell selected in cast_area_spell!")
            return

        if row is not None and col is not None:
            center = self._map.get_cell(row, col)

        if center is not None:
            message = Message(type="castSpell",
                              turn=self.get_current_turn(),
                              info={
                                  "typeId": spell.type_id,
                                  "cell": {
                                      "row": center.row,
                                      "col": center.col
                                  },
                                  "unitId": -1,
                                  "pathId": -1
                              })
            self._queue.put(message)
        else:
            Logs.show_log("invalid cell selected in cast_area_spell")
コード例 #16
0
ファイル: api.py プロジェクト: ORJIKALU/favourites
 def post(self):
     if request.args.get("category"):
         new_category = request.form.get("category").upper()
         current = Category.query.filter_by(name=new_category).first()
         if current:
             abort(404, message="{} already exist".format(new_category))
         category = Category(name=new_category)
         db.session.add(category)
         db.session.commit()
         log = Logs(action="added", category=category.name)
         db.session.add(log)
         db.session.commit()
         return jsonify({'Success':"{} added successfully".format(new_category)})
     else:
         abort(404, message="please enter name for category")
コード例 #17
0
ファイル: application.py プロジェクト: ORJIKALU/favourites
def add_category():
    if request.form.get("category"):
        new_category = request.form.get("category").upper()
        current = Category.query.filter_by(name=new_category).first()
        if current:
            flash(new_category + " already exist in categories",
                  category=error)
            return redirect("/")
        category = Category(name=new_category)
        db.session.add(category)
        db.session.commit()
        log = Logs(action="added", category=category.name)
        db.session.add(log)
        db.session.commit()
        flash(request.form.get("category").upper() + " added to Categories",
              category="message")
        return redirect("/")
    else:
        flash("category must have a name", category="error")
        return redirect("/")
コード例 #18
0
 def get(self):
     logs = Logs.get_logs()
     template = JINJA_ENVIRONMENT.get_template(TEMPLATE_FOLDER + '/' + 'index.html')
     self.response.write(template.render(**logs))
コード例 #19
0
    def cast_unit_spell(self,
                        unit: Unit = None,
                        unit_id: int = None,
                        path: Path = None,
                        path_id: int = None,
                        cell: Cell = None,
                        row: int = None,
                        col: int = None,
                        spell: Spell = None,
                        spell_id: int = None) -> None:
        if spell is None and spell_id is None:
            Logs.show_log(
                "cast_unit_spell function called with no spell input!")
            return None
        if spell is None:
            if type(spell_id) is not int:
                Logs.show_log(
                    "spell_id is not an integer in cast_unit_spell function call!"
                )
                return
            spell = self.get_spell_by_id(spell_id)

        if row is not None and col is not None:
            if type(row) is not int or type(col) is not int:
                Logs.show_log(
                    "row and column arguments are invalid in cast_unit_spell function call"
                )
                return
            cell = Cell(row, col)

        if unit is not None:
            if type(unit) is not Unit:
                Logs.show_log(
                    "unit argument is invalid in cast_unit_spell function call"
                )
                return
            unit_id = unit.unit_id
        if path is not None:
            if type(path) is not Path:
                Logs.show_log(
                    "path argument is invalid in cast_unit_spell function call"
                )
                return
            path_id = path.id

        if type(unit_id) is not int:
            Logs.show_log(
                "unit_id argument is invalid in cast_unit_spell function call")
            return

        if type(path_id) is not int:
            Logs.show_log(
                "path_id argument is invalid in cast_unit_spell function call")
            return

        message = Message(type="castSpell",
                          turn=self.get_current_turn(),
                          info={
                              "typeId": spell.type_id,
                              "cell": {
                                  "row": cell.row,
                                  "col": cell.col
                              },
                              "unitId": unit_id,
                              "pathId": path_id
                          })
        self._queue.put(message)
コード例 #20
0
    def post(self):
        if self.is_connected() and get_is_admin_from_id(
                self.request.cookies.get('user_id').split('|')[0]):
            if self.request.get('id') and self.request.get('id') != "":
                log_sentence = None

                #Update absentee entry
                absentee = get_absentee_from_id(self.request.get('id'))

                if self.request.get('justified'):
                    absentee.justification_bool = True
                    log_sentence = "%(admin)s accepted the absence of %(student)s. (%(lesson)s from " \
                                   "%(hour_start)s to %(hour_end)s"
                else:
                    absentee.justification_bool = False
                    log_sentence = "%(admin)s refused the absence of %(student)s. (%(lesson)s from " \
                                   "%(hour_start)s to %(hour_end)s"

                if self.request.get('justification') and self.request.get(
                        'justification') != "":
                    absentee.justification_text = self.request.get(
                        'justification')
                else:
                    absentee.justification_text = "/"

                absentee.put()
                user_id = self.request.cookies.get('user_id').split('|')[0]
                account = get_account_from_id(user_id)

                log_sentence = log_sentence % {
                    'admin': account.name,
                    'student': absentee.student_name,
                    'lesson': absentee.class_title,
                    'hour_start': absentee.start_hour,
                    'hour_end': absentee.end_hour
                }

                # I don't know why, the date won't accept the same way
                log_sentence = log_sentence + " on the " + absentee.class_date + ".)"
                Logs(date_time=self.date_details.now(),
                     category="absentee control",
                     author=account.name,
                     description=log_sentence).put()

                #Redirect to correct page
                self.response.headers.add_header('Set-Cookie',
                                                 "message=Saved; Path = '/'")
                self.redirect('/administration/show_absentee/?id=' +
                              self.request.get('id'))

            else:
                self.render("message.html",
                            title="Invalid URL",
                            text="It seems you're using an invalid URL")

        else:
            self.render(
                "message.html",
                title="Access forbidden",
                text="It seems you're not an administrator nor a connected user"
            )
コード例 #21
0
    def get(self):
        if self.is_connected() and get_is_admin_from_id(
                self.request.cookies.get('user_id').split('|')[0]):
            accounts = get_all_accounts()
            error_messages = []
            infos_messages = []

            if self.request.get('action') and self.request.get('user'):
                action = self.request.get('action')
                user = self.request.get('user')
                now = datetime.datetime.now()
                author = get_username_from_id(
                    self.request.cookies.get('user_id').split('|')[0])

                if action == "delete":
                    if delete_user_from_login(user):
                        infos_messages.append("User " + user +
                                              " has been deleted")
                        Logs(date_time=now,
                             category="members_deletion",
                             author=author,
                             description=author + " deleted" + " account " +
                             user).put()
                    else:
                        error_messages.append("Error while deleting user " +
                                              user + ". Please try again")

                elif action == "grant_admin":
                    if grant_admin_from_login(user):
                        infos_messages.append(
                            "Admin privileges have been granted to user " +
                            user)
                        Logs(date_time=now,
                             category="members_privileges",
                             author=author,
                             description=author + " granted" +
                             " admin privileges to " + user).put()
                    else:
                        error_messages.append(
                            "Error while granting admin privileges to user " +
                            user)

                elif action == "remove_admin":
                    if remove_admin_from_login(user):
                        infos_messages.append(
                            "Admin privileges have been removed from user " +
                            user)
                        Logs(date_time=now,
                             category="members_privileges",
                             author=author,
                             description=author + " removed" +
                             " admin privileges from " + user).put()
                    else:
                        error_messages.append(
                            "Error while removing admin privileges from user "
                            + user)

                elif action == "grant_teacher":
                    if grant_teacher_from_login(user):
                        infos_messages.append(
                            "Teacher privileges have been granted to user " +
                            user)
                        Logs(date_time=now,
                             category="members_privileges",
                             author=author,
                             description=author + " granted" +
                             " teacher privileges to " + user).put()
                    else:
                        error_messages.append(
                            "Error while granting teacher privileges to user "
                            + user)

                elif action == "remove_teacher":
                    if remove_teacher_from_login(user):
                        infos_messages.append(
                            "Teacher privileges have been removed from user " +
                            user)
                        Logs(date_time=now,
                             category="members_privileges",
                             author=author,
                             description=author + " removed" +
                             " teacher privileges from " + user).put()
                    else:
                        error_messages.append(
                            "Error while removing teacher privileges from user "
                            + user)

                else:
                    error_messages.append(
                        "It seems you are using an invalid URL. No action will be done."
                    )

                time.sleep(1)
                accounts = get_all_accounts()
                self.render("administration_members.html",
                            accounts=accounts,
                            error_messages=error_messages,
                            infos_messages=infos_messages)

            elif self.request.get('action') and not self.request.get('user') or self.request.get('user')\
                    and not self.request.get('action'):
                error_messages.append(
                    "It seems you are using an invalid URL. No action will be done."
                )
                self.render("administration_members.html",
                            accounts=accounts,
                            error_messages=error_messages)

            else:
                self.render("administration_members.html", accounts=accounts)

        else:
            self.render(
                "message.html",
                title="Access forbidden",
                text="It seems you're not an administrator nor a connected user"
            )
コード例 #22
0
    def post(self):
        # Test user connexion and privileges
        if self.is_connected() and get_is_teacher_from_id(
                self.request.cookies.get('user_id').split('|')[0]):
            #First, get the class the teacher should have right now
            class_date = self.date_details.strftime("%d/%m/%Y")
            teacher_name = get_account_from_id(
                self.request.cookies.get('user_id').split('|')[0]).name
            class_to_display = self.filter_teacher_class(
                teacher_name, self.date_details.strftime("%H:%M"), class_date)

            # If there's a class
            if class_to_display is not None:
                # Then, we get the students for this class
                students_list = []
                groups = self.ade_communicator.get_students_groups()

                for group_name in groups:
                    for group_to_find in class_to_display['groups']:
                        if re.match(group_to_find, group_name) is not None:
                            temp = []
                            for student in groups[group_name]:
                                temp.append({
                                    "name": student,
                                    "group": group_name
                                })

                            students_list.extend(temp)

                students_list.sort(key=lambda x: x['name'])

                temp = students_list
                students_list = []
                email_uniq = []
                current_month = int(self.date_details.strftime("%m"))
                re_2a = re.compile(r"^2A .*")
                re_2ag = re.compile(r"^2A G.*")

                for student in temp:
                    #Diff groups if class is for 2A
                    if re_2a.match(student['group']):
                        #If we're on semester 2 => majors groups
                        if 1 <= current_month <= 8:
                            if student['name'][
                                    'mail'] not in email_uniq and not re_2ag.match(
                                        student['group']):
                                students_list.append(student)
                                email_uniq.append(student['name']['mail'])

                        #Else normal groups
                        else:
                            if student['name'][
                                    'mail'] not in email_uniq and re_2ag.match(
                                        student['group']):
                                students_list.append(student)
                                email_uniq.append(student['name']['mail'])

                    #Else we treat them normally
                    else:
                        if student['name']['mail'] not in email_uniq:
                            students_list.append(student)
                            email_uniq.append(student['name']['mail'])

                # Purge current absentees
                present_absentees = get_absentees_for_class(
                    class_to_display['class_name'],
                    class_to_display['teacher_name'], class_date,
                    class_to_display['start_time'],
                    class_to_display['end_time'])

                if len(present_absentees) != 0:
                    Logs(date_time=self.date_details.now(),
                         category="absentees mark",
                         author=teacher_name,
                         description=teacher_name +
                         " deleted all absentees for class " +
                         class_to_display['class_name'] + " (" + class_date +
                         " from " + class_to_display['start_time'] + " to " +
                         class_to_display['end_time'] + ")").put()

                db.delete(present_absentees)

                #Check who is present now from post argument
                for student in students_list:
                    name = student['name']['name']
                    mail = student['name']['mail']

                    if self.request.get(mail + "|" + name + "|box"):
                        absentee = Absentees(
                            student_name=name,
                            student_email=mail,
                            student_group=student['group'],
                            class_title=class_to_display['class_name'],
                            teacher_name=class_to_display['teacher_name'],
                            start_hour=class_to_display['start_time'],
                            end_hour=class_to_display['end_time'],
                            class_date=class_date,
                            justification_bool=False,
                            justification_text="/")
                        absentee.put()

                        Logs(date_time=datetime.datetime.now(),
                             category="absentees mark",
                             author=teacher_name,
                             description=teacher_name + " marked " +
                             absentee.student_name + " (" +
                             absentee.student_group + ") as absent for " +
                             absentee.class_title + " (" +
                             absentee.class_date + " from " +
                             absentee.start_hour + " to " + absentee.end_hour +
                             ")").put()

                # Useful to avoid bug while writing and querying
                time.sleep(1)
                self.redirect('/students/absentees/')
            # Else, congrats, the teacher doesn't have to do anything
            else:
                self.redirect('/students/absentees/')

        else:
            self.render(
                "message.html",
                title="Access fobidden",
                text="It seems you're not a teacher nor a connected user")