def guardarExtraccion(): badflag = False if not os.path.exists("caracteristicas"): error = InputError("Faltan las características de la investigación!!") st.sidebar.write(error) badflag = True if not os.path.exists("tareas_def"): error = InputError("Faltan las tareas visuales!!") st.sidebar.write(error) badflag = True if not os.path.exists("paper_selected"): error = InputError("Falta seleccionar el paper!!") st.sidebar.write(error) badflag = True if badflag: return False with open('paper_selected', 'r') as fp: paper_dict = json.loads(json.load(fp)) paper = Paper.objects.get(doi=paper_dict["_id"]) with open('caracteristicas', 'r') as fp: caracteristicas = json.load(fp) paper.research_goal = caracteristicas["Objetivo"] paper.viticultural_aspects = caracteristicas["Aspectos"] paper.practical_contibution = caracteristicas["Práctica"] with open('tareas_def', 'r') as fp: tasks = json.load(fp) paper.visual_tasks = [] for key in tasks: task_dict = tasks[key] task = Visual_Task.from_json(json.dumps(task_dict)) paper.visual_tasks.append(task) paper.save() st.sidebar.success( "Se han guardado los datos extraidos en la base de datos.") st.sidebar.json(paper.to_json())
def auth_login(email, password): """ Given a registered users' email and password logs the user in by generating a valid token for the session Raises: - InputError: Email doesn't belong to any user in the database - InputError: Password is incorrect Returns: { user_id (int) token (str) } """ users = User.query.all() # Find the user object associated with the email for each_user in users: if each_user.email == email: if each_user.password == hashlib.sha256( password.encode()).hexdigest(): # User has been verified once this block is reached generated_token = generate_token(each_user) # printColour("Returning: {}".format({ # "user_id": each_user.id, # "token": generated_token # }), colour="blue") return { "user_id": each_user.id, "token": generated_token, "username": each_user.username, "profile_img_url": each_user.bio.profile_img_url } # Password is incorrect raise InputError(description="Password is incorrect") # If program execution reaches here, email does not exist raise InputError(description="Email doesn't exist")
def users_profile_setemail(token, email): """ Update the authorised user's email address Parameters: token (str) email (str) Returns: {} """ verify_token(token) user = get_user_from_token(token) if not user: raise InputError(description="Target user doesn't exist") # If the email is unchanged, do nothing if user.email == email: return # The supplied email must pass the email regex format if not email_is_legit(email): raise InputError(description="Email entered is not a valid email") # Email mustn't be in use by any existing user existing_user = User.query.filter_by(email=email).first() if existing_user: raise InputError(description="{} is being used by another user".format(email)) user.email = email db.session.commit()
def message_send(token, channel_id, message): """ Sends a message to the selected channel. Parameters: token (str) channel_id (int) message (str) Returns: { message_id } """ verify_token(token) if not message: raise InputError("Message can't be empty") if len(message) > 1000: raise InputError("Message is over 1000 characters") user = get_user_from_token(token) selected_channel = select_channel(channel_id) # Raise error if the user is not a part of the channel they are trying to message in if not is_user_member(user, selected_channel): raise AccessError( description="User is not a member of channel with channel_id") sent_message = Message(channel=selected_channel, user=user, message=message) db.session.add(sent_message) db.session.commit() return {"message_id": sent_message.id}
def downsize_image(self, new_xy: tuple, image_to_mod: Image.Image = None): """ Downsize image, default image is self.image_PIL. Returns: image : Image.Image : PIL image cropped """ image = self.original_PIL.convert( 'L') if image_to_mod is None else image_to_mod new_x = new_xy[0] new_y = new_xy[1] if not isinstance(new_x, int) or not isinstance(new_y, int): message = 'Attempting to downsize image with non int dimentions.' raise InputError(message) #Check the ensure the dimentions are within the image size if new_x > image.width: message = 'Attempting to "upsize" the image horizontally.' raise InputError(message) if new_y > image.height: message = 'Attempting to "upsize" the image vertically.' raise InputError(message) #Modify the image. try: image = image.resize(new_xy) except Exception as e: message = 'Unknown error occured downsizing image.' raise UnknownError(message, e) #Update data members if nessecary. if image_to_mod is None: self.modified_PIL = image self.modified_tkinter = self.get_window_image(image) self.modified_array = self.image_as_array(image) return image
def channels_messages(token, channel_id, start, limit=50): """ Given a channel that the user is a member of, returns up to a specified maximum number of messages from a starting index. Messages are ordered in ascending recency, so the message at index 0 is the most recent. Parameters: token (str) channel_id (int) start (int) limit (int) Returns: { messages, exhausted } Where: messages: list of message dictionary: { message_id, user_id, message, time_created, is_author } exhausted: bool indicating whether the there any more messages left to fetch """ # check parameters are all valid and raise exception if they aren't # add user_id, associated first name and last name into channel_id dictionary (or storage) verify_token(token) user = get_user_from_token(token) if not user: raise AccessError(description="Invalid Token") selected_channel = select_channel(channel_id) if not selected_channel: raise InputError(description="Channel ID is not a valid channel") if is_user_member(user, selected_channel) is False: raise AccessError(description="You are not a member of this channel") # Loop through 50 message dictionaries of list starting from start index messsages_list = selected_channel.messages_sent messsages_list.sort(key=(lambda x: x.time_created)) payload = { "messages": [], "exhausted": True } if not messsages_list: # printColour("Results: {}".format(payload), colour="blue") return payload if start >= len(messsages_list): raise InputError(description="Starting index is greater than or equal to the total number of messages in the channel") if not (start + limit >= len(messsages_list)): messages["exhausted"] = False for i, message in enumerate(messsages_list[start :], start=1): payload["messages"].append({ "message_id": message.id, "user_id": message.user_id, "message": message.message, "time_created": message.time_created.timestamp(), "is_author": message.user_id == user.id }) if i == limit: break # printColour("Results: {}".format(payload), colour="blue") return payload
def d(self, email, password, first_name=None, last_name=None): if not email or not validate_email(email): raise InputError(email, [2]) if not password: raise InputError('Password', error_messages[3]) if first_name: if not all(x.isalpha() or x.isspace() for x in first_name): raise InputError(first_name, error_messages[4]) if last_name: if not last_name.isalpha(): raise InputError(last_name, error_messages[4]) f(self, email, password, first_name, last_name)
def auth_signup(email, password, username): """ Creates a new account, given a user's email and password. Returns a dict containing a token and user_id for authenticating their session. Raises: - InputError: Invalid email format - InputError: Email already exists in db - InputError: Password less than 6 chars Returns: { user_id (int) token (str) } """ # Check for improper inputs and raise InputError: if not email_is_legit(email): raise InputError(description="Invalid email") if len(password) < 6: raise InputError( description="Password can't be less than 6 characters") if not username_valid(username): raise InputError( description= "Username must only use alphanumeric characters and be 1-20 characters long" ) users = User.query.all() # Check if the email exists in the database for each_user in users: if each_user.email == email: raise InputError( description="This email has already been registered with") # Adding a default profile picture for the user profile_image_endpoint = os.getenv("BASE_URI") + "/images/{}".format( "default.jpg") # Adding a new user new_user_bio = Bio(title="Techsuite user", profile_img_url=profile_image_endpoint) new_user = User(email=email, password=hashlib.sha256(password.encode()).hexdigest(), permission_id=1, username=username, bio=new_user_bio) db.session.add(new_user) db.session.add(new_user_bio) db.session.commit() generated_token = generate_token(new_user) send_welcome_email(new_user, "Welcome to Techsuite!") return { "user_id": new_user.id, "token": generated_token, "username": new_user.username, "profile_img_url": new_user_bio.profile_img_url }
def input_d_out(): d_out = input('Введите внешний диаметр трубы, мм: ') try: d_out = float(d_out) except ValueError: message = f'Введено некорректное значение диаметра: {d_out}.' raise InputError(message) if d_out <= 0: message = 'Введено отрицательное или нулевое значение диаметра.' raise InputError(message) print('-' * 69) return d_out / 1000
def channels_removeowner(token, channel_id, user_id): """ Desc: Remove user with user id user_id an owner of this channel Params: (token, channel_id, user_id) Returns: empty dict Errors: InputError on invalid channel_id InputError when user_id DOESN'T already have ownership over a channel before calling channel_removeowner AccessError when the user isn't an owner of the slackr or an owner of this channel TYPES: token str channel_id int user_id int """ verify_token(token) selected_channel = select_channel(channel_id) if not selected_channel: raise InputError(description="Not a valid channel") calling_user = get_user_from_token(token) details = channels_details(token, channel_id) # Check whether the target user is actually in the list of members members_list = details["all_members"] user_found = False for member in members_list: if member["user_id"] == user_id: user_found = True break if not user_found: raise InputError("Target user must be a part of this channel") # Check whether user_id is not already an owner in channel owners_list = details["owner_members"] calling_user_is_owner = False target_user_is_owner = False for owner in owners_list: if owner["user_id"] == user_id: target_user_is_owner = True if owner["user_id"] == calling_user.id: calling_user_is_owner = True if not calling_user_is_owner: raise InputError("You are not authorised to remove existing owners") if not target_user_is_owner: raise InputError("Target user is not an owner of the channel") target_user = User.query.filter_by(id=user_id).first() for each_membership in target_user.channel_membership: if each_membership.channel_id == channel_id: each_membership.is_owner = False db.session.commit() return {}
def collect_raw_data(self): """ Pull raw data from window and save in variables. """ #Hologram width. try: self.hologram_width = float(self.entry_width.get().strip()) except ValueError as e: message = 'Hologram width must be a floating point.' raise InputError(message, e) #Hologram height. try: self.hologram_height = float(self.entry_height.get().strip()) except ValueError as e: message = 'Hologram height must be a floating point.' raise InputError(message, e) #Spot size try: val = self.entry_spot.get().strip() if val != '': self.spot_size = float(val) else: self.spot_size = -1 except ValueError as e: message = 'Spot size must be a floating point.' raise InputError(message, e) #Pixels Horizontal. try: val = self.entry_pixel_x.get().strip() if val != '': self.pixels_x = int(val) else: self.pixels_x = self.image.original_PIL.width except ValueError as e: message = 'Horizontal Pixels must be an int.' raise InputError(message, e) #Pixels Vertical. try: val = self.entry_pixel_y.get().strip() if val != '': self.pixels_y = int(val) else: self.pixels_y = self.image.original_PIL.height except ValueError as e: message = 'Vertical Pixels must be an int.' raise InputError(message, e) self.cropping = self.entry_crop.get().strip() self.strings_exposure = self.text_exposure.get(1.0, 'end-1c').strip() self.strings_ignore = self.text_ignore.get(1.0, 'end-1c').strip() self.strings_laser = self.text_laser.get(1.0, 'end-1c').strip()
def _input_t(point, state): """Connects the domain with its inlet/outlet temperature.""" t = input(f'Enter the {point} temperature of the {state} domain, °C: ') try: t = float(t) except ValueError: message = f'Incorrect {point} temperature of the {state} domain ' \ f'has been entered: {t}' raise InputError(message) if t < 0: message = f'Negative {point} temperature of the {state} domain ' \ f'has been entered.' raise InputError(message) print('-' * 69) return t
def input_t(in_out, state): t = input(f'Введите значение {in_out} температуры {state} ' f'теплоносителя, °C: ') try: t = float(t) except ValueError: message = f'Введено некорректное значение {in_out} температуры ' \ f'{state} теплоносителя: {t}' raise InputError(message) if t < 0: message = f'Введено отрицательное значение {in_out} ' \ f'температуры {state} теплоносителя.' raise InputError(message) print('-' * 69) return t
def download_img_and_crop(url, u_id, x_start, y_start, x_end, y_end): """ Given a URL to an web image resource, download it to the project directory's 'static/images' folder with a unique filename. The image is then cropped and overwritten by the cropped result. Parameters: url str u_id int x_start int y_start int x_end int y_end int Returns the filename of the cropped image on success, otherwise returns None """ filename = "user{}_profile.jpg".format(u_id) image_path = PROFILE_IMG_DIRECTORY + filename # Remove the previous profile picture, if it exists try: os.remove(image_path) except FileNotFoundError: pass # Fetching and saving the profile picture to server directory res = requests.get(url) if res.status_code != 200: raise InputError(description="Request to image resource failed") with open(image_path, "wb") as output_img: output_img.write(res.content) try: pic = Image.open(image_path) except: raise InputError(description="Not a valid image file!") crop_coordinates = (x_start, y_start, x_end, y_end) width, height = pic.size if (x_start > width or y_start > height or x_end > width or y_end > height or x_start < 0 or y_start < 0 or x_end < 0 or y_end < 0 or x_start > x_end or y_start > y_end): raise InputError(description="Coordinates out of bounds") cropped_pic = pic.crop(crop_coordinates) cropped_pic.save(image_path) return filename
def _get_task(self): """TODO: Docstring for _get_task. :returns: TODO """ os.makedirs("text", exist_ok=True) os.makedirs("regex", exist_ok=True) self.regex_files_dir = path(self.task, 'regex') self.text_files_dir = path(self.task, 'text') os.makedirs(self.regex_files_dir, exist_ok=True) os.makedirs(self.text_files_dir, exist_ok=True) if not all( isdir(d) for d in (self.regex_files_dir, self.text_files_dir)): raise InputError("should have 'regex' and 'text' \ subdirectories inside the task directory") if isfile(path(self.task, "_config.py")): self.config = open(path(self.task, "_config.py")) if not os.listdir(self.text_files_dir): task_config = importlib.import_module(".".join( path(self.task, "_config").split("/"))) if hasattr(task_config, "TEXT_URLS"): self._download_texts(task_config.TEXT_URLS) self._preprocess_text() elif hasattr(task_config, "TEXT_SCRIPT"): subprocess.call(task_config.TEXT_SCRIPT)
def init_connection(username=None, password=None): """Initializes connection to running MySQL server Connects to a running MySQL server using a username/password and returns the connection if successful. Args: username: the username of the account on the server to connect with password: the password of the account on the server to connect with Returns: connection: the open connection to the MySQL server Raises: InputError: The username or password input was incorrect """ if not username or not password: username = input("Username: "******"Password: ") try: connection = mysql.connector.connect(user=username, password=password) except mysql.connector.Error as err: raise InputError(message='There was a problem connecting. Please check' ' your username and password, and make sure' ' the server is running.', args=err.args) return connection
def channels_join(token, channel_id): """ Given a channel_id of a channel that the authorised user can join, adds them to that channel Parameters: token (str) channel_id (int) Returns: {} """ verify_token(token) user = get_user_from_token(token) if not user: raise AccessError(description="Invalid Token") selected_channel = select_channel(channel_id) if not selected_channel: raise InputError(description="Target channel is not a valid channel") # Check whether channel is private or not. Raise AccessError if it is if not selected_channel.visibility == "public": raise AccessError(description="Target channel isn't public") new_membership = MemberOf( user=user, channel=selected_channel, is_owner=False ) db.session.add(new_membership) db.session.commit() return {}
def users_profile(token, user_id): """ For a valid user, returns some of their basic fields Parameters: token (str) user_id (int) Returns: { user_id, email, username, profile_img_url, is_connected_to, connection_is_pending } """ verify_token(token) calling_user = get_user_from_token(token) target_user = User.query.filter_by(id=user_id).first() if not target_user: raise InputError(description="user_id does not refer to any user in the database") connected = False pending = False connection = Connection.query.filter_by(user_id=calling_user.id, other_user_id=target_user.id).first() if connection: if connection.approved: connected = True else: pending = True return { "user_id": target_user.id, "email": target_user.email, "username": target_user.username, "profile_img_url": target_user.bio.profile_img_url, "is_connected_to": connected, "connection_is_pending": pending }
def input_lambda_steel(): lambda_steel = input('Введите коэффициент теплопроводности металла ' 'стенки трубы, Вт/(м∙град): ') try: lambda_steel = float(lambda_steel) except ValueError: message = f'Введено некорректное значение коэффициента ' \ f'теплопроводности металла стенки трубы: ' \ f'{lambda_steel}.' raise InputError(message) if lambda_steel <= 0: message = 'Введено отрицательное или нулевое значение ' \ 'коэффициента теплопроводности металла стенки трубы.' raise InputError(message) print('-' * 69) return lambda_steel
def users_bio_fetch(token, user_id): """ Returns the target user's bio and its associated details Parameters: token (str) user_id (int) Returns: { first_name, last_name, cover_img_url, title, summary, location, education, email, username } """ verify_token(token) user = User.query.filter_by(id=user_id).first() if not user: raise InputError(description="{} does not refer to any user in the database".format(user_id)) return { "first_name": user.bio.first_name, "last_name" : user.bio.last_name, "cover_img_url" : user.bio.cover_img_url, "title" : user.bio.title, "summary" : user.bio.summary, "location" : user.bio.location, "education" : user.bio.education, "email": user.email, "username": user.username }
def download_img_and_get_filename(url, user_id): """ Given a URL to an web image resource, download it to the project directory"s "static/images" folder with a unique filename of format: user_x_profile.jpg where x is the user"s ID Parameters: url (str) user_id (int) Returns: Filename (str) of the image on success, otherwise returns None """ filename = "user_{}_profile.jpg".format(user_id) image_path = IMAGE_DIRECTORY + filename # Remove the previous profile picture, if it exists try: printColour("Removing existing profile picture: {}".format(filename), colour="red_1") os.remove(image_path) except FileNotFoundError: pass # Fetching and saving the profile picture to server directory res = requests.get(url) if res.status_code != 200: raise InputError(description="Request to image resource failed") with open(image_path, "wb") as output_img: printColour("Saving picture: {}".format(image_path), colour="blue") output_img.write(res.content) return filename
def _query(self, query_type: str, model: str, query: list, options: dict = {}) -> list: """ Verifies the `query_type` is supported by the API and executes the API request on a new XMLRPC instance, returning the result """ if query_type not in self.QUERY_TYPES: raise InputError( 'query_type', 'Incorrect Type of query. Available types are: %s' % (', '.join(self.QUERY_TYPES))) return self._connect().execute_kw( self.database, self.user_id, self.user_pass, model, # This is the "table" that will be interacted with, in Odoo notation (eg, `res.partner` for `res_partner` in postgresql) query_type, # Alters how Odoo will behave with the `query` and `options` fields [ query ], # query must be a list containing either a list or dict depending on the query_type options ) # options will always be an optional dict, but the keys and values will change depending on query_type
def crop_image_file(image_filename, x_start, y_start, x_end, y_end): image_path = PROFILE_IMG_DIRECTORY + image_filename try: pic = Image.open(image_path) except: raise InputError(description="Not a valid image file!") crop_coordinates = (x_start, y_start, x_end, y_end) width, height = pic.size if (x_start > width or y_start > height or x_end > width or y_end > height or x_start < 0 or y_start < 0 or x_end < 0 or y_end < 0 or x_start > x_end or y_start > y_end): raise InputError(description="Coordinates out of bounds") cropped_pic = pic.crop(crop_coordinates) cropped_pic.save(image_path)
def channels_leave(token, channel_id): """ Removes the caller from the specified channel. Parameters: token (str) channel_id (str) Returns: {} """ verify_token(token) user = get_user_from_token(token) if not user: raise AccessError(description="Invalid Token") channels_list = Channel.query.all() selected_channel = select_channel(channel_id) # Check if Channel ID is not a valid channel if not selected_channel: raise InputError(description="Channel ID is not a valid channel") # Check user if the user is not currently a member of the selected channel if not is_user_member(user, selected_channel): raise AccessError(description="You are not a member of this channel") membership = MemberOf.query.filter_by(user_id=user.id, channel_id=selected_channel.id).first() db.session.delete(membership) db.session.commit() # If the user attempting to leave is the owner... Pass down ownership to someone else? Or delete channel # TODO: # If there is no members left in channel, delete channel # TODO: return {}
def users_profile_set_username(token, username): """ Update the authorised user's first and last name Parameters: token (str) username (str) """ verify_token(token) user = get_user_from_token(token) if not user: raise InputError(description="Target user doesn't exist") if not username_valid(username): raise InputError( description="Username, {}, must only use alphanumeric characters and be 1-20 characters long".format(username) ) user.username = username db.session.commit()
def check_value_t(self): if self.t_in_heat <= self.t_out_heat: message = 'Начальная температура горячего теплоносителя меньше ' \ 'или равна конечной.' raise InputError(message) if self.t_in_cool >= self.t_out_heat: message = 'Начальная температура холодного теплоносителя больше ' \ 'или равна конечной.' raise InputError(message) if not 0 <= (self.t_in_heat + self.t_out_heat) / 2 < 370: message = 'Средняя температура потока горячего теплоносителя ' \ 'выходит за границы 0..370°C' raise InputError(message) if not 0 <= (self.t_in_cool + self.t_out_cool) / 2 < 370: message = 'Средняя температура потока холодного теплоносителя ' \ 'выходит за границы 0..370°C' raise InputError(message)
def play_note_list(notes: List[Duration], tempo): if 0 >= tempo: raise InputError(tempo, "tempo to small") for note in notes: note.play() time.sleep((tempo / 60) * float(note.duration)) note.stop()
def post_to_chime(event, context): """Lambda function handler.""" LOG.info('Received event: %s', event) if not isinstance(event, list): raise InputError(event, "Input needs to be a json array") for message in event: chime.post_message(config.CHIME_URL, message)
def __ui_return(self): try: rentalId = int(input('Rental ID: ')) except ValueError: raise InputError('ID must be an integer') print(' * Insert date as day/month/year (00/00/0000) format') returnDate = input('Returned date: ') self.__serviceRentals.return_movie(rentalId, returnDate)
def replace(self): value = input('> ') try: value = int(value) except ValueError: raise InputError(value, 'Invalid user input.') self.set(value)