def stats(dataset_name, query): try: area = query.get('area') data = None for idx, a in enumerate(area): if isinstance(a, str): sp = a.split('/', 1) if data is None: data = list_areas(sp[0], simplify=False) b = [x for x in data if x.get('key') == a] a = b[0] area[idx] = a points_lat =[] for p in area[0]['polygons'][0]: points_lat.append(p[1]) except Exception as e: raise ServerError(gettext("Unknown Error: you have tried something that we did not expect. \ Please try again or try something else. If you would like to report \ this error please contact [email protected]. ") + str(e)) if (max(points_lat)-min(points_lat))>360: raise ClientError(gettext("Error: you are trying to create a plot that is wider than the world. \ The desired information is ambiguous please select a smaller area and try again")) elif any((p > 180 or p < -180) for p in points_lat) and any(-180 <= p <= 180 for p in points_lat): #if there area points on both sides of the date line return wrap_computer_stats(query, dataset_name, points_lat) else: # no world wrap return computer_stats(area, query, dataset_name) raise ServerError(gettext("Unknown Error: you have tried something that we did not expect. \ Please try again or try something else. If you would like to report \ this error please contact [email protected]"))
def process_answer(self, message: dict): """ Processes the server's response. Depending on the response code either: finishes working (200); raises ServerError (400); updates the lists and emits the relevant signal (205); or processes the message from another user, saves it to DB and emits the signal. :param message: message to process """ SOCKET_LOGGER.debug("Обработка сообщения от сервера: %s." % message) if RESPONSE in message: if message[RESPONSE] == 200: return elif message[RESPONSE] == 400: raise ServerError(f'400: {message[ERROR]}') elif message[RESPONSE] == 205: self.request_user_list() self.request_contacts() self.msg_205_signal.emit() else: SOCKET_LOGGER.debug("Принят неизвестный ответ сервера: %s" % message[RESPONSE]) elif ACTION in message and message[ACTION] == MESSAGE \ and SENDER in message and DESTINATION in message \ and MESSAGE_TEXT in message \ and message[DESTINATION] == self.client_nickname: SOCKET_LOGGER.info('Получено сообщение от пользователя %s: %s' % ( message[SENDER], message[MESSAGE_TEXT], )) self.database.save_message_to_history(message[SENDER], 'in', message[MESSAGE_TEXT]) self.new_msg_signal.emit(message)
def _hovmoller_plot(self, subplot, map_subplot, nomap_subplot, name, vmin, vmax, data, times, cmap, unit, title): if self.showmap: plt.subplot(subplot[map_subplot[0], map_subplot[1]]) else: plt.subplot(subplot[nomap_subplot[0], nomap_subplot[1]]) try: c = plt.pcolormesh( self.distance, times, data, cmap=cmap, shading='gouraud', # Smooth shading vmin=vmin, vmax=vmax) except TypeError as e: raise ServerError( gettext("Internal server error occured: " + str(e))) ax = plt.gca() ax.set_title(title, fontsize=14) # Set title of subplot ax.yaxis_date() ax.yaxis.grid(True) ax.set_facecolor('dimgray') plt.xlabel(gettext("Distance (km)")) plt.xlim([self.distance[0], self.distance[-1]]) divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", size="5%", pad=0.05) bar = plt.colorbar(c, cax=cax) bar.set_label("%s (%s)" % (name, utils.mathtext(unit)))
def __init__(self, server_address: str, server_port: int, client_nickname: str, database, password: str, keys: RsaKey): """ Initialization of client's socket. Requests the contacts and existing users' lists, connects to the server and sets the running flag to True. :param server_address: server's IP address :param server_port: listening port on the server :param client_nickname: client's login :param database: client's DB :param password: client's password, duh :param keys: client's RSA key """ Thread.__init__(self) QObject.__init__(self) self.client_nickname = client_nickname self.database = database self.client_socket = None self.password = password self.keys = keys self.establish_connection(server_address, server_port) self.pubkey = None try: self.request_contacts() self.request_user_list() except OSError as e: if e.errno: SOCKET_LOGGER.critical('Потеряно соединение с сервером.') raise ServerError('Потеряно соединение с сервером.') SOCKET_LOGGER.error('Таймаут соединения с сервером ' 'при запросе списков пользователей.') except JSONDecodeError: SOCKET_LOGGER.critical('Потеряно соединение с сервером.') raise ServerError('Потеряно соединение с сервером.') self.running = True
def subset(self, query): raise ServerError( "Subsetting FVCOM datasets is currently not supported.")
def get_values(self, area_info, dataset_name, variables): config = DatasetConfig(dataset_name) with open_dataset(config) as dataset: if self.time is None or (type(self.time) == str and len(self.time) == 0): time = -1 else: time = int(self.time) if time < 0: time += len(dataset.nc_data.timestamps) time = np.clip(time, 0, len(dataset.nc_data.timestamps) - 1) depth = 0 depthm = 0 if self.depth: if self.depth == 'bottom': depth = 'bottom' depthm = 'Bottom' if len(self.depth) > 0 and \ self.depth != 'bottom': depth = int(self.depth) depth = np.clip(depth, 0, len(dataset.depths) - 1) depthm = dataset.depths[depth] lat, lon = np.meshgrid( np.linspace(area_info.bounds[0], area_info.bounds[2], 50), area_info.spaced_points ) output_fmtstr = "%6.5g" for v_idx, v in enumerate(variables): var = dataset.variables[v] variable_name = config.variable[var].name variable_unit = config.variable[var].unit lat, lon, d = dataset.get_raw_point( lat.ravel(), lon.ravel(), depth, time, v ) lon[np.where(lon > 180)] -= 360 if len(var.dimensions) == 3: variable_depth = "" elif depth == 'bottom': variable_depth = "(@ Bottom)" else: variable_depth = "(@%d m)" % np.round(depthm) points = [Point(p) for p in zip(lat.values.ravel(), lon.values.ravel())] for i, a in enumerate(area_info.area_query): indices = np.where( map( lambda p, poly=area_info.area_polys[i]: poly.contains(p), points ) ) selection = np.ma.array(d.values.ravel()[indices]) if len(selection) > 0 and not selection.mask.all(): area_info.output[i]['variables'].append({ 'name': ("%s %s" % (variable_name, variable_depth)).strip(), 'unit': variable_unit, 'min': output_fmtstr % ( np.ma.amin(selection).astype(float) ), 'max': output_fmtstr % ( np.ma.amax(selection).astype(float) ), 'mean': output_fmtstr % ( np.ma.mean(selection).astype(float) ), 'median': output_fmtstr % ( np.ma.median(selection).astype(float) ), 'stddev': output_fmtstr % ( np.ma.std(selection).astype(float) ), 'num': "%d" % selection.count(), }) else: area_info.output[i]['variables'].append({ 'name': ("%s %s" % (variable_name, variable_depth)).strip(), 'unit': variable_unit, 'min': gettext("No Data"), 'max': gettext("No Data"), 'mean': gettext("No Data"), 'median': gettext("No Data"), 'stddev': gettext("No Data"), 'num': "0", }) ClientError(gettext("there are no datapoints in the area you selected. \ you may have selected a area on land or you may \ have an ara that is smallenough to fit between \ the datapoints try selection a different area or \ a larger area")) area_info.stats = area_info.output return raise ServerError(gettext("An Error has occurred. When opening the dataset. \ Please try again or try a different dataset. \ If you would like to report this error please \ contact [email protected]"))
def establish_connection(self, ip_address: str, port: int): """ Establishes connection to the server. Makes 5 attempts to do so, if unsuccessful, ends the cycle. If successful, sends the presence message to the server, and then, sends the encrypted password to the server to compare to the one stored in the server's DB. :param ip_address: server's IP address :param port: server's listening port """ self.client_socket = socket(AF_INET, SOCK_STREAM) self.client_socket.settimeout(5) connected = False for i in range(5): SOCKET_LOGGER.info('Попытка соединения №%d' % (i + 1, )) try: self.client_socket.connect((ip_address, port)) except (OSError, ConnectionRefusedError): pass else: connected = True break sleep(1) if not connected: SOCKET_LOGGER.critical( 'Не удалось установить соединение с сервером.') raise ServerError('Не удалось установить соединение с сервером.') SOCKET_LOGGER.debug('Установлено соединение с сервером. ' 'Начинаю процесс авторизации.') password_bytes = self.password.encode('utf-8') salt = self.client_nickname.lower().encode('utf-8') password_hash = pbkdf2_hmac('sha512', password_bytes, salt, 10000) password_hash_str = hexlify(password_hash) SOCKET_LOGGER.debug('Подготовлен хэш пароля: %s' % password_hash_str) self.pubkey = self.keys.publickey().export_key().decode('ascii') with socket_lock: msg = self.establish_presence() try: send_message(self.client_socket, msg) server_response = receive_message(self.client_socket) SOCKET_LOGGER.debug('Ответ сервера - %s' % server_response) if RESPONSE in server_response: if server_response[RESPONSE] == 400: raise ServerError(server_response[ERROR]) elif server_response[RESPONSE] == 511: resp_data = server_response[DATA] resp_hash = new(password_hash_str, resp_data.encode('utf-8'), 'MD5') digest = resp_hash.digest() client_response = { RESPONSE: 511, DATA: b2a_base64(digest).decode('ascii') } send_message(self.client_socket, client_response) self.process_answer(receive_message( self.client_socket)) except (OSError, JSONDecodeError): SOCKET_LOGGER.critical('В процессе авторизации потеряно ' 'соединение с сервером') raise ServerError('В процессе авторизации потеряно ' 'соединение с сервером') else: SOCKET_LOGGER.info('Соединение успешно установлено.')