index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
41,387
irmakcakmak/great-circle-distance
refs/heads/master
/point.py
import math EARTH_RADIUS = 6378.137 # km class Point: def __init__(self, lat, lon): if lat < -90.0 or lat > 90.0: raise ValueError("Latitude must be between -90.0 and 90.0") if lon < -180.0 or lon > 180.0: raise ValueError("Longitude must be between -180.0 and 180.0") self.lat = float(lat) self.lon = float(lon) @classmethod def from_record(cls, data): try: obj = cls(float(data["latitude"]), float(data["longitude"])) except KeyError: raise ValueError("Required fields: latitude, longitude") return obj def __sub__(self, other): if isinstance(other, Point): return Point(self.lat - other.lat, self.lon - other.lon) else: raise NotImplementedError class PointRad: def __init__(self, lat, lon): self.lat = lat self.lon = lon @classmethod def from_decimal(cls, lat, lon): return cls(math.radians(lat), math.radians(lon)) def __sub__(self, other): if isinstance(other, Point.PointRad): return Point.PointRad(self.lat - other.lat, self.lon - other.lon) else: raise NotImplementedError @property def radians(self): return Point.PointRad.from_decimal(self.lat, self.lon) def dist_to(self, other, radius=EARTH_RADIUS): """ Calculates distance between two points on a sphere :param radius: radius of the sphere :param other: :return: """ diff = self.radians - other.radians A = math.sin(abs(diff.lat) / 2) ** 2 B = math.cos(self.radians.lat) * math.cos(other.radians.lat) * math.sin(abs(diff.lon) / 2) ** 2 haversine = 2 * math.asin(math.sqrt(A + B)) return radius * haversine def within_dist(self, other: "Point", max_dist: float,): """ Returns if other point is within given radius :param max_dist: within perimeter? :param other: Point :return: bool """ return self.dist_to(other) <= max_dist
{"/test/test_user.py": ["/user.py"], "/main.py": ["/point.py", "/user.py", "/reader.py"], "/test/test_point.py": ["/point.py"], "/test/test_reader.py": ["/reader.py"]}
41,388
irmakcakmak/great-circle-distance
refs/heads/master
/main.py
import argparse import logging from point import Point from user import User import reader logging.basicConfig() LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) ORIGIN = (53.339428, -6.257664) MAX_DIST = 100 # km def latitude(lat): lat = float(lat) if lat < -90.0 or lat > 90.0: raise argparse.ArgumentTypeError("Latitude is between -90 and 90") return lat def longitude(lon): lon = float(lon) if lon < -180.0 or lon > 180.0: raise argparse.ArgumentTypeError("Longitude is between -180 and 180") return lon if __name__ == "__main__": # Parse command line arguments parser = argparse.ArgumentParser() parser.add_argument("--file", type=str, required=True, help="Path to data file") parser.add_argument("--max-dist", type=float, default=MAX_DIST, help="Max distance in kilometers") parser.add_argument("--lat", type=latitude, default=ORIGIN[0], help="Origin latitude to calculate distances from") parser.add_argument("--lon", type=longitude, default=ORIGIN[1], help="Origin longitude to calculate distances from") args = parser.parse_args() # initialise variables, check if within given distance users_to_invite = [] origin = Point(args.lat, args.lon) for record in reader.read(args.file): point = Point.from_record(record) if point.within_dist(origin, args.max_dist): users_to_invite.append(User.from_record(record)) # sort users users_to_invite.sort() # log LOGGER.info("Users to invite:") for user in users_to_invite: LOGGER.info(user)
{"/test/test_user.py": ["/user.py"], "/main.py": ["/point.py", "/user.py", "/reader.py"], "/test/test_point.py": ["/point.py"], "/test/test_reader.py": ["/reader.py"]}
41,389
irmakcakmak/great-circle-distance
refs/heads/master
/user.py
class User: def __init__(self, user_id, name): self.user_id = user_id self.name = name def __lt__(self, other): if isinstance(other, User): return self.user_id < other.user_id else: raise NotImplementedError @classmethod def from_record(cls, data): """ Inits user from data. :param data: dict with user_id and name fields :return: instance """ try: obj = cls(data["user_id"], data["name"]) except KeyError: raise ValueError("Required fields: user_id, name") return obj def __str__(self): return "user_id: {} name: {}".format(self.user_id, self.name)
{"/test/test_user.py": ["/user.py"], "/main.py": ["/point.py", "/user.py", "/reader.py"], "/test/test_point.py": ["/point.py"], "/test/test_reader.py": ["/reader.py"]}
41,390
irmakcakmak/great-circle-distance
refs/heads/master
/test/test_point.py
import unittest from point import Point class PointTest(unittest.TestCase): def test_dist_to(self): a = Point(0, 0) # origin meridian on the Equator b = Point(1, 0) # first meridian on the Equator self.assertAlmostEqual(a.dist_to(b), 111.3, places=1) def test_within_dist(self): a = Point(0, 0) b = Point(1, 0) self.assertTrue(a.within_dist(b, 112)) def test_not_within_dist(self): a = Point(0, 0) b = Point(1, 0) self.assertFalse(a.within_dist(b, 110)) def test_radian_conversion(self): point = Point(53.339428, -6.257664) self.assertAlmostEqual(point.radians.lat, 0.93, places=2) self.assertAlmostEqual(point.radians.lon, -0.11, places=2) def test_point_rad_from_decimal(self): point = Point.PointRad.from_decimal(41, 29) # istanbul self.assertAlmostEqual(point.lat, 0.72, places=2) self.assertAlmostEqual(point.lon, 0.51, places=2) def test_point_subtraction(self): a = Point(53.01, 6.01) b = Point(41.23, 29.23) diff = a - b self.assertIsInstance(diff, Point) self.assertAlmostEqual(diff.lat, 11.78, places=2) self.assertAlmostEqual(diff.lon, -23.22, places=2) def test_rad_subtraction(self): a = Point.PointRad(0.93, -0.10) b = Point.PointRad(0.71, 0.50) diff = a - b self.assertIsInstance(diff, Point.PointRad) self.assertAlmostEqual(diff.lat, 0.22, places=2) self.assertAlmostEqual(diff.lon, -0.6, places=2) def test_point_from_malformed_data(self): with self.assertRaises(ValueError): Point.from_record({"lat": 41, "lon": 29}) def test_invalid_lat(self): with self.assertRaises(ValueError): Point.from_record({"latitude": 91, "longitude": 20}) def test_invalid_lon(self): with self.assertRaises(ValueError): Point.from_record({"latitude": -70, "longitude": -181})
{"/test/test_user.py": ["/user.py"], "/main.py": ["/point.py", "/user.py", "/reader.py"], "/test/test_point.py": ["/point.py"], "/test/test_reader.py": ["/reader.py"]}
41,391
irmakcakmak/great-circle-distance
refs/heads/master
/test/test_reader.py
import unittest import reader class ReaderTest(unittest.TestCase): def test_read(self): records = [] for record in reader.read("test/resources/test_file.json"): records.append(record) self.assertEqual(len(records), 1) record = records[0] fields = [key for key in record.keys()] fields.sort() expected = ["latitude", "longitude", "user_id", "name"] expected.sort() self.assertListEqual(fields, expected) def test_missing_field(self): records = [] for record in reader.read("test/resources/test_missing_field_file.json"): records.append(record) self.assertEqual(len(records), 2) def test_invalid_json(self): records = [] for record in reader.read("test/resources/test_invalid_data.json"): records.append(record) self.assertEqual(len(records), 1)
{"/test/test_user.py": ["/user.py"], "/main.py": ["/point.py", "/user.py", "/reader.py"], "/test/test_point.py": ["/point.py"], "/test/test_reader.py": ["/reader.py"]}
41,392
irmakcakmak/great-circle-distance
refs/heads/master
/reader.py
import json from json import JSONDecodeError import logging logging.basicConfig() LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.ERROR) VALID_FIELDS = ["latitude", "longitude", "user_id", "name"] def read(filename): with open(filename, 'r') as f: for line in f: try: data = json.loads(line) except JSONDecodeError as ex: # Log and continue to next line LOGGER.error("Malformed data: {}".format(ex.msg)) continue # if all fields present, yield; else log and continue if all([field in data for field in VALID_FIELDS]): yield data else: LOGGER.error("Missing field in data. Valid fields are {}".format(", ".join(VALID_FIELDS)))
{"/test/test_user.py": ["/user.py"], "/main.py": ["/point.py", "/user.py", "/reader.py"], "/test/test_point.py": ["/point.py"], "/test/test_reader.py": ["/reader.py"]}
41,403
junglefive/EightPoleModuleTester
refs/heads/master
/CSM37F58_APP_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CSM37F58_APP.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setWindowModality(QtCore.Qt.NonModal) MainWindow.resize(660, 879) MainWindow.setMinimumSize(QtCore.QSize(400, 500)) font = QtGui.QFont() font.setFamily("Consolas") MainWindow.setFont(font) MainWindow.setWindowOpacity(1.0) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.centralwidget) self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) self.tabWidget.setSizePolicy(sizePolicy) self.tabWidget.setMinimumSize(QtCore.QSize(0, 0)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(204, 204, 204)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(204, 204, 204)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(204, 204, 204)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(204, 204, 204)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) self.tabWidget.setPalette(palette) self.tabWidget.setObjectName("tabWidget") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.gridLayout_2 = QtWidgets.QGridLayout(self.tab_2) self.gridLayout_2.setObjectName("gridLayout_2") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.btn_update_all = QtWidgets.QPushButton(self.tab_2) self.btn_update_all.setObjectName("btn_update_all") self.horizontalLayout.addWidget(self.btn_update_all) self.horizontalLayout.setStretch(0, 1) self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 1) self.tabWidget_2 = QtWidgets.QTabWidget(self.tab_2) self.tabWidget_2.setObjectName("tabWidget_2") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.gridLayout_3 = QtWidgets.QGridLayout(self.tab_4) self.gridLayout_3.setObjectName("gridLayout_3") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.verticalLayout_2 = QtWidgets.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.watch_table_dev_set = QtWidgets.QTableView(self.tab_4) self.watch_table_dev_set.setMouseTracking(True) self.watch_table_dev_set.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_dev_set.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_dev_set.setDragEnabled(False) self.watch_table_dev_set.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_dev_set.setAlternatingRowColors(True) self.watch_table_dev_set.setSortingEnabled(False) self.watch_table_dev_set.setObjectName("watch_table_dev_set") self.watch_table_dev_set.horizontalHeader().setDefaultSectionSize(150) self.watch_table_dev_set.horizontalHeader().setStretchLastSection(True) self.verticalLayout_2.addWidget(self.watch_table_dev_set) self.verticalLayout.addLayout(self.verticalLayout_2) self.gridLayout_3.addLayout(self.verticalLayout, 0, 0, 1, 1) self.tabWidget_2.addTab(self.tab_4, "") self.tab_5 = QtWidgets.QWidget() self.tab_5.setObjectName("tab_5") self.gridLayout_7 = QtWidgets.QGridLayout(self.tab_5) self.gridLayout_7.setObjectName("gridLayout_7") self.verticalLayout_5 = QtWidgets.QVBoxLayout() self.verticalLayout_5.setObjectName("verticalLayout_5") self.watch_table_dev_info = QtWidgets.QTableView(self.tab_5) self.watch_table_dev_info.setMouseTracking(True) self.watch_table_dev_info.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_dev_info.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_dev_info.setDragEnabled(False) self.watch_table_dev_info.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_dev_info.setAlternatingRowColors(True) self.watch_table_dev_info.setSortingEnabled(False) self.watch_table_dev_info.setObjectName("watch_table_dev_info") self.watch_table_dev_info.horizontalHeader().setDefaultSectionSize(150) self.watch_table_dev_info.horizontalHeader().setStretchLastSection(True) self.verticalLayout_5.addWidget(self.watch_table_dev_info) self.gridLayout_7.addLayout(self.verticalLayout_5, 0, 0, 1, 1) self.tabWidget_2.addTab(self.tab_5, "") self.tab_8 = QtWidgets.QWidget() self.tab_8.setObjectName("tab_8") self.gridLayout_5 = QtWidgets.QGridLayout(self.tab_8) self.gridLayout_5.setObjectName("gridLayout_5") self.verticalLayout_6 = QtWidgets.QVBoxLayout() self.verticalLayout_6.setObjectName("verticalLayout_6") self.watch_table_usr_info = QtWidgets.QTableView(self.tab_8) self.watch_table_usr_info.setMouseTracking(True) self.watch_table_usr_info.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_usr_info.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_usr_info.setDragEnabled(False) self.watch_table_usr_info.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_usr_info.setAlternatingRowColors(True) self.watch_table_usr_info.setSortingEnabled(False) self.watch_table_usr_info.setObjectName("watch_table_usr_info") self.watch_table_usr_info.horizontalHeader().setDefaultSectionSize(150) self.watch_table_usr_info.horizontalHeader().setStretchLastSection(True) self.verticalLayout_6.addWidget(self.watch_table_usr_info) self.gridLayout_5.addLayout(self.verticalLayout_6, 0, 0, 1, 1) self.tabWidget_2.addTab(self.tab_8, "") self.tab_9 = QtWidgets.QWidget() self.tab_9.setObjectName("tab_9") self.gridLayout_6 = QtWidgets.QGridLayout(self.tab_9) self.gridLayout_6.setObjectName("gridLayout_6") self.verticalLayout_7 = QtWidgets.QVBoxLayout() self.verticalLayout_7.setObjectName("verticalLayout_7") self.watch_table_usr_bia = QtWidgets.QTableView(self.tab_9) self.watch_table_usr_bia.setMouseTracking(True) self.watch_table_usr_bia.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_usr_bia.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_usr_bia.setDragEnabled(False) self.watch_table_usr_bia.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_usr_bia.setAlternatingRowColors(True) self.watch_table_usr_bia.setSortingEnabled(False) self.watch_table_usr_bia.setObjectName("watch_table_usr_bia") self.watch_table_usr_bia.horizontalHeader().setDefaultSectionSize(150) self.watch_table_usr_bia.horizontalHeader().setStretchLastSection(True) self.verticalLayout_7.addWidget(self.watch_table_usr_bia) self.gridLayout_6.addLayout(self.verticalLayout_7, 0, 0, 1, 1) self.tabWidget_2.addTab(self.tab_9, "") self.gridLayout_2.addWidget(self.tabWidget_2, 1, 0, 1, 1) self.tabWidget_3 = QtWidgets.QTabWidget(self.tab_2) self.tabWidget_3.setObjectName("tabWidget_3") self.tab_6 = QtWidgets.QWidget() self.tab_6.setObjectName("tab_6") self.gridLayout_8 = QtWidgets.QGridLayout(self.tab_6) self.gridLayout_8.setObjectName("gridLayout_8") self.verticalLayout_4 = QtWidgets.QVBoxLayout() self.verticalLayout_4.setObjectName("verticalLayout_4") self.watch_table_analy_result = QtWidgets.QTableView(self.tab_6) self.watch_table_analy_result.setMouseTracking(True) self.watch_table_analy_result.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_analy_result.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_analy_result.setDragEnabled(False) self.watch_table_analy_result.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_analy_result.setAlternatingRowColors(True) self.watch_table_analy_result.setSortingEnabled(False) self.watch_table_analy_result.setObjectName("watch_table_analy_result") self.watch_table_analy_result.horizontalHeader().setDefaultSectionSize(150) self.watch_table_analy_result.horizontalHeader().setStretchLastSection(True) self.verticalLayout_4.addWidget(self.watch_table_analy_result) self.gridLayout_8.addLayout(self.verticalLayout_4, 0, 0, 1, 1) self.tabWidget_3.addTab(self.tab_6, "") self.tab_7 = QtWidgets.QWidget() self.tab_7.setObjectName("tab_7") self.gridLayout_9 = QtWidgets.QGridLayout(self.tab_7) self.gridLayout_9.setObjectName("gridLayout_9") self.verticalLayout_8 = QtWidgets.QVBoxLayout() self.verticalLayout_8.setObjectName("verticalLayout_8") self.watch_table_tst_middle = QtWidgets.QTableView(self.tab_7) self.watch_table_tst_middle.setMouseTracking(True) self.watch_table_tst_middle.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_tst_middle.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_tst_middle.setDragEnabled(False) self.watch_table_tst_middle.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_tst_middle.setAlternatingRowColors(True) self.watch_table_tst_middle.setSortingEnabled(False) self.watch_table_tst_middle.setObjectName("watch_table_tst_middle") self.watch_table_tst_middle.horizontalHeader().setDefaultSectionSize(150) self.watch_table_tst_middle.horizontalHeader().setStretchLastSection(True) self.verticalLayout_8.addWidget(self.watch_table_tst_middle) self.gridLayout_9.addLayout(self.verticalLayout_8, 0, 0, 1, 1) self.tabWidget_3.addTab(self.tab_7, "") self.tab_10 = QtWidgets.QWidget() self.tab_10.setObjectName("tab_10") self.gridLayout_10 = QtWidgets.QGridLayout(self.tab_10) self.gridLayout_10.setObjectName("gridLayout_10") self.verticalLayout_9 = QtWidgets.QVBoxLayout() self.verticalLayout_9.setObjectName("verticalLayout_9") self.watch_table_com_log = QtWidgets.QTableView(self.tab_10) self.watch_table_com_log.setMouseTracking(True) self.watch_table_com_log.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_com_log.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_com_log.setDragEnabled(False) self.watch_table_com_log.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_com_log.setAlternatingRowColors(True) self.watch_table_com_log.setSortingEnabled(False) self.watch_table_com_log.setObjectName("watch_table_com_log") self.watch_table_com_log.horizontalHeader().setDefaultSectionSize(150) self.watch_table_com_log.horizontalHeader().setStretchLastSection(True) self.verticalLayout_9.addWidget(self.watch_table_com_log) self.gridLayout_10.addLayout(self.verticalLayout_9, 0, 0, 1, 1) self.tabWidget_3.addTab(self.tab_10, "") self.tab_11 = QtWidgets.QWidget() self.tab_11.setObjectName("tab_11") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.tab_11) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.verticalLayout_3 = QtWidgets.QVBoxLayout() self.verticalLayout_3.setObjectName("verticalLayout_3") self.watch_table_res_real = QtWidgets.QTableView(self.tab_11) self.watch_table_res_real.setMouseTracking(True) self.watch_table_res_real.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.watch_table_res_real.setEditTriggers(QtWidgets.QAbstractItemView.AnyKeyPressed|QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed|QtWidgets.QAbstractItemView.SelectedClicked) self.watch_table_res_real.setDragEnabled(False) self.watch_table_res_real.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.watch_table_res_real.setAlternatingRowColors(True) self.watch_table_res_real.setSortingEnabled(False) self.watch_table_res_real.setObjectName("watch_table_res_real") self.watch_table_res_real.horizontalHeader().setDefaultSectionSize(150) self.watch_table_res_real.horizontalHeader().setStretchLastSection(True) self.verticalLayout_3.addWidget(self.watch_table_res_real) self.horizontalLayout_2.addLayout(self.verticalLayout_3) self.tabWidget_3.addTab(self.tab_11, "") self.gridLayout_2.addWidget(self.tabWidget_3, 2, 0, 1, 1) self.tabWidget.addTab(self.tab_2, "") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.formLayout = QtWidgets.QFormLayout(self.tab) self.formLayout.setObjectName("formLayout") self.checkBox = QtWidgets.QCheckBox(self.tab) self.checkBox.setEnabled(False) self.checkBox.setObjectName("checkBox") self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.checkBox) self.label_6 = QtWidgets.QLabel(self.tab) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(240, 240, 240)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(240, 240, 240)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(240, 240, 240)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(240, 240, 240)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) self.label_6.setPalette(palette) self.label_6.setObjectName("label_6") self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.label_6) self.horizontalLayout_9 = QtWidgets.QHBoxLayout() self.horizontalLayout_9.setObjectName("horizontalLayout_9") self.line_cmd_1 = QtWidgets.QLineEdit(self.tab) self.line_cmd_1.setEnabled(False) self.line_cmd_1.setAccessibleDescription("") self.line_cmd_1.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.line_cmd_1.setObjectName("line_cmd_1") self.horizontalLayout_9.addWidget(self.line_cmd_1) self.btn_cmd_1 = QtWidgets.QPushButton(self.tab) self.btn_cmd_1.setAccessibleDescription("") self.btn_cmd_1.setCheckable(False) self.btn_cmd_1.setObjectName("btn_cmd_1") self.horizontalLayout_9.addWidget(self.btn_cmd_1) self.horizontalLayout_9.setStretch(0, 6) self.horizontalLayout_9.setStretch(1, 1) self.formLayout.setLayout(1, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_9) self.checkBox_2 = QtWidgets.QCheckBox(self.tab) self.checkBox_2.setEnabled(False) self.checkBox_2.setObjectName("checkBox_2") self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.checkBox_2) self.label_7 = QtWidgets.QLabel(self.tab) self.label_7.setObjectName("label_7") self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.label_7) self.horizontalLayout_10 = QtWidgets.QHBoxLayout() self.horizontalLayout_10.setObjectName("horizontalLayout_10") self.line_cmd_2 = QtWidgets.QLineEdit(self.tab) self.line_cmd_2.setEnabled(False) self.line_cmd_2.setAccessibleDescription("") self.line_cmd_2.setObjectName("line_cmd_2") self.horizontalLayout_10.addWidget(self.line_cmd_2) self.btn_cmd_2 = QtWidgets.QPushButton(self.tab) self.btn_cmd_2.setAccessibleDescription("") self.btn_cmd_2.setObjectName("btn_cmd_2") self.horizontalLayout_10.addWidget(self.btn_cmd_2) self.horizontalLayout_10.setStretch(0, 6) self.horizontalLayout_10.setStretch(1, 1) self.formLayout.setLayout(3, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_10) self.horizontalLayout_8 = QtWidgets.QHBoxLayout() self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.lineEdit_2 = QtWidgets.QLineEdit(self.tab) self.lineEdit_2.setEnabled(False) self.lineEdit_2.setObjectName("lineEdit_2") self.horizontalLayout_8.addWidget(self.lineEdit_2) self.lineEdit_3 = QtWidgets.QLineEdit(self.tab) self.lineEdit_3.setEnabled(False) self.lineEdit_3.setObjectName("lineEdit_3") self.horizontalLayout_8.addWidget(self.lineEdit_3) self.lineEdit = QtWidgets.QLineEdit(self.tab) self.lineEdit.setEnabled(False) self.lineEdit.setObjectName("lineEdit") self.horizontalLayout_8.addWidget(self.lineEdit) self.lineEdit_4 = QtWidgets.QLineEdit(self.tab) self.lineEdit_4.setEnabled(False) self.lineEdit_4.setObjectName("lineEdit_4") self.horizontalLayout_8.addWidget(self.lineEdit_4) self.lineEdit_5 = QtWidgets.QLineEdit(self.tab) self.lineEdit_5.setEnabled(False) self.lineEdit_5.setObjectName("lineEdit_5") self.horizontalLayout_8.addWidget(self.lineEdit_5) self.formLayout.setLayout(4, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_8) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.line_body_height = QtWidgets.QLineEdit(self.tab) self.line_body_height.setObjectName("line_body_height") self.horizontalLayout_6.addWidget(self.line_body_height) self.line_body_years_old = QtWidgets.QLineEdit(self.tab) self.line_body_years_old.setObjectName("line_body_years_old") self.horizontalLayout_6.addWidget(self.line_body_years_old) self.line_body_weight = QtWidgets.QLineEdit(self.tab) self.line_body_weight.setObjectName("line_body_weight") self.horizontalLayout_6.addWidget(self.line_body_weight) self.line_body_gender = QtWidgets.QLineEdit(self.tab) self.line_body_gender.setObjectName("line_body_gender") self.horizontalLayout_6.addWidget(self.line_body_gender) self.line_body_mode = QtWidgets.QLineEdit(self.tab) self.line_body_mode.setEnabled(False) self.line_body_mode.setObjectName("line_body_mode") self.horizontalLayout_6.addWidget(self.line_body_mode) self.horizontalLayout_6.setStretch(0, 1) self.horizontalLayout_6.setStretch(1, 1) self.horizontalLayout_6.setStretch(2, 1) self.horizontalLayout_6.setStretch(3, 1) self.horizontalLayout_6.setStretch(4, 1) self.horizontalLayout_4.addLayout(self.horizontalLayout_6) self.formLayout.setLayout(5, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_4) self.checkBox_3 = QtWidgets.QCheckBox(self.tab) self.checkBox_3.setEnabled(False) self.checkBox_3.setObjectName("checkBox_3") self.formLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.checkBox_3) self.label_9 = QtWidgets.QLabel(self.tab) self.label_9.setObjectName("label_9") self.formLayout.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.label_9) self.horizontalLayout_11 = QtWidgets.QHBoxLayout() self.horizontalLayout_11.setObjectName("horizontalLayout_11") self.line_cmd_3 = QtWidgets.QLineEdit(self.tab) self.line_cmd_3.setEnabled(False) self.line_cmd_3.setAccessibleDescription("") self.line_cmd_3.setObjectName("line_cmd_3") self.horizontalLayout_11.addWidget(self.line_cmd_3) self.btn_cmd_3 = QtWidgets.QPushButton(self.tab) self.btn_cmd_3.setAccessibleDescription("") self.btn_cmd_3.setObjectName("btn_cmd_3") self.horizontalLayout_11.addWidget(self.btn_cmd_3) self.horizontalLayout_11.setStretch(0, 6) self.horizontalLayout_11.setStretch(1, 1) self.formLayout.setLayout(7, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_11) self.checkBox_8 = QtWidgets.QCheckBox(self.tab) self.checkBox_8.setEnabled(False) self.checkBox_8.setObjectName("checkBox_8") self.formLayout.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.checkBox_8) self.label_8 = QtWidgets.QLabel(self.tab) self.label_8.setObjectName("label_8") self.formLayout.setWidget(8, QtWidgets.QFormLayout.FieldRole, self.label_8) self.horizontalLayout_12 = QtWidgets.QHBoxLayout() self.horizontalLayout_12.setObjectName("horizontalLayout_12") self.line_cmd_4 = QtWidgets.QLineEdit(self.tab) self.line_cmd_4.setEnabled(False) self.line_cmd_4.setAccessibleDescription("") self.line_cmd_4.setObjectName("line_cmd_4") self.horizontalLayout_12.addWidget(self.line_cmd_4) self.btn_cmd_4 = QtWidgets.QPushButton(self.tab) self.btn_cmd_4.setAccessibleDescription("") self.btn_cmd_4.setObjectName("btn_cmd_4") self.horizontalLayout_12.addWidget(self.btn_cmd_4) self.horizontalLayout_12.setStretch(0, 6) self.horizontalLayout_12.setStretch(1, 1) self.formLayout.setLayout(9, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_12) self.checkBox_9 = QtWidgets.QCheckBox(self.tab) self.checkBox_9.setEnabled(False) self.checkBox_9.setObjectName("checkBox_9") self.formLayout.setWidget(10, QtWidgets.QFormLayout.LabelRole, self.checkBox_9) self.label_10 = QtWidgets.QLabel(self.tab) self.label_10.setObjectName("label_10") self.formLayout.setWidget(10, QtWidgets.QFormLayout.FieldRole, self.label_10) self.horizontalLayout_13 = QtWidgets.QHBoxLayout() self.horizontalLayout_13.setObjectName("horizontalLayout_13") self.line_cmd_5 = QtWidgets.QLineEdit(self.tab) self.line_cmd_5.setEnabled(False) self.line_cmd_5.setAccessibleDescription("") self.line_cmd_5.setObjectName("line_cmd_5") self.horizontalLayout_13.addWidget(self.line_cmd_5) self.btn_cmd_5 = QtWidgets.QPushButton(self.tab) self.btn_cmd_5.setAccessibleDescription("") self.btn_cmd_5.setObjectName("btn_cmd_5") self.horizontalLayout_13.addWidget(self.btn_cmd_5) self.horizontalLayout_13.setStretch(0, 6) self.horizontalLayout_13.setStretch(1, 1) self.formLayout.setLayout(11, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_13) self.checkBox_7 = QtWidgets.QCheckBox(self.tab) self.checkBox_7.setEnabled(False) self.checkBox_7.setObjectName("checkBox_7") self.formLayout.setWidget(12, QtWidgets.QFormLayout.LabelRole, self.checkBox_7) self.label_11 = QtWidgets.QLabel(self.tab) self.label_11.setObjectName("label_11") self.formLayout.setWidget(12, QtWidgets.QFormLayout.FieldRole, self.label_11) self.horizontalLayout_14 = QtWidgets.QHBoxLayout() self.horizontalLayout_14.setObjectName("horizontalLayout_14") self.line_cmd_6 = QtWidgets.QLineEdit(self.tab) self.line_cmd_6.setEnabled(False) self.line_cmd_6.setAccessibleDescription("") self.line_cmd_6.setObjectName("line_cmd_6") self.horizontalLayout_14.addWidget(self.line_cmd_6) self.btn_cmd_6 = QtWidgets.QPushButton(self.tab) self.btn_cmd_6.setAccessibleDescription("") self.btn_cmd_6.setObjectName("btn_cmd_6") self.horizontalLayout_14.addWidget(self.btn_cmd_6) self.horizontalLayout_14.setStretch(0, 6) self.horizontalLayout_14.setStretch(1, 1) self.formLayout.setLayout(13, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_14) self.checkBox_6 = QtWidgets.QCheckBox(self.tab) self.checkBox_6.setEnabled(False) self.checkBox_6.setObjectName("checkBox_6") self.formLayout.setWidget(14, QtWidgets.QFormLayout.LabelRole, self.checkBox_6) self.label_12 = QtWidgets.QLabel(self.tab) self.label_12.setObjectName("label_12") self.formLayout.setWidget(14, QtWidgets.QFormLayout.FieldRole, self.label_12) self.horizontalLayout_15 = QtWidgets.QHBoxLayout() self.horizontalLayout_15.setObjectName("horizontalLayout_15") self.line_cmd_7 = QtWidgets.QLineEdit(self.tab) self.line_cmd_7.setEnabled(True) self.line_cmd_7.setAccessibleDescription("") self.line_cmd_7.setObjectName("line_cmd_7") self.horizontalLayout_15.addWidget(self.line_cmd_7) self.btn_cmd_7 = QtWidgets.QPushButton(self.tab) self.btn_cmd_7.setAccessibleDescription("") self.btn_cmd_7.setObjectName("btn_cmd_7") self.horizontalLayout_15.addWidget(self.btn_cmd_7) self.horizontalLayout_15.setStretch(0, 6) self.horizontalLayout_15.setStretch(1, 1) self.formLayout.setLayout(15, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_15) self.checkBox_10 = QtWidgets.QCheckBox(self.tab) self.checkBox_10.setEnabled(False) self.checkBox_10.setObjectName("checkBox_10") self.formLayout.setWidget(16, QtWidgets.QFormLayout.LabelRole, self.checkBox_10) self.label_13 = QtWidgets.QLabel(self.tab) self.label_13.setObjectName("label_13") self.formLayout.setWidget(16, QtWidgets.QFormLayout.FieldRole, self.label_13) self.horizontalLayout_17 = QtWidgets.QHBoxLayout() self.horizontalLayout_17.setObjectName("horizontalLayout_17") self.line_cmd_8 = QtWidgets.QLineEdit(self.tab) self.line_cmd_8.setEnabled(False) self.line_cmd_8.setAccessibleDescription("") self.line_cmd_8.setObjectName("line_cmd_8") self.horizontalLayout_17.addWidget(self.line_cmd_8) self.btn_cmd_8 = QtWidgets.QPushButton(self.tab) self.btn_cmd_8.setAccessibleDescription("") self.btn_cmd_8.setObjectName("btn_cmd_8") self.horizontalLayout_17.addWidget(self.btn_cmd_8) self.horizontalLayout_17.setStretch(0, 6) self.horizontalLayout_17.setStretch(1, 1) self.formLayout.setLayout(17, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_17) self.checkBox_13 = QtWidgets.QCheckBox(self.tab) self.checkBox_13.setEnabled(False) self.checkBox_13.setObjectName("checkBox_13") self.formLayout.setWidget(18, QtWidgets.QFormLayout.LabelRole, self.checkBox_13) self.label_16 = QtWidgets.QLabel(self.tab) self.label_16.setObjectName("label_16") self.formLayout.setWidget(18, QtWidgets.QFormLayout.FieldRole, self.label_16) self.horizontalLayout_19 = QtWidgets.QHBoxLayout() self.horizontalLayout_19.setObjectName("horizontalLayout_19") self.line_cmd_9 = QtWidgets.QLineEdit(self.tab) self.line_cmd_9.setEnabled(False) self.line_cmd_9.setAccessibleDescription("") self.line_cmd_9.setObjectName("line_cmd_9") self.horizontalLayout_19.addWidget(self.line_cmd_9) self.btn_cmd_9 = QtWidgets.QPushButton(self.tab) self.btn_cmd_9.setAccessibleDescription("") self.btn_cmd_9.setObjectName("btn_cmd_9") self.horizontalLayout_19.addWidget(self.btn_cmd_9) self.horizontalLayout_19.setStretch(0, 6) self.horizontalLayout_19.setStretch(1, 1) self.formLayout.setLayout(19, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_19) self.checkBox_14 = QtWidgets.QCheckBox(self.tab) self.checkBox_14.setEnabled(False) self.checkBox_14.setObjectName("checkBox_14") self.formLayout.setWidget(20, QtWidgets.QFormLayout.LabelRole, self.checkBox_14) self.label_17 = QtWidgets.QLabel(self.tab) self.label_17.setObjectName("label_17") self.formLayout.setWidget(20, QtWidgets.QFormLayout.FieldRole, self.label_17) self.horizontalLayout_20 = QtWidgets.QHBoxLayout() self.horizontalLayout_20.setObjectName("horizontalLayout_20") self.horizontalLayout_16 = QtWidgets.QHBoxLayout() self.horizontalLayout_16.setObjectName("horizontalLayout_16") self.line_cmd_query = QtWidgets.QLineEdit(self.tab) self.line_cmd_query.setEnabled(False) self.line_cmd_query.setAccessibleDescription("") self.line_cmd_query.setObjectName("line_cmd_query") self.horizontalLayout_16.addWidget(self.line_cmd_query) self.line_cmd_query_dis = QtWidgets.QLineEdit(self.tab) self.line_cmd_query_dis.setObjectName("line_cmd_query_dis") self.horizontalLayout_16.addWidget(self.line_cmd_query_dis) self.horizontalLayout_20.addLayout(self.horizontalLayout_16) self.btn_cmd_query = QtWidgets.QPushButton(self.tab) self.btn_cmd_query.setAccessibleDescription("") self.btn_cmd_query.setObjectName("btn_cmd_query") self.horizontalLayout_20.addWidget(self.btn_cmd_query) self.horizontalLayout_20.setStretch(0, 6) self.horizontalLayout_20.setStretch(1, 1) self.formLayout.setLayout(21, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_20) self.checkBox_16 = QtWidgets.QCheckBox(self.tab) self.checkBox_16.setEnabled(False) self.checkBox_16.setObjectName("checkBox_16") self.formLayout.setWidget(22, QtWidgets.QFormLayout.LabelRole, self.checkBox_16) self.label_19 = QtWidgets.QLabel(self.tab) self.label_19.setObjectName("label_19") self.formLayout.setWidget(22, QtWidgets.QFormLayout.FieldRole, self.label_19) self.horizontalLayout_22 = QtWidgets.QHBoxLayout() self.horizontalLayout_22.setObjectName("horizontalLayout_22") self.line_cmd_write = QtWidgets.QLineEdit(self.tab) self.line_cmd_write.setEnabled(True) self.line_cmd_write.setAccessibleDescription("") self.line_cmd_write.setObjectName("line_cmd_write") self.horizontalLayout_22.addWidget(self.line_cmd_write) self.btn_cmd_write = QtWidgets.QPushButton(self.tab) self.btn_cmd_write.setAccessibleDescription("") self.btn_cmd_write.setObjectName("btn_cmd_write") self.horizontalLayout_22.addWidget(self.btn_cmd_write) self.horizontalLayout_22.setStretch(0, 6) self.horizontalLayout_22.setStretch(1, 1) self.formLayout.setLayout(23, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_22) self.checkBox_11 = QtWidgets.QCheckBox(self.tab) self.checkBox_11.setEnabled(False) self.checkBox_11.setObjectName("checkBox_11") self.formLayout.setWidget(24, QtWidgets.QFormLayout.LabelRole, self.checkBox_11) self.label_14 = QtWidgets.QLabel(self.tab) self.label_14.setObjectName("label_14") self.formLayout.setWidget(24, QtWidgets.QFormLayout.FieldRole, self.label_14) self.horizontalLayout_18 = QtWidgets.QHBoxLayout() self.horizontalLayout_18.setObjectName("horizontalLayout_18") self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.line_cmd_read = QtWidgets.QLineEdit(self.tab) self.line_cmd_read.setEnabled(True) self.line_cmd_read.setAccessibleDescription("") self.line_cmd_read.setObjectName("line_cmd_read") self.horizontalLayout_3.addWidget(self.line_cmd_read) self.line_cmd_read_dis = QtWidgets.QLineEdit(self.tab) self.line_cmd_read_dis.setObjectName("line_cmd_read_dis") self.horizontalLayout_3.addWidget(self.line_cmd_read_dis) self.horizontalLayout_18.addLayout(self.horizontalLayout_3) self.btn_cmd_read = QtWidgets.QPushButton(self.tab) self.btn_cmd_read.setAccessibleDescription("") self.btn_cmd_read.setObjectName("btn_cmd_read") self.horizontalLayout_18.addWidget(self.btn_cmd_read) self.horizontalLayout_18.setStretch(0, 6) self.horizontalLayout_18.setStretch(1, 1) self.formLayout.setLayout(25, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_18) self.checkBox_12 = QtWidgets.QCheckBox(self.tab) self.checkBox_12.setEnabled(False) self.checkBox_12.setObjectName("checkBox_12") self.formLayout.setWidget(26, QtWidgets.QFormLayout.LabelRole, self.checkBox_12) self.label_15 = QtWidgets.QLabel(self.tab) self.label_15.setObjectName("label_15") self.formLayout.setWidget(26, QtWidgets.QFormLayout.FieldRole, self.label_15) self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.btn_query_state = QtWidgets.QPushButton(self.tab) self.btn_query_state.setObjectName("btn_query_state") self.horizontalLayout_5.addWidget(self.btn_query_state) self.btn_cmd_reset = QtWidgets.QPushButton(self.tab) self.btn_cmd_reset.setObjectName("btn_cmd_reset") self.horizontalLayout_5.addWidget(self.btn_cmd_reset) self.horizontalLayout_5.setStretch(0, 6) self.horizontalLayout_5.setStretch(1, 1) self.formLayout.setLayout(27, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_5) self.checkBox.raise_() self.label_6.raise_() self.checkBox_2.raise_() self.label_7.raise_() self.checkBox_3.raise_() self.label_9.raise_() self.checkBox_8.raise_() self.label_8.raise_() self.checkBox_9.raise_() self.label_10.raise_() self.checkBox_7.raise_() self.label_11.raise_() self.checkBox_6.raise_() self.label_12.raise_() self.checkBox_10.raise_() self.label_13.raise_() self.checkBox_11.raise_() self.label_14.raise_() self.checkBox_12.raise_() self.label_15.raise_() self.checkBox_13.raise_() self.label_16.raise_() self.checkBox_14.raise_() self.label_17.raise_() self.checkBox_16.raise_() self.label_19.raise_() self.tabWidget.addTab(self.tab, "") self.tab_12 = QtWidgets.QWidget() self.tab_12.setObjectName("tab_12") self.gridLayout = QtWidgets.QGridLayout(self.tab_12) self.gridLayout.setObjectName("gridLayout") self.horizontalLayout_23 = QtWidgets.QHBoxLayout() self.horizontalLayout_23.setObjectName("horizontalLayout_23") self.verticalLayout_11 = QtWidgets.QVBoxLayout() self.verticalLayout_11.setObjectName("verticalLayout_11") self.horizontalLayout_24 = QtWidgets.QHBoxLayout() self.horizontalLayout_24.setObjectName("horizontalLayout_24") self.lineEdit_8 = QtWidgets.QLineEdit(self.tab_12) self.lineEdit_8.setEnabled(False) self.lineEdit_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lineEdit_8.setObjectName("lineEdit_8") self.horizontalLayout_24.addWidget(self.lineEdit_8) self.line_timer_read_addr = QtWidgets.QLineEdit(self.tab_12) self.line_timer_read_addr.setObjectName("line_timer_read_addr") self.horizontalLayout_24.addWidget(self.line_timer_read_addr) self.horizontalLayout_24.setStretch(0, 2) self.horizontalLayout_24.setStretch(1, 1) self.verticalLayout_11.addLayout(self.horizontalLayout_24) self.horizontalLayout_25 = QtWidgets.QHBoxLayout() self.horizontalLayout_25.setObjectName("horizontalLayout_25") self.lineEdit_9 = QtWidgets.QLineEdit(self.tab_12) self.lineEdit_9.setEnabled(False) self.lineEdit_9.setLayoutDirection(QtCore.Qt.LeftToRight) self.lineEdit_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lineEdit_9.setObjectName("lineEdit_9") self.horizontalLayout_25.addWidget(self.lineEdit_9) self.line_timer_read_byte_len = QtWidgets.QLineEdit(self.tab_12) self.line_timer_read_byte_len.setObjectName("line_timer_read_byte_len") self.horizontalLayout_25.addWidget(self.line_timer_read_byte_len) self.horizontalLayout_25.setStretch(0, 2) self.horizontalLayout_25.setStretch(1, 1) self.verticalLayout_11.addLayout(self.horizontalLayout_25) self.horizontalLayout_26 = QtWidgets.QHBoxLayout() self.horizontalLayout_26.setObjectName("horizontalLayout_26") self.lineEdit_6 = QtWidgets.QLineEdit(self.tab_12) self.lineEdit_6.setEnabled(False) self.lineEdit_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lineEdit_6.setObjectName("lineEdit_6") self.horizontalLayout_26.addWidget(self.lineEdit_6) self.line_read_time = QtWidgets.QLineEdit(self.tab_12) self.line_read_time.setObjectName("line_read_time") self.horizontalLayout_26.addWidget(self.line_read_time) self.horizontalLayout_26.setStretch(0, 2) self.horizontalLayout_26.setStretch(1, 1) self.verticalLayout_11.addLayout(self.horizontalLayout_26) self.horizontalLayout_23.addLayout(self.verticalLayout_11) self.verticalLayout_12 = QtWidgets.QVBoxLayout() self.verticalLayout_12.setObjectName("verticalLayout_12") self.comboBox_read_timer = QtWidgets.QComboBox(self.tab_12) self.comboBox_read_timer.setLayoutDirection(QtCore.Qt.LeftToRight) self.comboBox_read_timer.setObjectName("comboBox_read_timer") self.verticalLayout_12.addWidget(self.comboBox_read_timer) self.btn_read_timer = QtWidgets.QPushButton(self.tab_12) self.btn_read_timer.setObjectName("btn_read_timer") self.verticalLayout_12.addWidget(self.btn_read_timer) self.horizontalLayout_23.addLayout(self.verticalLayout_12) self.horizontalLayout_23.setStretch(0, 2) self.horizontalLayout_23.setStretch(1, 1) self.gridLayout.addLayout(self.horizontalLayout_23, 0, 0, 1, 1) self.plainTextEdit_read_timer = QtWidgets.QPlainTextEdit(self.tab_12) self.plainTextEdit_read_timer.setObjectName("plainTextEdit_read_timer") self.gridLayout.addWidget(self.plainTextEdit_read_timer, 1, 0, 1, 1) self.tabWidget.addTab(self.tab_12, "") self.tab_13 = QtWidgets.QWidget() self.tab_13.setObjectName("tab_13") self.verticalLayout_10 = QtWidgets.QVBoxLayout(self.tab_13) self.verticalLayout_10.setObjectName("verticalLayout_10") self.horizontalLayout_21 = QtWidgets.QHBoxLayout() self.horizontalLayout_21.setObjectName("horizontalLayout_21") self.textBrowser_iap = QtWidgets.QTextBrowser(self.tab_13) self.textBrowser_iap.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.textBrowser_iap.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.textBrowser_iap.setObjectName("textBrowser_iap") self.horizontalLayout_21.addWidget(self.textBrowser_iap) self.textBrowser_iap_read = QtWidgets.QTextBrowser(self.tab_13) self.textBrowser_iap_read.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.textBrowser_iap_read.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.textBrowser_iap_read.setObjectName("textBrowser_iap_read") self.horizontalLayout_21.addWidget(self.textBrowser_iap_read) self.verticalLayout_10.addLayout(self.horizontalLayout_21) self.btn_iap_loadfile = QtWidgets.QPushButton(self.tab_13) self.btn_iap_loadfile.setObjectName("btn_iap_loadfile") self.verticalLayout_10.addWidget(self.btn_iap_loadfile) self.btn_iap_erase = QtWidgets.QPushButton(self.tab_13) self.btn_iap_erase.setObjectName("btn_iap_erase") self.verticalLayout_10.addWidget(self.btn_iap_erase) self.btn_iap_start = QtWidgets.QPushButton(self.tab_13) self.btn_iap_start.setEnabled(False) self.btn_iap_start.setObjectName("btn_iap_start") self.verticalLayout_10.addWidget(self.btn_iap_start) self.btn_iap_read_flash = QtWidgets.QPushButton(self.tab_13) self.btn_iap_read_flash.setEnabled(False) self.btn_iap_read_flash.setObjectName("btn_iap_read_flash") self.verticalLayout_10.addWidget(self.btn_iap_read_flash) self.btn_iap_get_version = QtWidgets.QPushButton(self.tab_13) self.btn_iap_get_version.setObjectName("btn_iap_get_version") self.verticalLayout_10.addWidget(self.btn_iap_get_version) self.tabWidget.addTab(self.tab_13, "") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.gridLayout_4 = QtWidgets.QGridLayout(self.tab_3) self.gridLayout_4.setObjectName("gridLayout_4") self.textEdit = QtWidgets.QTextEdit(self.tab_3) font = QtGui.QFont() font.setFamily("宋体") self.textEdit.setFont(font) self.textEdit.setReadOnly(True) self.textEdit.setObjectName("textEdit") self.gridLayout_4.addWidget(self.textEdit, 0, 0, 1, 1) self.tabWidget.addTab(self.tab_3, "") self.horizontalLayout_7.addWidget(self.tabWidget) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 660, 23)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(4) self.tabWidget_2.setCurrentIndex(3) self.tabWidget_3.setCurrentIndex(3) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "CSM37F58-八电极模块测试上位机")) self.btn_update_all.setText(_translate("MainWindow", "点击更新全部RAM")) self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_4), _translate("MainWindow", "设备配置区(读/写)")) self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_5), _translate("MainWindow", "设备信息区(读)")) self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_8), _translate("MainWindow", "用户信息区(读/写)")) self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_9), _translate("MainWindow", "用户测试BIA区(读)")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_6), _translate("MainWindow", "成分分析结果区(读)")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_7), _translate("MainWindow", "测试过程数据区(读)")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_10), _translate("MainWindow", "通讯日志区(读)")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_11), _translate("MainWindow", "真实电阻显示区(读)")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "各片区RAM(读/写)")) self.checkBox.setText(_translate("MainWindow", "1")) self.label_6.setText(_translate("MainWindow", "WakeUp命令")) self.line_cmd_1.setText(_translate("MainWindow", "0xA0 0x3F 0x5A 0x53")) self.btn_cmd_1.setToolTip(_translate("MainWindow", "发送此命令,唤醒模组")) self.btn_cmd_1.setText(_translate("MainWindow", "发送")) self.checkBox_2.setText(_translate("MainWindow", "2")) self.label_7.setText(_translate("MainWindow", "写入人体参数")) self.line_cmd_2.setText(_translate("MainWindow", "0xA0 0x10 0x58 0x02 0xC1 0xAA 0x9E 0x00")) self.btn_cmd_2.setToolTip(_translate("MainWindow", "直接更改,自动更新到命令(发送5次写命令)")) self.btn_cmd_2.setText(_translate("MainWindow", "发送")) self.lineEdit_2.setText(_translate("MainWindow", "身高(cm)")) self.lineEdit_3.setText(_translate("MainWindow", "年龄(岁)")) self.lineEdit.setText(_translate("MainWindow", "体重(kg)")) self.lineEdit_4.setText(_translate("MainWindow", "性别")) self.lineEdit_5.setText(_translate("MainWindow", "模式")) self.line_body_height.setText(_translate("MainWindow", "170")) self.line_body_years_old.setText(_translate("MainWindow", "30")) self.line_body_weight.setText(_translate("MainWindow", "70.5")) self.line_body_gender.setText(_translate("MainWindow", "男")) self.line_body_mode.setText(_translate("MainWindow", "默认")) self.checkBox_3.setText(_translate("MainWindow", "3")) self.label_9.setText(_translate("MainWindow", "使能测量开关")) self.line_cmd_3.setText(_translate("MainWindow", "0xA0 0x10 0x00 0x80")) self.btn_cmd_3.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_3.setText(_translate("MainWindow", "发送")) self.checkBox_8.setText(_translate("MainWindow", "4")) self.label_8.setText(_translate("MainWindow", "计算成分命令")) self.line_cmd_4.setText(_translate("MainWindow", "0xA0 0x3F 0x5A 0x04")) self.btn_cmd_4.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_4.setText(_translate("MainWindow", "发送")) self.checkBox_9.setText(_translate("MainWindow", "5")) self.label_10.setText(_translate("MainWindow", "Sleep命令(发送后不要再发命令,否则唤醒)")) self.line_cmd_5.setText(_translate("MainWindow", "0xA0 0x3F 0x5A 0x35")) self.btn_cmd_5.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_5.setText(_translate("MainWindow", "发送")) self.checkBox_7.setText(_translate("MainWindow", "6")) self.label_11.setText(_translate("MainWindow", "写Flash命令(M_PART 和 FREQ有效)")) self.line_cmd_6.setText(_translate("MainWindow", "0xA0 0x3F 0x5A 0x05")) self.btn_cmd_6.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_6.setText(_translate("MainWindow", "发送")) self.checkBox_6.setText(_translate("MainWindow", "7")) self.label_12.setText(_translate("MainWindow", "更改测试部位为双手,默认50KHz(需先发送写Flash命令)")) self.line_cmd_7.setText(_translate("MainWindow", "0xA0 0x10 0x02 0x01")) self.btn_cmd_7.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_7.setText(_translate("MainWindow", "发送")) self.checkBox_10.setText(_translate("MainWindow", "8")) self.label_13.setText(_translate("MainWindow", "解锁写保护命令")) self.line_cmd_8.setText(_translate("MainWindow", "0xA0 0x3F 0x5A 0x06")) self.btn_cmd_8.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_8.setText(_translate("MainWindow", "发送")) self.checkBox_13.setText(_translate("MainWindow", "9")) self.label_16.setText(_translate("MainWindow", "打开校准开关(需先发送解锁写保护命令)")) self.line_cmd_9.setText(_translate("MainWindow", "0xA0 0x10 0x09 0x80")) self.btn_cmd_9.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_9.setText(_translate("MainWindow", "发送")) self.checkBox_14.setText(_translate("MainWindow", "10")) self.label_17.setText(_translate("MainWindow", "查询模块是运行在BOOT还是APP下")) self.line_cmd_query.setText(_translate("MainWindow", "0xA0 0xF0 0x00")) self.btn_cmd_query.setToolTip(_translate("MainWindow", "BOOT(启动模式:0x00), APP(正常就绪:0x01)")) self.btn_cmd_query.setText(_translate("MainWindow", "查询")) self.checkBox_16.setText(_translate("MainWindow", "11")) self.label_19.setText(_translate("MainWindow", "自定义写命令(写一个Byte)")) self.line_cmd_write.setText(_translate("MainWindow", "0xA0 0x10 0x58 0xAA")) self.btn_cmd_write.setToolTip(_translate("MainWindow", "硬件地址+发送数据地址+发送数据")) self.btn_cmd_write.setText(_translate("MainWindow", "发送")) self.checkBox_11.setText(_translate("MainWindow", "12")) self.label_14.setText(_translate("MainWindow", "自定义读命令(读取一个byte)")) self.line_cmd_read.setText(_translate("MainWindow", "0xA0 0x10 0x58")) self.btn_cmd_read.setToolTip(_translate("MainWindow", "硬件地址+读取数据地址")) self.btn_cmd_read.setText(_translate("MainWindow", "读取")) self.checkBox_12.setText(_translate("MainWindow", "13")) self.label_15.setText(_translate("MainWindow", "查询/复位CSM37F58")) self.btn_query_state.setText(_translate("MainWindow", "查询READY信号状态")) self.btn_cmd_reset.setToolTip(_translate("MainWindow", "显示读取到的内容")) self.btn_cmd_reset.setText(_translate("MainWindow", "复位")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "命令区(功能)")) self.lineEdit_8.setText(_translate("MainWindow", "读取地址((Base + Offset) Addr):")) self.line_timer_read_addr.setText(_translate("MainWindow", "0x11AC")) self.lineEdit_9.setText(_translate("MainWindow", "连续读取字节数(Bytes):")) self.line_timer_read_byte_len.setText(_translate("MainWindow", "1")) self.lineEdit_6.setText(_translate("MainWindow", "定时间隔时间(ms):")) self.line_read_time.setText(_translate("MainWindow", "1000")) self.btn_read_timer.setText(_translate("MainWindow", "开始")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_12), _translate("MainWindow", "定时任务")) self.btn_iap_loadfile.setText(_translate("MainWindow", "选择文件")) self.btn_iap_erase.setToolTip(_translate("MainWindow", "[0xA0, 0x00, 0x00, 0xAA, 0x55, 0xA5, 0x5A]")) self.btn_iap_erase.setText(_translate("MainWindow", "擦除Flash")) self.btn_iap_start.setToolTip(_translate("MainWindow", "先点击擦除Flash命令,会激活此按钮")) self.btn_iap_start.setText(_translate("MainWindow", "升级(先擦除)")) self.btn_iap_read_flash.setText(_translate("MainWindow", "ReadFlash(加校验区)")) self.btn_iap_get_version.setToolTip(_translate("MainWindow", "[0xA0, 0xFF, 0xFF, 0xA1,0xRead,0xRead,0xRead,0xRead]")) self.btn_iap_get_version.setText(_translate("MainWindow", "查询当前版本号(0xFFFF)")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_13), _translate("MainWindow", "在线升级(IAP)")) self.textEdit.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'宋体\'; font-size:9pt; font-weight:400; font-style:normal;\">\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\';\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\';\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600;\">注意事项</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt;\"> </span><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> </span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt;\"> 1. 连接示意图.</span></p>\n" "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><img src=\":/picture/img/connect_demo.png\" /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600;\"> 2</span><span style=\" font-family:\'Consolas\'; font-size:12pt; font-weight:600;\">.</span><span style=\" font-family:\'Simsum\'; font-size:12pt; color:#000000;\"> 可能需要安装微软官方C++类库:</span><a href=\" https://www.microsoft.com/en-us/download/details.aspx?id=48145\"><span style=\" text-decoration: underline; color:#0000ff;\">https://www.microsoft.com/en-us/download/details.aspx?id=48145</span></a></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; text-decoration: underline; color:#0000ff;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; text-decoration: underline; color:#0000ff;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600;\">版本说明</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600;\"> </span><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600; font-style:italic;\">V0.4</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 1. 增加了定时查询制定地址</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 2. 保存对应的十进制数据到.csv文件</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600;\"> </span><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600; font-style:italic;\">V0.3</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 1. 增加了IAP功能.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 2. 查询当前版本.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 3. 擦除Flash.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 4. 加载bin文件.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600; font-style:italic;\"> V0.2</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 1. 修复部分RAM读取首地址错误问题.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 2. 发送命令时关闭按键使能.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 3. 更新到最新命令.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:16pt;\"> </span><span style=\" font-family:\'Consolas\'; font-size:16pt; font-weight:600; font-style:italic;\">V0.1</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 1. 读取所有RAM值.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 2. 基本命令.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Consolas\'; font-size:12pt;\"> 3. 自定义命令.</span></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\'; font-size:12pt; font-weight:600;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\'; font-size:16pt; font-weight:600;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\'; font-size:16pt; font-weight:600;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\'; font-size:16pt; font-weight:600;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\'; font-size:16pt; font-weight:600;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\';\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Consolas\';\"><br /></p></body></html>")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "帮助/使用手册")) import picture_rc
{"/CSM37F58_APP.py": ["/CSM37F58_APP_ui.py"]}
41,404
junglefive/EightPoleModuleTester
refs/heads/master
/CSM37F58_APP.py
import sys,time,os from CSM37F58_APP_ui import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from serial.tools.list_ports import * from picture_qrc import * import datetime from IIC_CH341 import * from PyQt5.QtCore import QTimer import numpy as np class MyApp(QtWidgets.QMainWindow, Ui_MainWindow): CMD_CSM37F58_IAP_CHECKSUM_ADDRESS = 0xEC00 CMD_CSM37F58_IAP_GET_VERSION_ADDRESS = 0xFFFF def __init__(self): super(MyApp, self).__init__() QtWidgets.QMainWindow.__init__(self) self.setupUi(self) Ui_MainWindow.__init__(self) # logo self.setWindowIcon(QIcon(":picture/img/110.png")) # 默认时间戳 self.time_stamp = datetime.datetime.now().strftime('%Y-%m-%d') # #初始化显示大小 self.init_default_display() self.init_watch_table_all() self.init_read_timer() ## # #初始化信号槽 self.btn_update_all.clicked.connect(self.update_watch_table_display) self.btn_cmd_1.clicked.connect(self.on_click_btn_cmd_1) self.btn_cmd_2.clicked.connect(self.on_click_btn_cmd_2) self.btn_cmd_3.clicked.connect(self.on_click_btn_cmd_3) self.btn_cmd_4.clicked.connect(self.on_click_btn_cmd_4) self.btn_cmd_5.clicked.connect(self.on_click_btn_cmd_5) self.btn_cmd_6.clicked.connect(self.on_click_btn_cmd_6) self.btn_cmd_7.clicked.connect(self.on_click_btn_cmd_7) self.btn_cmd_8.clicked.connect(self.on_click_btn_cmd_8) self.btn_cmd_9.clicked.connect(self.on_click_btn_cmd_9) self.btn_cmd_query.clicked.connect(self.on_click_btn_cmd_query) self.btn_cmd_write.clicked.connect(self.on_click_btn_cmd_write) self.btn_cmd_read.clicked.connect(self.on_click_btn_cmd_read) self.btn_cmd_reset.clicked.connect(self.on_clicked_btn_cmd_reset) self.btn_query_state.clicked.connect(self.on_clicked_btn_query_state) # IAP self.btn_iap_loadfile.clicked.connect(self.on_clicked_btn_iap_loadfile) self.btn_iap_start.clicked.connect(self.on_clicked_btn_iap_start) self.btn_iap_erase.clicked.connect(self.on_clicked_btn_iap_erase) self.btn_iap_get_version.clicked.connect(self.on_clicked_btn_iap_get_version) self.btn_iap_read_flash.clicked.connect(self.on_clicked_btn_iap_read_flash) #line self.line_body_height.textChanged.connect(self.on_changed_line_body_data) self.line_body_weight.textChanged.connect(self.on_changed_line_body_data) self.line_body_years_old.textChanged.connect(self.on_changed_line_body_data) self.line_body_gender.textChanged.connect(self.on_changed_line_body_data) self.line_body_mode.textChanged.connect(self.on_changed_line_body_data) self.btn_read_timer.clicked.connect(self.on_clicked_btn_read_timer) # self.read_timer = QTimer() self.read_timer.timeout.connect(self.read_timer_event) # self.read_timer.start(int(self.line_read_time.text())) def on_clicked_btn_read_timer(self): print("click read_timer") if(self.btn_read_timer.text()=="结束"): self.btn_read_timer.setText("开始") self.timer_event_enable = False # print("stop") self.read_timer.stop() else: #print("start") self.btn_read_timer.setText("结束") self.timer_event_enable = True # self.read_timer.timeout.connect(self.read_timer_event) self.read_timer.start(int(self.line_read_time.text())) def read_timer_event(self): print("timer_event:",datetime.datetime.now().strftime('%Y-%m-%d:%H:%M:%S')) if self.timer_event_enable == True: self.i2c_read_bytes() def read_save_file(self,s): with open("./record.csv","a+") as f: f.write(s) def i2c_read_bytes(self): try: protocol = CH341AIIC() save_mode ='big' if self.comboBox_read_timer.currentText() == "小端模式": save_mode = 'little' address_read = int(self.line_timer_read_addr.text(),16) length = int(self.line_timer_read_byte_len.text()) print("read:", hex(address_read)) result = False read = bytearray() if length == 1: result, read = protocol.read_byte(address_read) else: result,read = protocol.read_bytes(address_read,length) # print("type:",type(read)) #bytes print(str(result),read.hex()) if result: # QMessageBox.information(self, "提示", "读取成功") value = int.from_bytes(read,byteorder= save_mode) self.plainTextEdit_read_timer.appendPlainText("[" + datetime.datetime.now().strftime('%H:%M:%S') + "]: 0x" + read.hex()+","+str(value)) self.read_save_file(str(value)+'\n') print(str(value)) else: QMessageBox.information(self, "错误", "读取失败,请检查硬件") except Exception as e: print(str(e)) self.timer_event_enable =False QMessageBox.information(self, "错误", "读取失败,请检查硬件" + str(e)) def init_read_timer(self): self.line_timer_read_addr.setText("0x11AC") self.line_timer_read_byte_len.setText("1") self.comboBox_read_timer.addItems(["大端模式","小端模式"]) f = open("./record.csv", "a+") f.close() def on_clicked_btn_iap_read_flash(self): try: protocol = CH341AIIC() self.progress_bar = QProgressDialog() self.progress_bar.setWindowTitle("读取Flash中....") self.progress_bar.setWindowIcon(QIcon(":picture/img/110.png")) self.progress_bar.show() self.textBrowser_iap_read.clear() self.refresh_app() print("read_flash:"+str(self.frame_cnt+2)) self.textBrowser_iap_read.append("共加载%s包,加1包校验"%(self.frame_cnt+2)) for i in range(self.frame_cnt+1): result,ret = protocol.read_bytes(i*512,512) print("正在读取第%s包"%(i+1)) if not result: self.progress_bar.close() QMessageBox.information(self, "提示", "没有ACK信号,请检查模块") break self.textBrowser_iap_read.append("第%s包(512):"%(i+1)) self.progress_bar.setValue((i / (self.frame_cnt + 2) * 100)) self.textBrowser_iap_read.append(ret.hex()) self.refresh_app() # 读校验区 time.sleep(0.1) result, ret = protocol.read_bytes(self.CMD_CSM37F58_IAP_CHECKSUM_ADDRESS, 512) self.textBrowser_iap_read.append("第%s包(校验码):" % (self.frame_cnt+2)) self.textBrowser_iap_read.append(ret.hex()) self.progress_bar.setValue(100) except Exception as e: print("on_clicked_btn_iap_read_flash",str(e)) QMessageBox.information(self, "提示", "初始化CS341失败,请检查硬件") def on_clicked_btn_iap_get_version(self): print("获取版本") try: protocol = CH341AIIC() time.sleep(0.01) result,version = protocol.read_bytes(self.CMD_CSM37F58_IAP_GET_VERSION_ADDRESS,4) if result: print(bytes(version).hex()) QMessageBox.information(self, "提示","得到版本号: %s"%((bytes(version)).hex())) else: QMessageBox.information(self, "提示", "发送命令失败") except Exception as e: QMessageBox.information(self, "提示", "初始化CS341失败,请检查硬件") def on_clicked_btn_iap_erase(self): self.CSM37F58_IAP_CMD = [0xA0, 0x00, 0x00, 0xAA, 0x55, 0xA5, 0x5A] try: protocol = CH341AIIC() protocol.reset_io_D0(0.005) time.sleep(0.01) result = protocol.write_bytes(self.CSM37F58_IAP_CMD) if result: self.btn_iap_start.setEnabled(True) QMessageBox.information(self, "提示","命令发送成功") else: QMessageBox.information(self, "提示", "发送命令失败") except Exception as e: QMessageBox.information(self, "提示", "初始化CS341失败,请检查硬件") def on_clicked_btn_iap_start(self): print("clicked iap start") try: file = open(self.bin_path,"rb") bin_data = file.read() file.close() print(len(bin_data),int(len(bin_data)/512)) self.iic_send_bin_file(bin_data) self.btn_iap_start.setEnabled(False) except Exception as e: print(str(e)) QMessageBox.information(self, "提示", "请先选择Bin文件!") def iic_send_bin_file(self,bin_data): self.progress_bar = QProgressDialog() print("正在准备发送...") try: protocol = CH341AIIC() self.frame_cnt = int(len(bin_data) / 512) self.progress_bar.setWindowTitle("在线升级中(IAP)....") self.progress_bar.setWindowIcon(QIcon(":picture/img/110.png")) self.progress_bar.show() self.refresh_app() for i in range(self.frame_cnt): data_512bytes = bin_data[i*512:i*512+512] result = protocol.write_iap_bytes(i*512,bytearray(data_512bytes)) self.progress_bar.setValue((i/(self.frame_cnt+1)*100)) if not result: self.progress_bar.close() QMessageBox.information(self, "提示", "发送失败,请检查硬件") return time.sleep(0.01) # print("升级中..."+str(i)) # 发送最后一帧,可能不满512bytes,补足0xff last_frame = bin_data[(self.frame_cnt)*512:] print("last_frame:"+str(len(last_frame))+":"+(last_frame.hex())) last = bytearray(512) for i in range(512): last[i] = 0xff for i in range(len(last_frame)): last[i] = last_frame[i] protocol.write_iap_bytes(self.frame_cnt*512,last) print(("发送last: "+bytes(last).hex())) # send checksum protocol.write_iap_bytes(self.CMD_CSM37F58_IAP_CHECKSUM_ADDRESS,self.iap_checksum) self.progress_bar.setValue(100) print("升级完成") except Exception as e: print(str(e)) QMessageBox.information(self, "提示", "发送失败,请检查硬件") def on_clicked_btn_iap_loadfile(self): print("load file clicked") try: self.bin_path, describe = QFileDialog.getOpenFileName(self, 'Open file', '.', "txt files (*.bin)") print(self.bin_path) file = open(self.bin_path, "rb");bin_data = file.read();file.close() # get checksum self.frame_cnt = int(len(bin_data)/512) # load self.textBrowser_iap.append("共加载到%sBytes,将发送%s包(加1包校验)"%(len(bin_data),int(len(bin_data)/512)+2)) for i in range(self.frame_cnt): data_512bytes = bin_data[512*i:512*i + 512] self.textBrowser_iap.append("第%s包(512):"%(i+1)) self.textBrowser_iap.append(data_512bytes.hex()) self.refresh_app() # load_end self.iap_checksum = bytearray(512) for i in range(512): self.iap_checksum[i] = 0xff for i in range(self.frame_cnt): data_512bytes = bin_data[512*i:i*512+512] checksum = 0x00 for j in range(512): checksum += data_512bytes[j] self.iap_checksum[i+5] = checksum&0xff print(hex(checksum&0xff)) # 最后一帧处理 last_frame = bin_data[(self.frame_cnt)*512:] last = bytearray(512) for i in range(512): last[i] = 0xff for i in range(len(last_frame)): last[i] = last_frame[i] checksum = 0x00 print("last_len:",len(last)) for i in range(512): checksum += last[i] # last # self.iap_checksum[5+self.frame_cnt] = checksum&0xff self.iap_checksum[4] = self.frame_cnt+1 self.textBrowser_iap.append("第%s包(512):" % (self.frame_cnt + 1)) self.textBrowser_iap.append(bytes(last).hex()) self.refresh_app() #main_checksum version = 0x00 for i in range(self.frame_cnt+1): version +=self.iap_checksum[5+i] print("main_CHECKSUM:",version) version = version&0xffff main_version = (version&0xff00)>>8 other_version = (version&0xff) self.iap_checksum[0] = main_version self.iap_checksum[1] = other_version self.iap_checksum[2] = (~main_version)&0xff self.iap_checksum[3] = (~other_version)&0xff checksum =0x00 self.iap_checksum[511]=0x00 for i in range(512): checksum +=self.iap_checksum[i] self.iap_checksum[511] = checksum&0xff self.textBrowser_iap.append("第%s包(校验码):" % (self.frame_cnt + 2)) self.textBrowser_iap.append(bytes(self.iap_checksum).hex()) print("checksum:"+bytes(self.iap_checksum).hex()) self.btn_iap_loadfile.setText("已选择: "+self.bin_path) self.btn_iap_read_flash.setEnabled(True) except Exception as e: print(str(e)) def on_clicked_btn_query_state(self): print("查询状态...") try: protocol = CH341AIIC() if not protocol.get_input_D7(): QMessageBox.information(self,"提示","检测到低电平") else: QMessageBox.information(self, "提示", "检测到高电平") except Exception as e: QMessageBox.information(self,"提示","失败,请检查硬件") def on_clicked_btn_cmd_reset(self): try: protocol = CH341AIIC() protocol.reset_io_D0(0.005) print("event:按键复位") QMessageBox.information(self,"提示","发送成功") except Exception as e: QMessageBox.information(self,"提示","失败,请检查硬件") def on_changed_line_body_data(self): try: body_list = [0xA0,0x10,0x58,0x02,0xC1,0xAA,0x9E,0x00] body_height = int(self.line_body_height.text()) body_weight = int(float(self.line_body_weight.text())*10) body_years_old = int(self.line_body_years_old.text()) body_gender = self.line_body_gender.text() == "男" body_mode = 0 body_list[3] = body_weight>>8 body_list[4] = body_weight&0xff body_list[5] = body_height body_list[6] = body_gender*0x80 + body_years_old str_dis = ('0x'+' 0x'.join('{:02x}'.format(x) for x in body_list)) print(str_dis) self.line_cmd_2.setText(str_dis) print(str(body_height),str(body_weight),str(body_years_old),str(body_gender),str(body_mode)) except Exception as e: print(str(e)) print("editing...") def on_click_btn_cmd_1(self): self.iic_send_bytes(self.line_cmd_1.text(),True) def on_click_btn_cmd_2(self): hex_str = self.line_cmd_2.text() cmd_hex = hex_str.replace("0x","") cmd_bytes = bytes.fromhex(cmd_hex) cmd = [cmd_bytes[0],cmd_bytes[1],cmd_bytes[2],cmd_bytes[3]] self.iic_send_bytes(bytes(cmd).hex()) cmd[2] = cmd_bytes[2]+1 cmd[3] = cmd_bytes[4] self.iic_send_bytes(bytes(cmd).hex()) cmd[2] = cmd_bytes[2]+2 cmd[3] = cmd_bytes[5] self.iic_send_bytes(bytes(cmd).hex()) cmd[2] = cmd_bytes[2]+3 cmd[3] = cmd_bytes[6] self.iic_send_bytes(bytes(cmd).hex()) cmd[2] = cmd_bytes[2]+4 cmd[3] = cmd_bytes[7] self.iic_send_bytes(bytes(cmd).hex(),True) def on_click_btn_cmd_3(self): self.btn_cmd_3.setEnabled(False) self.iic_send_bytes(self.line_cmd_3.text(),True) self.btn_cmd_3.setEnabled(True) def on_click_btn_cmd_4(self): self.btn_cmd_4.setEnabled(False) self.iic_send_bytes(self.line_cmd_4.text(),True) self.btn_cmd_4.setEnabled(True) def on_click_btn_cmd_5(self): self.btn_cmd_5.setEnabled(False) self.iic_send_bytes(self.line_cmd_5.text(),True) self.btn_cmd_5.setEnabled(True) def on_click_btn_cmd_6(self): self.btn_cmd_6.setEnabled(False) self.iic_send_bytes(self.line_cmd_6.text(),True) self.btn_cmd_6.setEnabled(True) def on_click_btn_cmd_7(self): self.btn_cmd_7.setEnabled(False) self.iic_send_bytes(self.line_cmd_7.text(),True) self.btn_cmd_7.setEnabled(True) def on_click_btn_cmd_8(self): self.btn_cmd_8.setEnabled(False) self.iic_send_bytes(self.line_cmd_8.text(),True) self.btn_cmd_8.setEnabled(True) def on_click_btn_cmd_9(self): self.btn_cmd_9.setEnabled(False) self.iic_send_bytes(self.line_cmd_9.text(),True) self.btn_cmd_9.setEnabled(True) def on_click_btn_cmd_query(self): self.btn_cmd_query.setEnabled(False) self.iic_read_byte(self.line_cmd_query.text(), True, self.line_cmd_query_dis) self.btn_cmd_query.setEnabled(True) def on_click_btn_cmd_write(self): self.btn_cmd_write.setEnabled(False) self.iic_send_bytes(self.line_cmd_write.text(),True) self.btn_cmd_write.setEnabled(True) def on_click_btn_cmd_read(self): self.btn_cmd_read.setEnabled(False) self.iic_read_byte(self.line_cmd_read.text(),True,self.line_cmd_read_dis) self.btn_cmd_read.setEnabled(True) def iic_read_byte(self,hex_str,dis_success,dis_line): try: cmd_hex = hex_str.replace("0x", "") cmd_bytes = bytes.fromhex(cmd_hex) print(hex_str) protocol = CH341AIIC() print(hex(cmd_bytes[1]),hex(cmd_bytes[2])) address_read = (cmd_bytes[1]*256+cmd_bytes[2]) print("read:", hex(address_read)) result,read = protocol.read_byte(address_read) dis_line.setText("读取到数据:"+hex(read[0])) if dis_success & result: QMessageBox.information(self, "提示", "读取成功") elif dis_success: QMessageBox.information(self, "错误", "读取失败,请检查硬件") except Exception as e: print(str(e)) QMessageBox.information(self, "错误", "读取失败,请检查硬件" + str(e)) def refresh_app(self): qApp.processEvents() def iic_send_bytes(self,hex_str, dis_success = False): try: cmd_hex = hex_str.replace("0x","") cmd_bytes = bytes.fromhex(cmd_hex) protocol = CH341AIIC() protocol.set_clk(protocol.IIC_CLK_100kHz) result = protocol.write_bytes(cmd_bytes) print(str(cmd_bytes.hex())) if dis_success&result: QMessageBox.information(self,"提示","发送成功") elif dis_success: QMessageBox.information(self, "错误", "发送失败,请检查硬件" ) except Exception as e: print(str(e)) QMessageBox.information(self,"错误","发送失败,请检查硬件"+str(e)) def init_default_display(self): # size self.__desktop = QApplication.desktop() qRect = self.__desktop.screenGeometry() # 设备屏幕尺寸 self.resize(qRect.width() * 45/ 100, qRect.height() * 90 / 100) self.move(qRect.width() / 3, qRect.height() / 30) def init_watch_table_all(self): self.watch_modle_dev_set = QStandardItemModel(64, 3) self.watch_table_dev_set.setModel(self.watch_modle_dev_set) self.watch_modle_dev_info = QStandardItemModel(24, 3) self.watch_table_dev_info.setModel(self.watch_modle_dev_info) self.watch_modle_usr_info = QStandardItemModel(128, 3) self.watch_table_usr_info.setModel(self.watch_modle_usr_info) self.watch_modle_usr_bia = QStandardItemModel(128, 3) self.watch_table_usr_bia.setModel(self.watch_modle_usr_bia) # page2 self.watch_modle_analy_result = QStandardItemModel(128, 3) self.watch_table_analy_result.setModel(self.watch_modle_analy_result) self.watch_modle_tst_middle = QStandardItemModel(128, 3) self.watch_table_tst_middle.setModel(self.watch_modle_tst_middle) self.watch_modle_com_log = QStandardItemModel(24, 3) self.watch_table_com_log.setModel(self.watch_modle_com_log) self.watch_modle_res_real = QStandardItemModel(128, 3) self.watch_table_res_real.setModel(self.watch_modle_res_real) def update_watch_table_display(self): # 查询数据库数据 # self.watch_modle.setItem(0,0,QStandardItem("示例")) self.progress_bar = QProgressDialog() try: protocol = CH341AIIC() protocol.set_clk(protocol.IIC_CLK_100kHz) # print("逐个读地址:", hex(address_read)) self.progress_bar.setWindowTitle("更新RAM中....") self.progress_bar_current = 0 self.progress_bar_total = (64 + 24 + 128 + 128 + 128 + 128 + 128 + 24) self.progress_bar.setWindowIcon(QIcon(":picture/img/110.png")) self.progress_bar.show() self.update_table(protocol, start_addr=0x1000, read_length=64, watch_modle=self.watch_modle_dev_set) self.update_table(protocol, start_addr=0x1040, read_length=24, watch_modle=self.watch_modle_dev_info) self.update_table(protocol, start_addr=0x1058, read_length=128, watch_modle=self.watch_modle_usr_info) self.update_table(protocol, start_addr=0x10d8, read_length=128, watch_modle=self.watch_modle_usr_bia) # page 2 self.update_table(protocol, start_addr=0x1158, read_length=128, watch_modle=self.watch_modle_analy_result) self.update_table(protocol, start_addr=0x11d8, read_length=128, watch_modle=self.watch_modle_tst_middle) self.update_table(protocol, start_addr=0x1258, read_length=24, watch_modle=self.watch_modle_com_log) self.update_table(protocol, start_addr=0x1270, read_length=128, watch_modle=self.watch_modle_res_real) except Exception as e: QMessageBox.information(self,"错误",str(e)) def update_table(self,protocol, start_addr,read_length,watch_modle): for i in range(read_length): ret = protocol.read_byte(start_addr + i) if ret[0] == True: for x in ret[1]: watch_modle.setItem(i, 0, QStandardItem("%s + "%(hex(start_addr))+str(hex(i)+"="+hex(start_addr+i)))) watch_modle.setItem(i, 1, QStandardItem(str(hex(x)))) self.progress_bar_current = self.progress_bar_current+1 self.progress_bar.setValue(self.progress_bar_current*100/self.progress_bar_total) QtCore.QCoreApplication.processEvents() else: print("读取失败...") self.progress_bar.close() raise Exception("读取失败,请检查硬件。") def on_click_watch_table_view(self, model_index): pass print("add:",model_index.row(),model_index.column()) # QMessageBox.information(self,"提示","隐藏当前列",QMessageBox.Yes|QMessageBox.No) class Custum_complains(QThread): # const def __init__(self): super(Custum_complains, self).__init__() def run(self): pass try: # 串口工作主流程 """主循环""" while True: pass time.sleep(0.1) except Exception as e: print(str(e)) def mainloop_app(self): try: pass app = QtWidgets.QApplication(sys.argv) window = MyApp() window.show() pass except Exception as e: print(str(e)) finally: sys.exit(app.exec_()) if __name__ == "__main__": try: custum = Custum_complains() custum.start() custum.mainloop_app() except Exception as e: print(str(e)) finally: pass
{"/CSM37F58_APP.py": ["/CSM37F58_APP_ui.py"]}
41,410
cresumerjang/Django_std_v2
refs/heads/master
/accounts/urls.py
from django.conf.urls import url, include from django.conf import settings from django.contrib.auth.views import login, logout from . import views # settings.LOGIN_REDIRECT_URL = '/blog/list' # login redirect 옵션, template옵션 찾기 # logout redirect 옵션, template옵션 찾기 # ?next=/accounts/accountList # urlpatterns = [ # 회원가입 url(r'^signup/$', views.signup, name='signup'), # 로그인 url(r'^login/$', login, name='login', kwargs={'template_name' : 'accounts/login.html',}), # 로그아웃 url(r'^logout/$', logout, name='logout'), # 로그인 성공(리다이렉트처리) url(r'^profile/$', views.loginSuccess, name='login_success'), # 내 계정 url(r'^myAccount/$', views.myAccount, name='my_account'), # 모든 유저 리스트 url(r'^accountList/$', views.accountList, name='account_list'), # 탈퇴 url(r'^deleteAccount/$', views.deleteAccount, name='delect_account'), # 회원정보 수정 url(r'^modifyAccount/$', views.modifyAccount, name='modify_account'), ]
{"/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/admin.py": ["/accounts/models.py"], "/accounts/forms.py": ["/accounts/models.py"]}
41,411
cresumerjang/Django_std_v2
refs/heads/master
/blog/urls.py
from django.conf.urls import url, include from blog import views urlpatterns = [ url(r'^list$', views.list, name='list'), ]
{"/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/admin.py": ["/accounts/models.py"], "/accounts/forms.py": ["/accounts/models.py"]}
41,412
cresumerjang/Django_std_v2
refs/heads/master
/accounts/views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse from django.contrib.auth.views import login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from accounts.forms import SignupForm from accounts.models import Member def signup(request): if request.method == 'POST': signupField = SignupForm(request.POST) if signupField.is_valid(): signupField.save() # next_url = request.GET.get('next', '') # return redirect(settings.LOGIN_URL + '?next=' + next_url) return redirect(reverse('blog:list') + '?complete') else: signupField = SignupForm() return render(request, 'accounts/signup.html', { 'viewModel' : signupField, }) # 장고 로그인 성공시 기본리다이렉트 url패턴인 profile을 재선언한 메소드 def loginSuccess(request): return redirect(reverse('signup')) @login_required def myAccount(request): # login검증 # 로그인 필요시 로그인페이지로 # 로그인 되어있을경우 마이페이지로 return render(request, 'accounts/my_account.html', {}) def accountList(request): viewModel = Member.objects.values() return render(request, 'accounts/acount_list.html', {'viewModel' : viewModel,}) def deleteAccount(request): pass def modifyAccount(request): pass
{"/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/admin.py": ["/accounts/models.py"], "/accounts/forms.py": ["/accounts/models.py"]}
41,413
cresumerjang/Django_std_v2
refs/heads/master
/blog/views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse def list(request): return HttpResponse('blog list')
{"/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/admin.py": ["/accounts/models.py"], "/accounts/forms.py": ["/accounts/models.py"]}
41,414
cresumerjang/Django_std_v2
refs/heads/master
/accounts/admin.py
from django.contrib import admin from accounts.models import Member admin.site.register(Member)
{"/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/admin.py": ["/accounts/models.py"], "/accounts/forms.py": ["/accounts/models.py"]}
41,415
cresumerjang/Django_std_v2
refs/heads/master
/accounts/models.py
from django.db import models from django.conf import settings class Member(models.Model): # OneToOneField는 기존 테이블을 확장해서 다른 테이블을 만들 때 유용 user = models.OneToOneField(settings.AUTH_USER_MODEL) # 모델의 제약조건 매개변수의 name은 실제 테플릿 필드에서 꺼내쓸때 사용가능 # ->즉 queryset에서 참조 가능한 맵핑된 이름 # name = models.CharField(name='이름', max_length=30, blank=False, null=False) # age = models.IntegerField(name='나이', blank=True, null=True) # sex = models.CharField(name='성별', max_length=2, blank=True, null=True) name = models.CharField(max_length=30) age = models.IntegerField() sex = models.CharField(max_length=2, blank=True, null=True)
{"/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/admin.py": ["/accounts/models.py"], "/accounts/forms.py": ["/accounts/models.py"]}
41,416
cresumerjang/Django_std_v2
refs/heads/master
/accounts/forms.py
from django import forms from django.contrib.auth.forms import UserCreationForm from accounts.models import Member class SignupForm(UserCreationForm): name = forms.CharField(max_length=30) age = forms.IntegerField() sex = forms.CharField(max_length=2) def save(self): user = super(SignupForm, self).save(commit=False) user.save(); name = self.cleaned_data.get('name', '') age = self.cleaned_data.get('age', '') sex = self.cleaned_data.get('sex', '') Member.objects.create(user=user, name=name, age=age, sex=sex) # Member.objects.create(member=djangoUser) return user
{"/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py"], "/accounts/admin.py": ["/accounts/models.py"], "/accounts/forms.py": ["/accounts/models.py"]}
41,419
jareena-git/First_Project
refs/heads/master
/Serializer_module.py
from sqlalchemy.inspection import inspect from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declared_attr class Serializer(object): # @declared_attr # def salary_relation(cls): # return relationship("salary",backref="users") def serialize(self): return { c: getattr(self, c) for c in inspect(self).attrs.keys() } @staticmethod def serialize_list(l): return [m.serialize() for m in l] # @declared_attr # def user_relation(self): # return relationship('salary', backref='users')
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,420
jareena-git/First_Project
refs/heads/master
/AddressModule.py
from sqlalchemy import Column,Integer,String from sqlalchemy.orm import relationship from AddressMixinModule import AddressMixin from Serializer_module import Serializer class Address(AddressMixin,Serializer): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) email_address = Column(String, nullable=False) def __init__(self,id,email_address): self.id = id self.email_address = email_address def serialize(self): d=Serializer.serialize(self) return d
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,421
jareena-git/First_Project
refs/heads/master
/nessaceryInfo.py
# user = user(id=1, name="jareena", full_name="jareena shaik") # base.metadata.create_all(engine) # user1 = User(id=5,name="sulthana", full_name="sulthana shaik") # session.add(user1) # session.commit() # qry=session.query(User).filter_by(name="jareena").first() # for name, fullname in session.query(User.name, User.full_name): # print(name,fullname) # qry=session.query(User) # print(qry) # def __init__(self): # # dict_conf_args = {} # # dict_conf_args['username']='postgres' # # dict_conf_args['password'] = 'Saleem!123' # # dict_conf_args['database'] = 'postgres' # # dict_conf_args['port'] = '5432' # # dict_conf_args['host'] = '127.0.0.1' # # db_config_file=basedir+'/db.conf' # # url='postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(user=dict_conf_args['username'],password=dict_conf_args['password'], # # host=dict_conf_args['host'],port=dict_conf_args['port'], # # dbname=dict_conf_args['database'] ) # def create(User): # base.metadata.create_all(self.engin) # # user1=user(name="jareena",full_name="jareena shaik") # session.add(user1) # obj1 = self.session.query("users").all() # print(obj1) # basedir=os.path.dirname(__file__) # return json.dump([dict(r) for r in records],default=alchemyencoder) # for record in records.all(): # record_as_dict=dict({'id' : record.id,'name':record.name,'full_name': record.full_name}) # recordObject=[] # recorddict={} # for result in all_results: # recordObject.extend({'id' : result.id,'name':result.name,'full_name': result.full_name}) # print(recordObject) # recorddict=dict(recordObject) # return jsonify(record_as_dict) # for id,name,fullname in psqlconfigutils.session.query(User.id,User.name,User.full_name).filter_by(full_name='jareena shaik'): # recordObject={'id' : id,'name':name,'full_name': fullname} # return jsonify(recordObject)
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,422
jareena-git/First_Project
refs/heads/master
/project/UserMixinModule.py
from sqlalchemy.inspection import inspect from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import relationship class Serializer(object): # @declared_attr # def User_Addresses(cls): # return relationship("Address", order_by=Address.id, backref="user") def serialize(self): return { c: getattr(self, c) for c in inspect(self).attrs.keys() } @staticmethod def serialize_list(l): return [m.serialize() for m in l]
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,423
jareena-git/First_Project
refs/heads/master
/psqlconfigutils.py
import psycopg2 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from os.path import expanduser import os from userMixin import(UserMixin) from model import(address,user,base) # from Usercls import(user) # from models import(User,base) # from UserModule import(user,base) # url='postgresql://postgres:Saleem!123@127.0.0.1:5432/Employees' # # url = 'postgresql://postgres:Saleem!123@127.0.0.1:5432/Employees' # engine = create_engine(url) # Session = sessionmaker(bind=engine) # session = Session() # Session.configure(bind=engine) # base.metadata.create_all(engine) # url='postgresql://postgres:Saleem!123@127.0.0.1:5432/CollegeDB' engine = create_engine(url) Session = sessionmaker(bind=engine) session = Session() Session.configure(bind=engine) base.metadata.create_all(engine)
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,424
jareena-git/First_Project
refs/heads/master
/dbquerycls.py
from sqlalchemy.ext.declarative import declarative_base from psqlconfigutils import PsUtils from models import User user.address=relationship("Address",backref="user")
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,425
jareena-git/First_Project
refs/heads/master
/project/dbconnect.py
from config import config import psycopg2 def dbConnect(): con = None try: #reading config file params = config() # connect method is used to connect to the database con = psycopg2.connect(**params) except(Exception, psycopg2.DatabaseError) as error: print(error) return con dbConnect()
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,426
jareena-git/First_Project
refs/heads/master
/project/BluePrint21.py
from flask.blueprints import Blueprint from flask import jsonify,request import psqlconfigutils from model import(base,user,address) import json from sqlalchemy import desc from sqlalchemy import and_ addressBluePrint=Blueprint('addressBluePrint21',__name__) # @userBluePrint.route('/',methods=['GET']) # def get(): # records = psqlconfigutils.session.query(User).all() # return json.dumps(User.serialize_list(records)) @addressBluePrint.route('/address',methods=['POST']) def create_record(): id=request.json['id'] email_address=request.json['email_address'] adds=address(id=id,email_address=email_address) psqlconfigutils.session.add(adds) psqlconfigutils.session.commit() return "address added successfully" @addressBluePrint.route('/get_address_records',methods=['GET']) def get_addresses(): all_addresses=psqlconfigutils.session.query(address).all() return json.dumps(address.serialize_list(all_addresses)) @addressBluePrint.route('/userrecord',methods=['POST']) def create_user_record(): id=request.json['id'] name=request.json['name'] full_name=request.json['fullname'] password = request.json['password'] newUser=user(id=id,name=name,fullname=full_name,password=password) psqlconfigutils.session.add(newUser) psqlconfigutils.session.commit() return "user created successfully" @addressBluePrint.route('/getUserRecord/<id>', methods=['GET']) def get_user_record(id): user_record=psqlconfigutils.session.query(user).get(id) # change password of the trived object user_record.password="up_pass" print("Updated password of this user: {0}, password {1}".format(user_record.name,user_record.password)) #add fake user to the users table fake_user=psqlconfigutils.session.add(user(id=11,name="fake",fullname="fakeuser",password="fake_pass")) get_list_users_by_names=psqlconfigutils.session.query(user).filter(user.name.in_(["Sirajunnisa","fake","Jani"])).all() print("The list of users filter by name {0}".format(json.dumps(user.serialize_list(get_list_users_by_names)))) #role back changes which we made before # psqlconfigutils.session.rollback() # retrive record based on name is Saleem get_record_by_name=psqlconfigutils.session.query(user).filter_by(name='Saleem').first() print("Get single user by using name, userid is : {0},username is : {1},userfullname is : {2}".format(get_record_by_name.id,get_record_by_name.name,get_record_by_name.fullname)) #Get instances of the user class in desc order get_all_user_desc=psqlconfigutils.session.query(user).order_by(desc(user.id)) print("Get all instances of the user in desceding order:{0}".format(json.dumps(user.serialize_list(get_all_user_desc)))) get_all_user_asc=psqlconfigutils.session.query(user).order_by(user.id) print("Get all instances of the user in ascending order:{0}".format(json.dumps(user.serialize_list(get_all_user_asc)))) for name,fullname,password in psqlconfigutils.session.query(user.name,user.fullname,user.password): print("All users are {0},{1},{2}".format(name,fullname,password)) for row,lab in psqlconfigutils.session.query(user,user.name.label('user_name')).all(): print("labeld colums{0}:{1}:{2}{3}".format(row.name,row.fullname,row.password,lab.user_name)) return json.dumps(user.serialize(user_record)) @addressBluePrint.route('/getAllUserRecords', methods=['GET']) def get_user_records(): all_users=psqlconfigutils.session.query(user).all() for name,fullname in psqlconfigutils.session.query(user,user.fullname): print(name,fullname) # label the name to the column for name in psqlconfigutils.session.query(user.name.label('nick_name')): print(name.nick_name) for row in psqlconfigutils.session.query(user).order_by(desc(user.id))[0:5]: print(row) # get jani from user instance for fullname, in psqlconfigutils.session.query(user.fullname).\ filter_by(name='Jani'): print(fullname) for fullname, in psqlconfigutils.session.query(user.fullname).\ filter(user.name=='Saleem'): print(fullname,) # retrive record by name for row in psqlconfigutils.session.query(user).\ filter(user.name=="Jani").\ filter(user.fullname=="Janee Shaik"): print("my name is {0}".format(row)) # print(named_tuple) user_expected=psqlconfigutils.session.query(user).\ filter(and_(user.name=='Saleem',user.fullname=='Saleem Syed')).\ order_by(user.id).one() print("one fetch all the rows if single object found it will give otherwise throw error for") return json.dumps(user.serialize_list(all_users)) # full_name=request.json['full_name'] # newUser=User(id=id,name=name,full_name=full_name) # psqlconfigutils.session.add(newUser) # psqlconfigutils.session.commit() # return None
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,427
jareena-git/First_Project
refs/heads/master
/sum.py
# https://realpython.com/how-to-use-numpy-arange/ # def sum_of_two_nums(num1,num2): # try: # num1=int(num1) # num2=int(num2) # total = num1 + num2 # if (total == 20 or # num1 == 20 or # num2 == 20): # print("True") # else: # print("False") # except ValueError: # print("Please enter valid integer value") # # num1=input("Enter First Number") # num2=input("Enter Second Number") # obj=sum_of_two_nums(num1,num2) # # # # # def capitaliz_1_and_4(name): # if len(name) >= 1: # update_str="" # for n in range(len(name)-1): # if (n == 0 or # n == 3): # update_str=update_str + name[n].capitalize() # else: # update_str=update_str + name[n] # # print(update_str) # else: # print("Empty string") # # name=input("Please enter name") # obj=capitaliz_1_and_4(name) # # # # # # def three_of_next_three(lst): # # for l in range(len(lst)-1): # if lst[l] == 3: # if lst[l] == lst[l+1]: # print("True") # else: # print("False") # else: # print("False") # # lst = [ # 2, 22, 3, # 3, 32, 3, # 3] # obj=three_of_next_three(lst) # # # # def repeat_every_char_3(name): # repeat_name = "" # for char in range(len(name)): # repeat_name=repeat_name + (name[char] * 3) # print(repeat_name) # # # name=input("Enter name") # obj=repeat_every_char_3(name) # # # # # # # Calculate Prime number # def calculate_prime(): # num = 2 # count = 0 # i = 0 # if num > 1: # while num <= 100: # for dev in range(2,10): # if ((num % dev) == 0) and (dev != num): # count = count + 1 # break # if count >= 1: # count=0 # else: # print("Prime number{0}".format(num)) # num = num + 1 # obj = calculate_prime() # # # # Python 3 Programming - 55193 # Python 3 Functions and OOPS - 55194 # Numpy - 55936 # Pandas - 55937 # Matplotlib - 56869 # Qualis - 57661 # and not ((num % 1) == 0) # 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, and 97. # def times_table(number): # if number.isdigit(): # number = int(number) # [print("{0} * {1} = {2}".format(num,number,num * number)) for num in range(1,11)] # else: # print("Please enter valid number") # number = input("Please enter number between 1 to 12") # times_table(number) #Generate Pattern using @ # def generate_pattern(): # for i in range(1,5): # for j in range(i): # print("@",end=" ") # print(" ") # for i in range(3,0,-1): # for j in range(i): # print("@",end=" ") # print(" ") # # obj=generate_pattern() # def armstrong(): # num = int(input("Enter a number")) # sum = 0 # temp = num # while temp > 0: # digit = temp % 10 # sum += digit ** 3 # temp //= 10 # # display the result # if num == sum: # print(num,"is an Armstrong number") # else: # print(num,"is not an Armstrong number") # # obj = armstrong() #https://www.youtube.com/watch?v=mmiIjmo-GwQ&feature=emb_rel_end # def my(a,b): # if(a%2==0 & b%2==0): # print(min(a,b)) # else: # print(max(a,b)) # my(1,3) # 6591 # def fun(): # a, b, *c, d = [10, 20, "jareena", 12, 13] # print(a, b, c, d) # fun() # def fun(): # a, *b, (c, *d) = [10, 20, 30, "Python Programmig"] # print(a, b, c, d) # fun() # def fun(): # a, b, *d = (10, 20, "jareena", 12, 13) # print(a, b, d) # fun() # def fun(): # d1={'a':1,'b':3} # d2 = {'c': 1, 'd': 3} # a, b, *c = {'x':10, 'y':20,'z':d1,'i':d2} # print(a, b,c) # fun() # d1={'a':1,'b':3} # d2 = {'c': 1, 'd': 3} # # def fun(a, b, *c, d): # print(a, b, c, d) # # fun(d1,20,d2,40,80,d=70) # d1={'a':1,'b':3} # d2 = {'c': 1, 'd': 3} # # def fun(a, *c, d): # print(a, c, d) # # fun(d1,d=100) # def fun(a, b, c): # print(a, b, c) # # l = [10,39,40] # fun(*l) # def fun(): # st = "Python Programming Language" # a = st[0] # b = st[1] # *c, (*d, e) = st[2:] # print(a, b, c, d, e) # *c, (*d, e) = st[:] # print(a, b, c, d, e) # # fun() # # # list = [1,2,3,4,5,9,9,0,8] # print(list[:3]) # print(list[3:]) # print(list[::2]) # print(list[::3]) # print(list[::3]) # print(list[::4]) # print(list[::-1]) # print(list[:4:2]) # #odd alternatives # print(list[1::2]) # # def fun(): # k = [3,4,5,6,7,8,9] # print(k[::2]) # print(k[:5:2]) # print(k[1::2]) # fun() #range operation to revers the list in decending order # print(list(range(1,100))[::-1]) # # print(i) # # s='jareena' # for i in s: # print(i) # def fun(): # s = "Python Programming Language" # a = s[0] # b = s[2] # # print(list(s[:])) # # a, b, *c = s[0], s[1], s[2:] # print(a) # print(b) # print(c) # why c returning empty list # a, b, *c, d = s[0], s[1], list(s[2:]) # print(a) # print(b) # print(c) # print(d) # why i am getting error here for c even i am passing list # *c = list(s[3:]) ask # its working when we place d # *c, d = list(s[3:]) # print(c) # print(d) # print(list(s[2:])) # print(a) # print(b) # print(c) # print(d) # print(list(s[3:])) # l = list(s[3:len(s)]) # *c , d = list(s[3:])[::-1] # print(c) # print(d) # *c, d, (*e, f) = list(s[3::-1]) # print(c) # print(d) # print(e) # print(f) # # *c,(d, *e) = list(s[::2]) # print(c) # print(d) # print(e) #returning entaire slice as single element in list # print(s[2:]) # print(list(s[2:])) # why c getting list inside list # *c, (d, *e) = list(s[::2]), list(s[1::2]) # print(c) # print(d) # print(e) # *c, d = list(s[3::-1]) # print(c) # print(d) # # false # print(bool(None)) # # false # print(bool("")) # # false # print(bool(0)) # # true # print(bool(1)) # fun() # # def fun(average): # if average >= 90: # print("Distinct") # elif 60 <= average <= 90: # print("Above average") # elif average <= 40 and average >=60: # print("Average") # else: # print("Fail") # # fun(68.0) # def fun(): # s = "Hello Python" # st = "" # for i in range(len(s)-1, 0-1,-1): # st = st + s[i] # print(f"updated string {st}") # print(s[::-1]) # print(s[-1::-1]) # k = [3, 4, 5, 6, 7, 8, 9] # print(k[0::2]) # print(k[0:5:2]) # print(k[1::2]) # print(bool(5)) # tup2 = tuple("Welcome") # for word in tup2: # for w in word: # if "e" in w: # fun() # def fun(): # a = 0 # if a: # print(a) # else: # print (False) # fun() Remove these words ‘is’, ‘in’, ‘to’, ‘no’ from the text list. # def removable(t): # if "is" in t: # t.replace("is","") # print(t) # elif "in" in t: # t.replace("in","") # elif "to" in t: # t.replace("to","") # elif "no" in t: # t.replace("no","") # return t # # # def sliptable(t): # word = t.split() # return word # # # # 164273012 # # def remove_word(): # remove_list = ["is", "in", "to", "no"] # text = ["Life is beautiful", "No need to overthink", "Meditation help in overcoming depression"] # lst=[ word.replace(word,"") if word in remove_list else word for t in text for word in sliptable(t)] # print(lst) # remove_word() # # # def sliptable(t, remove_list): # word = t.split() # update_str = [] # for w in word: # if w in remove_list: # continue # else: # update_str.append(w) # return " ".join(update_str) # # # # def remove_word(): # remove_list = ["is", "in", "to", "no"] # text = ["Life is beautiful","No need to overthink","Meditation help in overcoming depression"] # lst=[sliptable(t, remove_list) for t in text] # print(lst) # # remove_word() # # def sliptable(t, remove_list): # # word = t.split() # # update_str = "" # # for w in word: # # if w in remove_list: # # w.replace(word,"") # # " ".join() # # return word # # # # # # 164273012 # # def remove_word(): # remove_list = ["is", "in", "to", "no"] # text = ["Life is beautiful", "No need to overthink", "Meditation help in overcoming depression"] # lst=[word if word in remove_list else word for t in text for word in sliptable(t, remove_list)] # print(lst) # remove_word() # list of even number # def even_numbers(): # lst =[num for num in range(2, 200) if num % 2 == 0] # print(lst) # even_numbers() # def cuboid(): # x = input("Enter x value") # y = input("Enter y value") # z = input("Enter z value") # n = input("Enter n value") # if x.isdigit() and y.isdigit() and z.isdigit(): # x = int(x) # y = int(y) # z = int(z) # n = int(n) # lst = [[i, j, k] for i in range(x + 1) for j in range(y + 1) for k in range(z + 1) if ((i + j + k) != n)] # print(lst) # else: # print("Please enter valid integer value") # cuboid() # # # import numpy as np # # import numpy as np # n = [[-1, -2, -3, -4], [-2,-4, -6, -8]] # y = np.array(n) # print(y.ndim) # print(y.shape) # print(y.size) # print(y.dtype) # print(y.nbytes) # # import numpy as np # x1 =np.array([[[-1, 1],[-2, 2],[-3, 3],[-4, 4]]]) # # print(x1.ndim) # print(x1.shape) # print(x1.size) # # # # import numpy as np # x2 =np.ones(shape=(3, 2, 2)) # print(x2) # x3 =np.eye(4, 4, k = -1) # print(x3) # # import numpy as np # x = np.random.rand(3, 4, 2) # print(x) # Remove word program # def sliptable(t, remove_list): # word = t.split() # update_str = [] # for w in word: # if w.lower() in remove_list: # continue # else: # update_str.append(w) # return " ".join(update_str) # # # # def remove_word(): # remove_list = ["is", "in", "to", "no"] # text = ["Life is beautiful","No need to overthink","Meditation help in overcoming depression"] # lst=[sliptable(t, remove_list) for t in text] # print(lst) # # remove_word() # Expected Ouput: ['Life beautiful', 'need overthink', 'Meditation help overcoming depression'] # https://www.w3resource.com/python-exercises/numpy/index-array.php # import numpy as np # x = np.arange(20) # y = x.reshape(2, 10) # print(np.hsplit(y)) # import numpy as np # x = np.arange(20) # print(x) # y = x.reshape(2, 10) # np.hsplit(y, 2) import numpy as np p = np.arange(3, 15, 3) p.reshape(2, 2) q = np.arange(15, 33, 3) q.reshape(2, 3) np.hstack((p, q)) import numpy as np y = np.arange(1, 7).reshape(2, 3) z = np.sqrt(y) print(z) print(np.add(z,5))
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,428
jareena-git/First_Project
refs/heads/master
/project/UserModules.py
from sqlalchemy import (Column,ForeignKey,Integer,Table,Sequence,String,MetaData) from sqlalchemy.orm import relationship,mapper from userMixin import(UserMixin) import userMixin from sqlalchemy.ext.declarative import declarative_base from UserMixinModule import Serializer class User(Serializer): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) fullname = Column(String(50)) password = Column(String(12)) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password) def serialize(self): d=Serializer.serialize(self) return d
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,429
jareena-git/First_Project
refs/heads/master
/UserModule.py
from sqlalchemy import (Column,ForeignKey,Integer,Table,Sequence,String,MetaData) from sqlalchemy.orm import relationship,mapper from sqlalchemy.ext.declarative import declarative_base from UserMixinModule import Serializer base=declarative_base() class user(Serializer): __tablename__= "users" id = Column(Integer,primary_key=True,nullable=False) name= Column(String(20),nullable=False) full_name=Column(String(20),nullable=False) def __init__(self,id,name,full_name): self.id=id self.name=name self.full_name
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,430
jareena-git/First_Project
refs/heads/master
/project/app.py
from flask import Flask,request,jsonify # from flask import from flask.blueprints import Blueprint from BlueprintRount import userBluePrint as userBluePrint_20 from BluePrint21 import addressBluePrint as addressBluePrint_21 # from . import pscons import os app=Flask(__name__) # db = SQLAlchemy(app) app.register_blueprint(userBluePrint_20,url_prefix='/2.0') app.register_blueprint(addressBluePrint_21,url_prefix='/2.1') basedir=os.path.abspath(os.path.dirname(__file__)) # DB_URL = 'postgresql+psycopg2://postgres:Saleem!123@127.0.0.1:5432/Employees' # app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning @app.route('/2.1') @app.route('/2.0') def index(): return 'hello jareena' # run server if __name__=="__main__": app.run(debug=True)
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,431
jareena-git/First_Project
refs/heads/master
/project/BlueprintRount.py
from flask.blueprints import Blueprint from flask import jsonify,request import psqlconfigutils from models import(User,base) import json userBluePrint=Blueprint('userBluePrint20',__name__) @userBluePrint.route('/',methods=['GET']) def get(): records = psqlconfigutils.session.query(User).all() return json.dumps(User.serialize_list(records)) @userBluePrint.route('/user',methods=['POST']) def create_record(): id=request.json['id'] name=request.json['name'] full_name=request.json['full_name'] newUser=User(id=id,name=name,full_name=full_name) psqlconfigutils.session.add(newUser) psqlconfigutils.session.commit() return None @userBluePrint.route('/ViewUser') def view_user(): return 'view user' @userBluePrint.route('/PostSalary',methods=['POST']) def create_salary(): id = request.json['id'] name= request.json['name'] emp_salary = request.json['emp_salary'] PositionLevel = request.json['PositionLevel'] Position = request.json['Position'] fk_declrative = request.json['fk_declrative'] new_salary_record=Salary(id=id,name=name,emp_salary=emp_salary,PositionLevel=PositionLevel,Position=Position,fk_declrative=fk_declrative) print(Salary.__table__) psqlconfigutils.session.add(new_salary_record) psqlconfigutils.session.commit() return 'Success' # @userBluePrint.route('/PostSalary',methods=['POST']) # def get_salary(id): # @userBluePrint.route('/StudentTb',methods=['POST']) # def create_student():
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,432
jareena-git/First_Project
refs/heads/master
/project/create_table.py
from dbconnect import dbConnect import psycopg2 con = dbConnect() # def create_tables(emp_list): # try: # if con: # cur = con.cursor() # query = "CREATE TABLE Employee(Id INTEGER PRIMARY KEY,Name VARCHAR(25) NOT NULL,City VARCHAR(20) NOT NULL)" # cur.execute(query) # cur.close() # con.commit() # else: # print("Connection object is None") # except(Exception,psycopg2.DatabaseError) as error: # print("Error while connnecting to database{0}".format(error)) # # if __name__ == "__main__": # create_tables([(1,"Sirajunnisa","Vijayawada"),(2,"Jani","Hyderabad"),(3,"Sona","Gujarath")]) # # def insert_tb_data(param_list): # try: # if con: # #if id is auto increament # select = "insert into Employee VALUES(%s,%s,%s)" # cur = con.cursor() # cur.executemany(select,param_list) # # result = cur.rowcount() # # print(result) # cur.close() # con.commit() # else: # print("Connection object is None") # except(Exception,psycopg2.DatabaseError) as error: # print(error) # finally: # if con is not None: # con.close() # # # if __name__ == "__main__": # insert_tb_data([(4,"Sirajunnisa","Vijayawada"),(8,"Jani","Hyderabad"),(6,"Sona","Gujarath")]) # def insert_tb_data(name, id): # try: # if con: # #if id is auto increament # select = "UPDATE Employee SET Name = %s WHERE Id = %s" # cur = con.cursor() # cur.execute(select,(name,id)) # cur.close() # con.commit() # else: # print("Connection object is None") # except(Exception,psycopg2.DatabaseError) as error: # print(error) # finally: # if con is not None: # con.close() # # # if __name__ == "__main__": # insert_tb_data("Siraj",1) # # 123 "jareena" "vijayawada" # 121 "jareena" "vijayawada" # 122 "joh" "vijaz" # 124 "johna" "Guntur" # 125 "jothi" "Srikakulam" # 126 "jothi" "Srikakulam" # 127 "jothi" "Srikakulam" # 2 "Jani" "Hyderabad" # 3 "Sona" "Gujarath" # 4 "Sirajunnisa" "Vijayawada" # 8 "Jani" "Hyderabad" # 6 "Sona" "Gujarath" # 1 "Siraj" "Vijayawada"
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,433
jareena-git/First_Project
refs/heads/master
/model.py
from sqlalchemy.ext.declarative import declarative_base from userMixin import(UserMixin) from UserModules import User from AddressModule import Address from Serializer_module import Serializer base=declarative_base() class user(base,User): pass class address(base,Address): pass
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,434
jareena-git/First_Project
refs/heads/master
/project/Usercls.py
from sqlalchemy import (Column,ForeignKey,Integer,Table,Sequence,String,MetaData) from sqlalchemy.orm import relationship,mapper from userMixin import(UserMixin) import userMixin from Serializer_module import Serializer # metadata=MetaData() # # usertb=Table("users",metadata,Column("id",Integer,primary_key=True),Column("name",String(20),nullable=False), # Column("full_name",String(20),nullable=False)) #userMixin.UserMixin class user(Serializer): __tablename__= 'users' id = Column(Integer,primary_key=True,nullable=False) name= Column(String(20),nullable=False) full_name=Column(String(20),nullable=False) def __init__(self,id,name,full_name): self.id=id self.name=name self.full_name=full_name def serialize(self): d=Serializer.serialize(self) return d # mapper(users,usertb) # # @property # def serialize(self): # """Return object data in easily serializable format""" # return { # 'id': self.id, # 'name': str(self.name), # # This is an example how to deal with Many2Many relations # 'full_name': str(self.full_name) # } # # @property # def serialize_many2many(self): # """ # Return object's relations in easily serializable format. # NB! Calls many2many's serialize property. # """ # return [item.serialize for item in self.many2many]
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,435
jareena-git/First_Project
refs/heads/master
/random_generator.py
#https://docs.sqlalchemy.org/en/14/orm/extensions/associationproxy.html # import random # # # def incorrect_attempts(): # attempts_remaining = input("how many incorrect attempts do you want?[1-25]") # if attempts_remaining.isdigit(): # attempts_remaining = int(attempts_remaining) # if attempts_remaining >= 25 or attempts_remaining <= 0: # print("Please Enter number between [1-25]") # else: # minimum_word_len(attempts_remaining) # elif attempts_remaining.lower() == "NaN".lower(): # print("NaN is not an integer between 1 and 25") # else: # print("{0}: is not an integer between 1 and 25:". # format(attempts_remaining)) # # # def minimum_word_len(attempts_remaining): # min_word_len = int(input("what minimum word length do you want? [4-16]")) # print("selecting a word...") # print() # read_word_frm_txt(min_word_len, attempts_remaining) # # # def read_word_frm_txt(min_word_len, attempts_remaining): # with open("words.txt", mode='r') as fd: # words_lines = fd.readlines() # for words_line in words_lines: # words_list = words_line.split(" ") # select_word(words_list, min_word_len, attempts_remaining) # # # def select_word(words_list, min_word_len, attempts_remaining): # selected_words_list = [] # for words in range(0, len(words_list)-1): # if len(words_list[words]) >= min_word_len: # selected_words_list.append(words_list[words]) # word = random.choice(selected_words_list) # replace_star(min_word_len, word, attempts_remaining) # # # def replace_star(min_word_len, word, attempts_remaining): # print("word:", end=" ") # for w in range(0, len(word)-1): # print("*", end=" ") # print() # reduce_attempts(attempts_remaining, word) # # # def reduce_attempts(attempts_remaining, word): # flag = 0 # previous_guesses = "" # try: # while (attempts_remaining != 0) and flag == 0: # # attempts_remaining -= 1 # previous = " " # print("Attempts Remaining:{0}".format(attempts_remaining)) # print("Previous Guesses:", previous) # next_letter = input("Choose the next letter:") # attempts_remaining -= 1 # if next_letter.isalpha(): # if len(next_letter) > 1: # print("Enter only Single charecter") # continue # else: # if next_letter in previous_guesses: # attempts_remaining += 1 # print("You have already guessed that letter") # print() # continue # else: # if next_letter in word: # next_letter_replicate = word.count(next_letter) # for letter in range(next_letter_replicate): # previous_guesses += next_letter # previous = next_letter # print("{0} is in the word!".format(next_letter)) # print() # print("word:", end=" ") # for w in word: # if w in previous_guesses: # print(w, end=" ") # if len(word) == len(previous_guesses): # print('Congratulations, You won the game!') # flag = 1 # break # break # break # # else: # print("*", end=" ") # print() # # else: # print("{0} is not in word:".format(next_letter)) # else: # print("Enter only letter") # continue # if attempts_remaining <= 0: # print() # print('You lost! Try again..') # print('The word was {}'.format(word)) # except: # print() # print('Try again.') # exit() # # # if __name__ == '__main__': # print('Starting a game of Hangman....') # incorrect_attempts() # given a 1D ARRAY, negate all elements which are between 3 and 8, in place # # considering a 10*3 matrix, extract rows with unequal values(eg [2,2,3]) # # import numpy as np # def load_nobel_data(): # nobel_daota = # # # # # def fun(a,*d,=0, **b): # print(a,d,b) # for i in d: # print(i) # # # fun(10,20,40,30,b=10,c=20) # first_last_20 = dataset.loc[dataset.last_valid_index] # set_data = dataset.head(20),dataset.tail(20) # set_data = dataset[:20],dataset[-20:] # print(dataset.iloc[0:20,-20:-1],dataset.iloc[-20:-1]) # print(dataset.loc[(dataset.head(20)) , (dataset.tail(20)),:]) # # # # import matplotlib.pyplot as plt # import numpy as np # import pandas as pd # def load_nobel_data(): # dataset = pd.read_csv("Nobel.csv") # # set_data = dataset.head(20), dataset.tail(20) # nobel_1901_2016 = dataset.loc[(dataset['year'] >= 1901) & (dataset['year'] <= 2016),['prize']] # print("{0} Prizes between 1901 and 2016".format(len(nobel_1901_2016))) # prizes_woned_male = dataset.loc[(dataset['sex'] == 'Male')] # print("{0} prizes woned by Male".format(len(prizes_woned_male))) # prizes_woned_female = dataset.loc[(dataset['sex'] == 'Female')] # print("{0} prizes woned by Female".format(len(prizes_woned_female))) # top_10_nationalities = dataset.loc[(dataset['birth_country'] == 'France') | # (dataset['birth_country'] == 'Germany') | # (dataset['birth_country'] == 'Netherlands') | # (dataset['birth_country'] == 'Denmark') | # (dataset['birth_country'] == 'Norway') | # (dataset['birth_country'] == 'Sweden') | # (dataset['birth_country'] == 'Iceland') | # (dataset['birth_country'] == 'Finland') | # (dataset['birth_country'] == 'Italy') | # (dataset['birth_country'] == 'United Kingdom'),['birth_country','prize']] # print("{0} Prizes woned by top 10 country".format(len(top_10_nationalities))) # null_data = dataset.isnull().sum() # print(null_data) # # dataset['born_winner'] = dataset["birth_country"] == "United States of America" # dataset['decade'] = (np.floor(dataset["year"] / 10) * 10).astype(int) # winners = dataset.groupby("decade", as_index=False)["born_winner"].mean() # print(winners) # # # Calculate the percentage of female Nobel Prize winners per decade and visualize the observations using matplotlib.pyplot # dataset['female_nobel_winner'] = dataset["sex"] == "Female" # female_winners = dataset.groupby(["decade"], as_index=False)["female_nobel_winner"].mean() # print(female_winners) # fig = plt.figure(figsize=(20, 10)) # plt.bar(female_winners['decade'],female_winners['female_nobel_winner']) # plt.xlabel('decade', fontsize=10) # plt.ylabel('female_nobel_winner', fontsize=10) # plt.xticks(female_winners['decade'],fontsize=10, rotation=30) # plt.title('female Nobel Prize winners') # plt.show() # # # Find out who was the first woman to win a Nobel Prize from the dataset # first_female = dataset[dataset["sex"] == "Female"] # print(first_female.nsmallest(1, "year")) # # # Find the Nobel Prize winners who have received 2 or more prizes # print(dataset.groupby("full_name").filter(lambda x: len(x) >= 2)) # # # Plot the ages of the Nobel Prize Winners using a scatter Plot # dataset['birth_date'] = pd.to_datetime(dataset["birth_date"]) # dataset['age'] = dataset["year"] - dataset["birth_date"].dt.year # plt.scatter(dataset['age'],dataset.index) # plt.title("Ages of the Nobel Prize Winners") # plt.xlabel("Age") # plt.show() # # '''Find out the oldest winner of a Nobel Prize for the year 2016 # and also the youngest winner of a Nobel Prize for the year 2016''' # oldest_winner = dataset.nlargest(n=1, columns='age') # print("The oldest winner in 2016 is {0}".format(oldest_winner)) # # # youngest_winner = dataset.nsmallest(n=1, columns='age') # print("The youngest_winner in 2016 is /n:{0}".format(youngest_winner)) # # Print/Display the first and last 20 entries in the dataset # set_data = dataset.head(20), dataset.tail(20) # print("{0} first and last 20 rows".format(set_data)) # Print/Display the number of Nobel Prizes handed out between 1901 and 2016 # nobel_1901_2016 = dataset.loc[(dataset['year'] >= 1901) & # (dataset['year'] <= 2016), ['prize']] # print("{0} Prizes between 1901 and 2016".format(len(nobel_1901_2016))) # # Print/Display the number of prizes won by male and female recipients # prizes_woned_male = dataset.loc[(dataset['sex'] == 'Male')] # print("{0} prizes woned by Male".format(len(prizes_woned_male))) # prizes_woned_female = dataset.loc[(dataset['sex'] == 'Female')] # print("{0} prizes woned by Female".format(len(prizes_woned_female))) # # Print/Display the number of prizes won by the top 10 nationalities # top_10_nationalities = dataset.loc[(dataset['birth_country'] == # 'France') | # (dataset['birth_country'] == # 'Germany') | # (dataset['birth_country'] == # 'Netherlands') | # (dataset['birth_country'] == # 'Denmark') | # (dataset['birth_country'] == # 'Norway') | # (dataset['birth_country'] == # 'Sweden') | # (dataset['birth_country'] == # 'Iceland') | # (dataset['birth_country'] == # 'Finland') | # (dataset['birth_country'] == # 'Italy') | # (dataset['birth_country'] == # 'United Kingdom'), # ['birth_country', 'prize']] # print("{0} Prizes woned by top 10 country".format(len(top_10_nationalities))) # # Print/Display how many null values are present in the dataset # null_data = dataset.isnull().sum() # print(null_data) # # Print/Display the percentage of USA born winners per decade # dataset['born_winner'] = dataset["birth_country"] == "United States of America" # dataset['decade'] = (np.floor(dataset["year"] / 10) * 10).astype(int) # winners = dataset.groupby("decade", as_index=False)["born_winner"].mean() # print(winners) # # # Calculate the percentage of female Nobel Prize winners per decade and visualize the observations using matplotlib.pyplot # dataset['female_nobel_winner'] = dataset["sex"] == "Female" # female_winners = dataset.groupby(["decade"], as_index=False) # ["female_nobel_winner"].mean() # # # print(female_winners) # fig = plt.figure(figsize=(20, 10)) # plt.bar(female_winners['decade'], female_winners['female_nobel_winner']) # plt.xlabel('decade', fontsize=10) # plt.ylabel('female_nobel_winner', fontsize=10) # plt.xticks(female_winners['decade'], fontsize=10, rotation=30) # plt.title('female Nobel Prize winners') # plt.show() # # # Find out who was the first woman to win a Nobel Prize from the dataset # first_female = dataset[dataset["sex"] == "Female"] # print(first_female.nsmallest(1, "year")) # # # Find the Nobel Prize winners who have received 2 or more prizes # print(dataset.groupby("full_name").filter(lambda x: len(x) >= 2)) # # # Plot the ages of the Nobel Prize Winners using a scatter Plot # dataset['birth_date'] = pd.to_datetime(dataset["birth_date"]) # dataset['age'] = dataset["year"] - dataset["birth_date"].dt.year # plt.scatter(dataset['age'], dataset.index) # plt.title("Ages of the Nobel Prize Winners") # plt.xlabel("Age") # plt.show() # ''' Find out the oldest winner of a Nobel Prize for the year 2016 # and also the youngest winner of a Nobel Prize for the year 2016''' # oldest_winner = dataset.nlargest(n=1, columns='age') # print("The oldest winner in 2016 is {0}".format(oldest_winner)) # youngest_winner = dataset.nsmallest(n=1, columns='age') # print("The youngest_winner in 2016 is /n:{0}".format(youngest_winner)) # # load_nobel_data() # # given a 1D ARRAY, negate all elements which are between 3 and 8, in place # # considering a 10*3 matrix, extract rows with unequal values(eg [2,2,3]) # # given a 1D ARRAY, negate all elements which are between 3 and 8, in place # import numpy as np # arr = np.arange(11) # m = (arr>3) & (arr<8) # arr[m]*=-1 # print(arr) # # # # considering a 10*3 matrix, extract rows with unequal values(eg [2,2,3]) # import numpy as np # extract = np.random.randint(0, 5, (10,3)) # print(extract) # for i in range(0,10): # if not ((extract[i,0] == extract[i,1]) and (extract[i,0] == extract[i,2])): # print(extract[i]) # print(f'Found directory: {dirpath}') # c=[chr(i) for i in [65, 66, 67]] # print(c) #https://www.brianheinold.net/python/python_book.html python books # https://www.tldp.org/LDP/abs/html/abs-guide.html # https://www3.ntu.edu.sg/home/ehchua/programming/webprogramming/Python1_Basics.html import os import os, sys import datetime from datetime import date, timedelta from datetime import datetime # yesterday = date.today() - timedelta(1) # yesterdaysDate = yesterday.strftime('%Y%m%d') # # yesterdaysFile_myFile = yesterday.strftime('myFile_%Y%m%d.csv') # for dirpath, dirnames, files in os.walk('D:\\TestDir\\', topdown=False): # for file_name in files: # file_name = os.path.splitext(file_name) # file_name = file_name[0] # file_name = datetime.strptime(file_name, '%Y-%m-%d').date() # if yesterdaysDate in file_names: # print("OKAY: {0} is available".format(yesterdaysFile_myFile)) # else: # print("ERROR: {0} does not exist!".format(yesterdaysFile_myFile)) # # print(file_name) # for dir_name in dirnames: # print(dir_name) # for dirpath, dirnames, files in os.walk('D:\\TestDir\\', topdown=False): # for file_name in files: # print(file_name) # for dir_name in dirnames: # print(dir_name) # # # # l = [10,3,9] # inx = 0 # val = 20 # while inx < len(l): # if l[inx] == val: # break # inx+=1 # else: # l.append(val) # print(l) # #wrong # l = [10,3,9] # inx = 0 # val = 9 # while inx < len(l): # if not l[inx] == val: # l.append(val) # else: # break # inx+=1 # class Employee(): # def __init__(self,name,age,salary): # self.name = name # self.age = age # self.salary = salary # def __eq__(self, other): # if self.age == other.age: # return True # else: # return False # def __lt__(self, other): # if self.salary < other.salary: # return True # else: # return False # e1 = Employee("jareena",40,30000) # e2 = Employee("sirajunnisa",20,90000) # print(e1 == e2) # print(e1 < e2) # # e1.salary = -3000 # print(e1.salary) # class Employee(): # def __init__(self, # name, # age, # salary # ): # self._name = name # self._age = age # self._salary = salary # # def get_pro(self): # return self._salary # # def set_pro(self,_salary): # if self._salary <= 0: # raise ValueError("salary should be positive") # else: # self._salary = salary # # def __eq__(self, other): # if self._age == other._age: # return True # else: # return False # # def __lt__(self, other): # if self._salary < other._salary: # return True # else: # return False # # e1 = Employee("jareena",40,30000) # e2 = Employee("sirajunnisa",20,90000) # # # print(e1 == e2) # print(e1 < e2) # e1.set_pro(-30000) # e1.set_pro # class Employee(): # def __init__(self, # name, # age, # salary # ): # self._name = name # self._age = age # self._salary = salary # # @property # def salary(self): # return self._salary # # @salary.setter # def salary(self, salary): # if salary <= 0: # raise ValueError("salary should be positive") # else: # self._salary = salary # # @property # def age(self): # return self._age # # @age.setter # def age(self, age): # if self.age <= 0: # raise ValueError("age should be positive") # else: # self._age = age # # # def __eq__(self, other): # if self.age == other.age: # return True # else: # return False # # def __lt__(self, other): # if self.salary < other.salary: # return True # else: # return False # # e1 = Employee("jareena",40,-30000) # e2 = Employee("sirajunnisa",20,90000) # # # print(e1 == e2) # print(e1 < e2) # # e1.name = "Rizwana" # # e1.salary = -3000 # print(e1 == e2) # print(e1.name) # # class Employee(): # def __init__(self, # name, # age, # salary # ): # self.name = name # self.age = age # self.salary = salary # # @property # def salary(self): # return self.salary # # @salary.setter # def salary(self, salary): # if salary <= 0: # raise ValueError("salary should be positive") # else: # self.salary = salary # # @property # def age(self): # return self.age # # @age.setter # def age(self, age): # if age <= 0: # raise ValueError("age should be positive") # else: # self.age = age # # # def __eq__(self, other): # if self.age == other.age: # return True # else: # return False # # def __lt__(self, other): # if self.salary < other.salary: # return True # else: # return False # # e1 = Employee("jareena",40,-30000) # e2 = Employee("sirajunnisa",20,90000) # # # print(e1 == e2) # print(e1 < e2) # # e1.name = "Rizwana" # # e1.salary = -3000 # print(e1 == e2) # print(e1.name) # # # lst = [1, 2] # lst1 = [1, 2] # print(lst is lst1) # print(lst == lst1) # print("lst address {0}".format(id(lst))) # print("lst1 address {0}".format(id(lst1))) # def fun(a, b): # print(a + b) # # x = 10 # y = 20 # fun(x, y) # def fun(a, b, c): # print(a + b + c) # # x = 10 # y = 20 # fun(x, y, 10) # if we want to make any argument optional by specifying respective parameter as default # after default parameter all arguments are made default # def fun(a, b=10, c = 20): # print(a + b + c) # # x = 1 # y = 2 # fun(x, y, 3) # def fun(a, b = 1, c = 2): # print(a + b + c) # # x = 10 # y = 20 # fun(x) # # def fun(a, b = 1, c = 2): # print("The value a is {0}, b is {1}, c is {2}, total is {3}".format(a, b, c, a + b + c)) # # x = 10 # y = 20 # fun(x,20) # def fun(a, b, c): # print("The value a is {0}, b is {1}, c is {2}, total is {3}".format(a, b, c, a + b + c)) # # # fun(a=20,b=20,c=30) # s, b, c, *d,e = {10,40,78,"python",90} # print("s is{0},b is {1},c is {2},d is {3},e is {4}".format(s,b,c,d,e)) # d1 = {"name":"jareena","id":6} # d2 = {"name":"jareena1","id":9} # d3 = {"email":"jareena@gmail.com","address":"Vijayawada"} # d = [*d1,*d2,*d3] # print("The name count is {0}".format(d.count("name"))) # d1 = {*d1,*d2,*d3} # print(d1) # print(d) # saibabu.o@tcs.com # bhiravprasad.bachu@tcs.com (Bhiravprasad Bachu) # lst = [10, 20, [30,40]] # a, b, (*d, e)= lst # print("a is {0}, b is {1}, d is {2}, e is {3}".format(a, b, d, e)) # def fun(a, b, c, *d): # print("a is {0}, b is {1}, d is {2}".format(a, b, d)) # # lst = "python" # fun(*lst) # https://treyhunner.com/2018/04/keyword-arguments-in-python/ very importent # def fun(a, b, *c, d): #after arbitory argument we should not pass any positional parameter, we will get key only argument error here # print("a is {0}, b is {1}, d is {2}".format(a, b, d)) # # lst = "python" # fun(*lst) # def fun(a, b, *c, d): # print("a is {0}, b is {1}, d is {2}".format(a, b, d)) # # lst = "python" # fun(*lst,d=20) # d is key only argument # # # def outer(): # count = 10 # def innner(): # print("The counter value is {0}".format(count)) # return innner() # d = outer()() # print(d.__code__.co_freevars) # print(d.__closur__) # # # def out(): # x=[1,2,3] # print("before innner{0}".format(hex(id(x)))) # def inner(): # y = x # print("after innner{0}".format(hex(id(y)))) # return inner # o = out()() # def modify_free_val(): # val = 0 # print("outer scope: {0}, memory: {1}".format(val,hex(id(val)))) # def inc_count(): # nonlocal val # print("inner scope before count : {0}, memory: {1}".format(val, hex(id(val)))) # val+=1 # print("inner scope: {0}, memory: {1}".format(val,hex(id(val)))) # return inc_count # # d = modify_free_val() # d() # # # def modify_free_val(): # val = 0 # print("outer scope: {0}, memory: {1}".format(val,hex(id(val)))) # def inc_count(): # nonlocal val # print("inner scope before count : {0}, memory: {1}".format(val, hex(id(val)))) # val+=1 # print("inner scope: {0}, memory: {1}".format(val,hex(id(val)))) # return inc_count # # d = modify_free_val() # d() # # def out(x): # x = 10 # def inner(y): # return x + 1 # return inner # o = out(10) # o(2) 0x7ffecbd37ce0 # def create(): # lst = [] # for n in range(1,4): # lst.append(lambda x, y=n : x + y) # return lst # obj = create() # print(obj[0](10)) # print(obj.__closure__) # print(obj.__code__.co_freevars) # print(obj) # x = [[0,0]] # print(x) # print(id(x)) # print("before con : {0}".format(id(x[0]))) # a = x + x # print(a) # print(id(a)) # print("after con : {0}".format(id(a[1]))) # print(x[0]==a[0]==a[1]) # lst = ['s','a','l'] # str_var = "jar" # up_str = " ".join(list(str_var)+lst) # print(up_str) # lst = [1,2,4] # def do_some(l): # lst.append("jareena") # do_some(lst) # print(lst) # # tup = (1,2,4) # def do_some(l): # print(tup + ("jareena",)) # do_some(tup) # print(tup) # lst = [1,2,4,5,43] # def do_some(l): # l[2:6] = (12,32,9,49,49) # do_some(lst) # print(lst) # tup = (1,2,4,5,43) # def do_some(tup): # print(tup[2:6] + (12,32,9,49,49)) # do_some(tup) # print(tup) # lst = [1,2,4] # def do_some(lst): # print(hex(id(lst))) # print(lst.append(29)) # result = lst.append(29) # print(hex(id(result))) # print(result) # do_some(lst) # print(lst) # l = [1,2,3] # print(l.reverse()) # print(l) # l = [[1,2,3],'c','d'] # def fun(lst): # print(l) # l2 = l.copy() # print(l[0] is l2[0]) # print(l[1] is l2[1]) # print(l2) # fun(l) # # l = ('c','d') # def fun(lst): # print(id(lst)) # lst = lst + ('e',) # print(id(lst)) # fun(l) # # l = ['c','d'] # def fun(lst): # print(id(lst)) # lst = lst + ['e'] # print("after concatination{0}".format(id(lst[0]))) # print(id(lst)) # fun(l) # print("outside {0}".format(id(l[0]))) # t=(10,29) # print("t :{0}".format(id(t))) # t1 = tuple(t) # print("t1 :{0}".format(id(t1))) # print(t1,"\n\n") # t=[10,29] # print("list t :{0}".format(id(t))) # t1 = list(t) # print("list t1 :{0}".format(id(t1))) # print(t[0] is t1[0]) # print(t1) # # t = (10, 30) # print(id(t)) # t2 = t[:] #here if we are creating t2 with entire t slicing then both t and t2 pointing to the same object # print(t[0] is t2[0]) #even elements or objects in containers of t and t2 are also same # print(id(t2)) # def fun(tup): # print(id(tup)) # t2 = tup[1:] #here if we are creating t2 with entire t slicing then both t and t2 pointing to the same object # print(tup[1] is t2[0]) #even elements or objects in containers of t and t2 are also same # print(id(t2)) # # t = (10, 30) # fun(t) # x = "python" # a = x + x # print(a) # # from copy import copy, deepcopy # def fun(a): # def __init__(self, a): # self.a = a # # # x = [1,2] # obj = fun(x) # print(x is obj.a) # cp = copy(obj) # # print(obj.a is cp.a) #Note: #container memory address is different but elements in both containers pointing to same memory address # lst = [[1,2],[3,4]] # emp_lst = [] # emp_lst = [e.copy() for e in lst] # print(emp_lst) # emp_lst[0][0] = 100 # print(id(lst[0][0]),lst) # print(id(emp_lst[0][0]),emp_lst) # print("\n\n\n") # lst = [[[1,1],[2,2]],[[3,3],[4,4]]] # emp_lst = [] # emp_lst = [[i.copy() for i in e] for e in lst] # print(emp_lst) # emp_lst[0][0][0] = 100 # print(id(lst[0][0][0]),lst) # print(id(emp_lst[0][0][0]),emp_lst) # print(emp_lst) # print(lst) # # print() # print("second list in lst elements: {0}".format(id(lst[0][0]))) # print("second list in emp_lst elements: {0}".format(id(emp_lst[0][0]))) # print() # # print("second list in lst elements: {0}".format(id(lst[0][0][0]))) # print("second list in emp_lst elements: {0}".format(id(emp_lst[0][0][0]))) # print("\n") # # def fun(l): # index = 0 # lst_new = [] # while True: # try: # element = l.__getitem__(index) # except IndexError: # break # lst_new.append(element**2) # index+=1 # print(lst_new) # # lst = [1,3,2,5,4] # obj = fun(lst) # class custom_sequence(): # def __init__(self, n): # self.n = n # def __getitem__(self, item): # if item < 0 or item >= self.n: # raise IndexError # else: # print(f"This is donder getitem function") # # # obj = custom_sequence(10) # # obj.__getitem__(10) # for i in obj: # print(i) # lst = [1,2,3] # lst[0:1] = {4,5,6,7} # print(lst) # class Custom_Sqnce: # def __init__(self,n): # self.n = n # # def __getitem__(self, item , lst, item1): # result = lst[item1] # print(result) # # if item < 0 or item >= self.n: # # raise IndexError # # else: # # result = lst.__getitem__(item1) # # print(result) # l = [12, 36, 37] # obj = Custom_Sqnce(10) # obj.__getitem__(9, l, 2) # lst = [12,34,23] # lst.extend((12,43,65)) # print(lst) # import numbers # class sam: # def __init__(self, x, y): # if isinstance(x, numbers.Real) and isinstance(y, numbers.Real): # self.pt = (x, y) # else: # raise TypeError # def __str__(self): # self.__repr__() # def __repr__(self): # f'sam(x = {self.pt[0]}, y = {self.pt[1]}))' # # # obj = sam(12, 78) # a,b = obj # # a = 'a' # b = 'b' # print(a < b) # dic = {'a':120,'b':130, 'c':12} # print(sorted(dic)) # print(sorted(dic,key=lambda k:dic[k])) # dic = ["jare", "mehna", "yauna"] # def lenght(s): # return len(s) # print(sorted(dic,key=lenght)) # https://tcsglobal.udemy.com/course/the-complete-python-postgresql-developer-course/learn/lecture/4707546#overview # # def lenght(s,s1): # return len(s), len(s1) # # emp = [] # upper = "" # lst = ["jare", "ma", "yauna"] # def sort_func(l,emp_lst): # for element in l: # for ele2 in range(1, len(l)): # if len(element) > len(l[ele2]): # upper+=element # else: # emp_lst.append(ele2) # print(emp_lst) # # sort_func(lst,emp) # from statistics import mean # def fun(*args): # return mean(args) # # lst = list(map(int,input("enter number").split())) # result = fun(*lst) # print("%.6f"%result) # print(result) # # nter number98 98 09 78 43 # 65.20 # reverse # save classes with area method # a=10 # b =20 # a, b = b, a # print("a is {0} and b is {1}".format(a,b)) # https://www.codegrepper.com/code-examples/r/python+practice+questions # # class Car(): # def __init__(self,max_speed,units): # self.max_speed = max_speed # self.units = units # def __str__(self): # if self.max_speed == 94: # return "Car with maximum spead of {} and the units is {}".format(self.max_speed,self.units) # else: # '''if we does not return something in function then function return NONE''' # return "Car with maximum spead of {} and the units is {}".format(self.max_speed,self.units) # # obj = Car(94,"mph") # print(obj.__str__()) # # # # # # from statistics import mean # def fun(*args): # return mean(args) # # lst = list(map(int, input("Enter list of numbers").split())) # result = fun(*lst) # print("%.2f"%result) #elements in both container pointing to the same memory address # but the elements are immutable so we cant make changes on i # lst = [(1,2),(3,4)] # emp_lst = [] # emp_lst = [e for e in lst] # print(emp_lst) # # emp_lst[0][0] = 100 # print(id(lst[0][0]),lst) # print(id(emp_lst[0][0]),emp_lst) #To avoid making changes on one container elements will effect on another container elements # lst = [[1,2],[3,4]] # emp_lst = [] # emp_lst = [e.copy() for e in lst] # print(emp_lst) # # print(id(lst[0][0]),lst) # # print(id(emp_lst[0][0]),emp_lst) # emp_lst[0][0] = 100 # # print(id(lst[0][0]),lst) # print(id(emp_lst[0][0]),emp_lst) # print(emp_lst) # from copy import copy, deepcopy # lst = [1,2,3] # emp_lst = [] # emp_lst = copy(lst) # print(lst) # print(emp_lst) # print(id(lst[0]) is id(emp_lst[0])) # print(id(lst[1]) is id(emp_lst[1])) # # print("check elements memory addresss: {0}".format(id(lst[0]) is id(emp_lst[0]))) # print(id(lst) is id(emp_lst)) # print(id(lst)) # print(id(emp_lst))
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,436
jareena-git/First_Project
refs/heads/master
/userMixin.py
from sqlalchemy import (Column,ForeignKey,Integer,Table,Sequence,String) class UserMixin(object): id = Column(Integer,primary_key=True) name = Column(String(25),nullable=False) def get_id(self): return id def get_name(self): return name
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,437
jareena-git/First_Project
refs/heads/master
/project/Salary_module.py
# from sqlalchemy import Column,Integer,Float,ForeignKey,Text # from sqlalchemy.orm import relationship # from salary_fk_Mixin import FkMixin # from Serializer_module import Serializer # class salary(FkMixin,Serializer): # __tablename__='salaries' # id = Column(Integer,primary_key=True) # emp_salary=Column(Float,nullable=False) # PositionLevel=Column(Text,nullable=False) # Position = Column(Text, nullable=False) # # user_id=Column(Integer, ForeignKey('users.id')) # # # def __init__(self,id,emp_salary,PositionLevel,Position): # self.id=id # self.emp_salary=emp_salary # self.PositionLevel=PositionLevel # self.Position=Position # # def serialize(self): # d = Serializer.serialize(self) # return d # #
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,438
jareena-git/First_Project
refs/heads/master
/AddressMixinModule.py
from sqlalchemy import ForeignKey,Column,Integer from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declared_attr class AddressMixin(object): @declared_attr def user_id(cls): return Column(Integer, ForeignKey('users.id')) @declared_attr def user(cls): relationship("User", back_populates="addresses")
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,439
jareena-git/First_Project
refs/heads/master
/models.py
from sqlalchemy.ext.declarative import declarative_base from userMixin import(UserMixin) from Usercls import user # from examplesmodel import example_model # from Salary_module import salary base=declarative_base(cls=UserMixin) class User(base,user): pass # class ExampleModel(base,example_model): # pass # # class Salary(base,salary): # pass
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,440
jareena-git/First_Project
refs/heads/master
/project/salary_fk_Mixin.py
# from sqlalchemy.ext.declarative import declared_attr # from sqlalchemy import Column,Integer,ForeignKey # from sqlalchemy.orm import relationship # # class FkMixin(object): # @declared_attr # def user_id(cls): # return Column(Integer,ForeignKey('users.id')) # @declared_attr # def relation_to(cls): # # return relationship("User", backref="salaries",primaryjoin="User.id == Post.user_id")
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,441
jareena-git/First_Project
refs/heads/master
/Bhargave_Game.py
# Python Program to illustrate # Hangman Game import random from collections import Counter someWords = '''apple banana''' someWords = someWords.split(' ') # randomly choose a secret word from our "someWords" LIST. word = random.choice(someWords) if __name__ == '__main__': print('Guess the word! HINT: word is a name of a fruit') for i in word: # For printing the empty spaces for letters of the word print(" " and " ") print() playing = True # list for storing the letters guessed by the player letterGuessed = '' chances = len(word) + 2 correct = 0 flag = 0 try: while (chances != 0) and flag == 0: # flag is updated when the word is correctly guessed print() chances -= 1 try: guess = str(input('Enter a letter to guess: ')) except: print('Enter only a letter!') continue # Validation of the guess if not guess.isalpha(): print('Enter only a LETTER') continue elif len(guess) > 1: print('Enter only a SINGLE letter') continue elif guess in letterGuessed: print('You have already guessed that letter') continue # If letter is guessed correctly if guess in word: k = word.count(guess) # k stores the number of times the guessed letter occurs in the word for _ in range(k): letterGuessed += guess # The guess letter is added as many times as it occurs '''banana mango strawberrye orange grape pineapple apricot lemon coconut cherry papaya berry peach lychee muskmelon''' # Print the word for char in word: if char in letterGuessed and (Counter(letterGuessed) != Counter(word)): print(char, end=' ') correct += 1 # If user has guessed all the letters elif (Counter(letterGuessed) == Counter(word)): # Once the correct word is guessed fully, # the game ends, even if chances remain print("The word is: ", end=' ') print(word) flag = 1 print('Congratulations, You won!') break # To break out of the for loop break # To break out of the while loop else: print('_', end=' ') # If user has used all of his chances if chances <= 0 and (Counter(letterGuessed) != Counter(word)): print() print('You lost! Try again..') print('The word was {}'.format(word)) except KeyboardInterrupt: print() print('Bye! Try again.') exit() import random from collections import Counter def incorrect_attempts(): attempts_remaining = input("how many incorrect attempts do you want? [1-25]") if attempts_remaining.isdigit(): attempts_remaining = int(attempts_remaining) if attempts_remaining >= 25 or attempts_remaining <= 0: print("Please Enter number between [1-25]") else: minimum_word_len(attempts_remaining) elif attempts_remaining.lower() == "NaN".lower(): print("NaN is not an integer between 1 and 25") else: print("{0}: is not an integer between 1 and 25:".format(attempts_remaining)) def minimum_word_len(attempts_remaining): min_word_len = int(input("what minimum word length do you want? [4-16]")) print("selecting a word...") read_word_frm_txt(min_word_len,attempts_remaining) def read_word_frm_txt(min_word_len,attempts_remaining): with open("words.txt",mode='r') as fd: words_lines = fd.readlines() for words_line in words_lines: words_list = words_line.split(" ") select_word(words_list,min_word_len,attempts_remaining) def select_word(words_list,min_word_len,attempts_remaining): selected_words_list = [] for words in range(0, len(words_list)-1): if len(words_list[words]) >= min_word_len: selected_words_list.append(words_list[words]) word = random.choice(selected_words_list) replace_star(min_word_len,word,attempts_remaining) def replace_star(min_word_len,word,attempts_remaining): print("word:",end=" ") for w in range(0, len(word)-1): print("*",end=" ") print() reduce_attempts(attempts_remaining,word) def reduce_attempts(attempts_remaining,word): flag = 0 previous_guesses = "" try: while (attempts_remaining != 0) and flag == 0: # attempts_remaining -= 1 previous = " " print() print("Attempts Remaining:{0}".format(attempts_remaining)) print("Previous Guesses:",previous) next_letter = input("Choose the next letter:") attempts_remaining -= 1 if next_letter.isalpha(): if len(next_letter) > 1: print("Enter only Single charecter") continue else: if next_letter in previous_guesses: attempts_remaining+=1 print("You have already guessed that letter") continue else: if next_letter in word: next_letter_replicate = word.count(next_letter) for letter in range(next_letter_replicate): previous_guesses+=next_letter previous = next_letter print("{0} is in the word!".format(next_letter)) print("word:",end=" ") for w in word: if w in previous_guesses: print(w,end=" ") if len(word) == len(previous_guesses): print('Congratulations, You won the game!') break break break else: print("*",end=" ") else: print("{0} is not in word:".format(next_letter)) else: print("Enter only letter") #watermelone continue except KeyboardInterrupt: print() print('Try again.') exit() if __name__ == '__main__': print('Starting a game of Hangman....') incorrect_attempts() import random def incorrect_attempts(): attempts_remaining = input("how many incorrect attempts do you want? [1-25]") if attempts_remaining.isdigit(): attempts_remaining = int(attempts_remaining) if attempts_remaining >= 25 or attempts_remaining <= 0: print("Please Enter number between [1-25]") else: minimum_word_len(attempts_remaining) elif attempts_remaining.lower() == "NaN".lower(): print("NaN is not an integer between 1 and 25") else: print("{0}: is not an integer between 1 and 25:".format(attempts_remaining)) def minimum_word_len(attempts_remaining): min_word_len = int(input("what minimum word length do you want? [4-16]")) print("selecting a word...") read_word_frm_txt(min_word_len,attempts_remaining) def read_word_frm_txt(min_word_len,attempts_remaining): with open("words.txt",mode='r') as fd: words_lines = fd.readlines() for words_line in words_lines: words_list = words_line.split(" ") select_word(words_list,min_word_len,attempts_remaining) def select_word(words_list,min_word_len,attempts_remaining): selected_words_list = [] for words in range(0, len(words_list)-1): if len(words_list[words]) >= min_word_len: selected_words_list.append(words_list[words]) word = random.choice(selected_words_list) replace_star(min_word_len,word,attempts_remaining) def replace_star(min_word_len,word,attempts_remaining): print("word:",end=" ") for w in range(0, len(word)-1): print("*",end=" ") print() reduce_attempts(attempts_remaining,word) def reduce_attempts(attempts_remaining,word): flag = 0 previous_guesses = "" try: while (attempts_remaining != 0) and flag == 0: # attempts_remaining -= 1 previous = " " print() print("Attempts Remaining:{0}".format(attempts_remaining)) print("Previous Guesses:",previous) next_letter = input("Choose the next letter:") attempts_remaining -= 1 if next_letter.isalpha(): if len(next_letter) > 1: print("Enter only Single charecter") continue else: if next_letter in previous_guesses: attempts_remaining+=1 print("You have already guessed that letter") continue else: if next_letter in word: next_letter_replicate = word.count(next_letter) for letter in range(next_letter_replicate): previous_guesses+=next_letter previous = next_letter print("{0} is in the word!".format(next_letter)) print("word:",end=" ") for w in word: if w in previous_guesses: print(w,end=" ") if len(word) == len(previous_guesses): print('Congratulations, You won the game!') flag = 1 break break break else: print("*",end=" ") else: print("{0} is not in word:".format(next_letter)) else: print("Enter only letter") #watermelone continue if attempts_remaining <= 0: print() print('You lost! Try again..') print('The word was {}'.format(word)) except: print() print('Try again.') exit() if __name__ == '__main__': print('Starting a game of Hangman....') incorrect_attempts()
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,442
jareena-git/First_Project
refs/heads/master
/project/config.py
# from configparser import ConfigParser # def config(filename = "database.ini", session = 'postgresql'): # db = {} # parser = ConfigParser() # parser.read(filename) # if parser.has_section(session): # params = parser.items(session) # parser returns list of tuples # for param in params: # iterate list of tuples and get each tuple one by one # db[param[0]] = param[1] # store into dictionary # else: # raise Exception("session not found{0}{1}".format(filename,session)) # # # return db # # # config()
{"/AddressModule.py": ["/AddressMixinModule.py", "/Serializer_module.py"], "/psqlconfigutils.py": ["/userMixin.py", "/model.py"], "/dbquerycls.py": ["/psqlconfigutils.py", "/models.py"], "/project/BluePrint21.py": ["/psqlconfigutils.py", "/model.py"], "/project/UserModules.py": ["/userMixin.py"], "/project/BlueprintRount.py": ["/psqlconfigutils.py", "/models.py"], "/model.py": ["/userMixin.py", "/AddressModule.py", "/Serializer_module.py"], "/project/Usercls.py": ["/userMixin.py", "/Serializer_module.py"], "/models.py": ["/userMixin.py"]}
41,446
jackyluo-learning/SocketIODemo
refs/heads/master
/utils.py
def resultVo(data, status): dict = {} dict["data"] = data dict["status"] = status return dict def statusVo(message, status): dict = {} dict["message"] = message dict["status"] = status return dict def args_verification(*args): for each in args: if each is None: return False return True
{"/app.py": ["/utils.py"]}
41,447
jackyluo-learning/SocketIODemo
refs/heads/master
/app.py
from flask import Flask, render_template, request from flask_socketio import SocketIO, emit, join_room, leave_room, send from utils import args_verification, statusVo, resultVo app = Flask(__name__) app.config['SECRET_KEY'] = 'iems5722' socketio = SocketIO(app) @app.route("/api/a4/broadcast_room", methods=["GET", "POST"]) def broadcast_room(): message = request.get_json(force=True) if args_verification(message): print(message) socketio.emit('room_message', {'message': message}, room=str(message['chatroom_id']), broadcast=True) return statusVo(message="Broadcast successfully.", status="OK") else: return statusVo(message="Broadcast failed.", status="ERROR") @app.route("/send_file", methods=["GET", "POST"]) def send_file(): message = request.get_json(force=True) if args_verification(message): print(message) socketio.emit('file_message', {'file': message}, room=str(message['chatroom_id']), broadcast=True) return statusVo(message="Send file successfully.", status="OK") else: return statusVo(message="Send file failed.", status="ERROR") @socketio.on('my event') def my_event_handler(data): emit('my event', data, broadcast=True) @socketio.on('join') def on_join(data): print(data) room = data['chatroom_id'] join_room(room) print("someone enter: ", room) emit('status', {'status': 'in', 'room': room}) @socketio.on('leave') def on_leave(data): room = data['chatroom_id'] leave_room(room) print("someone left: ", room) emit('status', {'status': 'out', 'room': room}) @socketio.on('text') def update_handler(json): emit('update', {'text': json['text']}, broadcast=True) @socketio.on('connect') def connect(): print('connected') if __name__ == '__main__': socketio.run(app, host='0.0.0.0', port=8001, debug=True)
{"/app.py": ["/utils.py"]}
41,463
dipee/notification_app
refs/heads/master
/home/models.py
from django.db import models from channels.layers import get_channel_layer from asgiref.sync import async_to_sync import json from django.contrib.auth.models import User class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) notification = models.TextField(max_length=100) is_seen = models.BooleanField(default=False) def save(self, *args, **kwargs): print("notification Saved") channel_layer = get_channel_layer() notification_objs = Notification.objects.filter(is_seen=False).count() data = {'count': notification_objs, 'current_notification': self.notification} async_to_sync(channel_layer.group_send)( 'test_consumer_group', { 'type': 'send_notification', 'value': json.dumps(data) } ) super(Notification, self).save(*args, **kwargs)
{"/home/consumers.py": ["/home/models.py"]}
41,464
dipee/notification_app
refs/heads/master
/home/consumers.py
from channels.generic.websocket import WebsocketConsumer, AsyncJsonWebsocketConsumer from asgiref.sync import async_to_sync import json from django.core import serializers from .models import Notification class TestConsumer(WebsocketConsumer): def connect(self): # print(self.scope['user']) # print(self.scope["headers"]) # headers = dict(self.scope["headers"]) # print(headers[b'bearer']) # if b'bearer' in self.scope["headers"]: # print(b'bearer'.decode('UTF-8')) self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" data = list(Notification.objects.all()) notification = serializers.serialize('json', data) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() self.send(text_data=json.dumps({'status': notification, })) # self.send(text_data=json.dumps({'status': 'connected from django channels'})) # return super().connect() def receive(self, text_data): print(text_data) return super().receive(text_data=text_data) def disconnect(self, code): print("Disconnected") return super().disconnect(code) def send_notification(self, event): data = event.get('value') self.send(text_data=json.dumps({'payload': data})) class AsyncTestConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = "async_test_consumer" self.room_group_name = "async_test_consumer_group" await (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) await self.accept() await self.send(text_data=json.dumps({'status': 'connected from async django channels'})) # return super().connect() async def receive(self, text_data): print(text_data) await self.send(text_data=json.dumps("we got you")) async def disconnect(self, code): await print("disconnected") async def send_notification(self, event): data = event.get('value') await self.send(text_data=json.dumps({'payload': data}))
{"/home/consumers.py": ["/home/models.py"]}
41,465
dipee/notification_app
refs/heads/master
/home/views.py
import re import channels from django.shortcuts import render from django.http import HttpResponse from django.template import loader import time from asgiref.sync import async_to_sync import json from channels.layers import get_channel_layer # Create your views here. def index(request): template = loader.get_template('index.html') context = {} return HttpResponse(template.render(context)) async def home(request): channel_layer = get_channel_layer() for i in range(1, 10): data = "hello from Home" await(channel_layer.group_send)( 'async_test_consumer_group', { 'type': 'send_notification', 'value': json.dumps(data) } ) time.sleep(1) return render(request, 'home.html')
{"/home/consumers.py": ["/home/models.py"]}
41,472
Vaishnavi476/final-Year-project
refs/heads/master
/app/migrations/0008_auto_20210624_0107.py
# Generated by Django 3.1.7 on 2021-06-23 19:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0007_product_purchasemodel'), ] operations = [ migrations.AddField( model_name='servicerequest', name='age', field=models.CharField(choices=[('Teenager', '21 to 32'), ('elder', '33 to 44')], default='', max_length=30), ), migrations.AddField( model_name='servicerequest', name='gender', field=models.CharField(choices=[('M', 'Male'), ('F', 'Female')], default='', max_length=6), ), migrations.AddField( model_name='servicerequest', name='request_for', field=models.TextField(default=''), ), migrations.AlterField( model_name='servicerequest', name='service_is_complete', field=models.BooleanField(default='True'), ), ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,473
Vaishnavi476/final-Year-project
refs/heads/master
/app/admin.py
from django.contrib import admin from .models import Profile,Equipment,EquipmentRental,Human_Resource,Purchase,ServiceRequest,Feedback,Contact from app.models import Product # Register your models here. admin.site.register(Profile) admin.site.register(Equipment) admin.site.register(EquipmentRental) admin.site.register(Human_Resource) admin.site.register(Purchase) admin.site.register(ServiceRequest) admin.site.register(Feedback) admin.site.register(Product) admin.site.register(Contact)
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,474
Vaishnavi476/final-Year-project
refs/heads/master
/app/migrations/0013_auto_20210624_1314.py
# Generated by Django 3.1.7 on 2021-06-24 07:44 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0012_auto_20210624_1302'), ] operations = [ migrations.RenameField( model_name='equipment', old_name='image_1', new_name='image', ), ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,475
Vaishnavi476/final-Year-project
refs/heads/master
/app/migrations/0004_human_resource_pic.py
# Generated by Django 3.1.7 on 2021-06-08 08:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0003_human_resource_phone'), ] operations = [ migrations.AddField( model_name='human_resource', name='pic', field=models.ImageField(default='hr.png', upload_to='hr'), ), ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,476
Vaishnavi476/final-Year-project
refs/heads/master
/app/migrations/0011_auto_20210624_0150.py
# Generated by Django 3.1.7 on 2021-06-23 20:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0010_auto_20210624_0148'), ] operations = [ migrations.AlterField( model_name='servicerequest', name='durations', field=models.CharField(choices=[('1Day', '1'), ('2Day', '2'), ('3Day', '3'), ('4Day', '4'), ('5Day', '5'), ('6Day', '6'), ('7Day', '7'), ('8Day', '8'), ('9Day', '9'), ('10Day', '10')], max_length=100), ), ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,477
Vaishnavi476/final-Year-project
refs/heads/master
/app/migrations/0007_product_purchasemodel.py
# Generated by Django 3.1.7 on 2021-06-18 07:59 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('app', '0006_profile_address'), ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('image', models.ImageField(upload_to='products/')), ('price', models.FloatField()), ], options={ 'verbose_name': 'Product', 'verbose_name_plural': 'Products', }, ), migrations.CreateModel( name='PurchaseModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=30)), ('qty', models.IntegerField(verbose_name='Quantity')), ('total_amt', models.IntegerField(verbose_name='total amount')), ('buyer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Purchase', 'verbose_name_plural': 'Purchases', }, ), ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,478
Vaishnavi476/final-Year-project
refs/heads/master
/app/forms.py
from app.models import Feedback from django import forms from django.db.models import fields from .models import Profile from django.forms.fields import IntegerField from .models import PurchaseModel, Purchase, ServiceRequest class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('Full_Name', 'gender', 'mobile', 'pic','address') class PurchaseForm(forms.ModelForm): class Meta: model = PurchaseModel fields = ('name','qty','total_amt') # widgets = { # 'qty':forms.HiddenInput(), # } class PurchaseModel(forms.ModelForm): class Meta: model = Purchase fields = ('user','equipment','price') # widgets = { # 'qty':forms.HiddenInput(), # # } class ServiceRequestForm(forms.ModelForm): class Meta: model = ServiceRequest fields = ('durations', 'gender', 'age', 'request_for') class FeedbackForm(forms.ModelForm): """Form definition for Feedback.""" class Meta: """Meta definition for Feedbackform.""" model = Feedback fields = ('name','email','phone','message')
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,479
Vaishnavi476/final-Year-project
refs/heads/master
/app/migrations/0012_auto_20210624_1302.py
# Generated by Django 3.1.7 on 2021-06-24 07:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0011_auto_20210624_0150'), ] operations = [ migrations.AlterField( model_name='servicerequest', name='durations', field=models.CharField(choices=[('1', '1-Day'), ('2', '2-Day'), ('3', '3-Day'), ('4', '4-Day'), ('5', '5-Day'), ('6', '6-Day'), ('7', '7-Day'), ('8', '8-Day'), ('9', '9-Day'), ('10', '10-Day')], max_length=100), ), migrations.AlterField( model_name='servicerequest', name='hr', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='hr_person', to='app.human_resource'), ), ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,480
Vaishnavi476/final-Year-project
refs/heads/master
/userauth/urls.py
from django.urls import path,include from.views import dashboard_view,register_user urlpatterns = [ path('', dashboard_view, name='dashboard'), path('register/',register_user, name='register'), path('oauth/',include('social_django.urls')) ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,481
Vaishnavi476/final-Year-project
refs/heads/master
/userauth/models.py
from django.db.models.fields import CharField, TextField # Create your models here.
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,482
Vaishnavi476/final-Year-project
refs/heads/master
/app/views.py
from app.forms import FeedbackForm from app.forms import ProfileForm, ServiceRequestForm from typing import ContextManager from django.shortcuts import render, redirect from .models import Human_Resource, Profile, Purchase, ServiceRequest, Contact, EquipmentRental from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.http.response import JsonResponse from app.forms import PurchaseForm from django.shortcuts import get_object_or_404, redirect, render from django.contrib import messages from .models import Equipment from cart.cart import Cart from django.contrib.auth.decorators import login_required from django.conf import settings from django.views.decorators.csrf import csrf_exempt import stripe # Create your views here. def homeview(request): ctx ={'title':'welcome'} return render(request,'index.html',context= ctx) def welcomeview(request): return render(request,'welcome.html') def ordering(request): return render(request,'ordering.html') def view_hr(request): hr = Human_Resource.objects.all() context = {'hr':hr} return render(request,'hr/view.html',context) def detail_hr(request,pk): hr= Human_Resource.objects.get(pk=pk) context = {'hr':hr} return render(request,'hr/detail.html',context) def index(request): return render(request, 'index.html') def purchase(request): equipments = Equipment.objects.all() context = {'equipments':equipments} return render(request,'purchase/purchase.html',context) def feedback(request): form = FeedbackForm() if request.method=='POST': form = FeedbackForm(request.POST) if form.is_valid(): form.save() messages.success(request,'your feedback is sent to admin') return redirect("feedback") ctx={'title':'feedback','form':form} return render(request,'feedback.html',ctx) def show_products(request): products = Equipment.objects.all() ctx = {'products':products} return render(request,'store/product_view.html',ctx) def show_single_product(request,pk): product = get_object_or_404(Equipment,pk=pk) ctx = {'product':product} return render(request,'store/product_detail.html',ctx) @login_required def cart_add(request, id): cart = Cart(request) product = Equipment.objects.get(id=id) cart.add(product=product) return redirect("product_all") @login_required def item_clear(request, id): cart = Cart(request) product = Equipment.objects.get(id=id) cart.remove(product) return redirect("cart_detail") @login_required def item_increment(request, id): cart = Cart(request) product = Equipment.objects.get(id=id) cart.add(product=product) return redirect("cart_detail") @login_required def item_decrement(request, id): cart = Cart(request) product = Equipment.objects.get(id=id) cart.decrement(product=product) return redirect("cart_detail") @login_required def cart_clear(request): cart = Cart(request) cart.clear() return redirect("cart_detail") @login_required def cart_detail(request): return render(request, 'cart/cart_detail.html') @csrf_exempt def stripe_config(request): if request.method == "GET": stripe_config = {'publicKey':settings.STRIPE_PUBLISHABLE_KEY} return JsonResponse(stripe_config,safe=False) @csrf_exempt def create_checkout_session(request): if request.method =='GET': domain_url = "http://127.0.0.1:8000/" stripe.api_key = settings.STRIPE_SECRET_KEY try: # product data checkout_session = stripe.checkout.Session.create( success_url = domain_url+'success?session_id={CHECKOUT_SESSION_ID}', cancel_url = domain_url+'cancelled/', payment_method_types = ['card'], mode = 'payment', line_items = [{ 'name':'ABCD', 'quantity':5, 'currency':'inr', 'amount':200020, # Rs 2000 and 20 paise }] ) cart = Cart(request) cart.clear() return JsonResponse({'sessionId':checkout_session['id']}) except Exception as e: return JsonResponse({'error':str(e)}) def notify_success(request): messages.success(request,f"Your payment is complete.") return redirect('home') def notify_cancelled(request): messages.error(request,f"Your payment is cancelled.") return redirect('cart_detail') def rent(request): equipment = EquipmentRental.objects.all() ctx = {"eqiupmentrental":equipment} return render(request,'rent_services/rent.html',ctx) def equipment(request): equipment = Equipment.objects.all() ctx = {"eqiupments":equipment} return render(request,'equipment.html',ctx) def service_request(request,pk): hr=Human_Resource.objects.filter(pk=pk)[0] form = ServiceRequestForm() if request.method=='POST': form = ServiceRequestForm(request.POST) if form.is_valid(): fd = form.save(commit = False) fd.hr=hr fd.for_user = request.user fd.save() messages.success(request,"Service request has been sent") return redirect('home') context = {'form':form} return render(request,'hr/request_form.html', context) @login_required def user_profileview(request): users = Profile.objects.filter(user__pk=request.user.pk) if len(users)==1: context= {'userprofile':users} else: context = {'userprofile': None} return render(request, 'user_profile.html',context) def edit_profileview(request, pk): try: udata = Profile.objects.filter(pk=pk) if len(udata)==1: form = ProfileForm(instance=udata[0]) else: form = ProfileForm() if request.method=='POST': if len(udata)==1: form = ProfileForm(request.POST, request.FILES, instance=udata[0]) else: form = ProfileForm(request.POST, request.FILES) if form.is_valid(): fd=form.save(commit=False) fd.user=request.user fd.email=request.user.email fd.save() return redirect('up') context = {"pform":form} return render(request, 'edit_profile.html', context) except Exception as e: print('some error occurred',e) return redirect('up') def contact(request): error="" if request.method=='POST': n = request.POST['cname'] pn = request.POST['cphone'] e = request.POST['cemail'] p = request.POST['cpurpose'] try: Contact.objects.create(con_name=n,con_mobile=pn,con_email=e,con_purpose=p) messages.success(request,"Feedback has been save") error = "no" return render(request,'contact.html',d) except: error="yes" d = {'error':error} return render(request,'contact.html',d)
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,483
Vaishnavi476/final-Year-project
refs/heads/master
/app/urls.py
from django.urls import path from .views import homeview, welcomeview, ordering, view_hr, detail_hr, purchase, rent, equipment, user_profileview from .views import service_request, edit_profileview, contact from .views import index from django.views.generic import TemplateView from app import views urlpatterns = [ path('', homeview, name='home'), path('welcome/',welcomeview, name='welcome'), path('ordering/',ordering,name='ordering'), path('hr/view',view_hr, name='view_hr'), path('hr/detail/<int:pk>',detail_hr, name='detail_hr'), path('purchase/',purchase, name='pc'), path('rent/',rent, name='rs'), path('service/request/<int:pk>',service_request, name='sr'), path('equipment/',equipment, name='eq'), path('userprofile/', user_profileview, name='up'), path('editprofile/<int:pk>', edit_profileview, name='editpro'), path('',index,name='home'), path('cart/add/<int:id>/', views.cart_add, name='cart_add'), path('cart/item_clear/<int:id>/', views.item_clear, name='item_clear'), path('cart/item_increment/<int:id>/', views.item_increment, name='item_increment'), path('cart/item_decrement/<int:id>/', views.item_decrement, name='item_decrement'), path('cart/cart_clear/', views.cart_clear, name='cart_clear'), path('cart/cart-detail/',views.cart_detail,name='cart_detail'), path('product/detail/<int:pk>',views.show_single_product,name='product_detail'), path('product/all',views.show_products,name='product_all'), path('contact/',contact, name='contact'), path("config/",views.stripe_config, name='config'), path('create-checkout-session/',views.create_checkout_session,name='create_checkout_session'), path('success/',views.notify_success,name='success'), path('cancelled/',views.notify_cancelled,name='cancelled'), path('feedback/',views.feedback, name='feedback'), path("about/",TemplateView.as_view(template_name='about.html'),name='about') ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,484
Vaishnavi476/final-Year-project
refs/heads/master
/app/models.py
from django.db import models from django.db.models.deletion import CASCADE from django.contrib.auth.models import User from django.db.models.fields import CharField, DateTimeField, IntegerField, TextField, EmailField from django.db.models.fields.related import ForeignKey from django.core.validators import RegexValidator from django.utils.translation import gettext_lazy as _ from django.core.validators import RegexValidator,MinValueValidator,MaxValueValidator #Create your models here. duration_option = ( ('1','1-Day'), ('2','2-Day'), ('3','3-Day'), ('4','4-Day'), ('5','5-Day'), ('6','6-Day'), ('7','7-Day'), ('8','8-Day'), ('9','9-Day'), ('10','10-Day') ) gender_option = ( ('M', 'Male'), ('F', 'Female') ) age_option = ( ('Teenager', '21 to 32'), ('elder', '33 to 44'), ) phone_regex = RegexValidator(regex=r'^\d{10,15}$', message="Phone number must be entered in the format: '999999999'. Up to 15 digits allowed.") class Profile(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) Full_Name = models.CharField(max_length=30, default='') gender = models.CharField(max_length=6,choices=gender_option, default='') email = models.CharField(max_length=30) mobile = models.CharField(max_length=15,validators=[phone_regex], default='') pic = models.ImageField(upload_to='users') update_on = models.DateTimeField(auto_now=True) address = models.TextField(default="not available") class Equipment(models.Model): name = models.CharField(max_length=50) catagory = models.CharField(max_length=50, default='Machine_one') price = models.IntegerField(null=True) rent_price = models.IntegerField(null=True) image = models.ImageField(upload_to='equipments') image_2 = models.ImageField(upload_to='equipments') Description = models.TextField() availability = models.BooleanField() date_added = models.DateTimeField(auto_now=True) def __str__(self): return self.name class EquipmentRental(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) equipment = models.ForeignKey(Equipment,on_delete=models.CASCADE) rent_price = models.IntegerField(null=True) rent_date = models.DateTimeField(auto_now=True) expiry_date = models.DateTimeField(auto_now=True) Delivery_Address = models.TextField(max_length=500) is_date_expired = models.BooleanField(default=True) Fine = models.IntegerField(null=True) def __str__(self): return f"{self.rent_price}" class Human_Resource(models.Model): name = models.CharField(max_length=32) age = models.IntegerField(null=True) address = models.TextField(max_length=500) helpertype = models.CharField(max_length=32) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(max_length=15,validators=[phone_regex]) email = models.EmailField(blank=True) date_added = models.DateTimeField(auto_now=True) is_available = models.BooleanField() pic= models.ImageField(upload_to="hr",default="hr.png") def __str__(self): return self.name class Purchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) equipment = models.ForeignKey(Equipment,on_delete=models.DO_NOTHING) price = models.IntegerField(null=True) is_payment_complete = models.BooleanField() date_purchase = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username class PurchaseModel(models.Model): """Model definition for PurchaseModel.""" buyer = models.ForeignKey(User,on_delete=CASCADE) name = CharField(max_length=30) qty = IntegerField(verbose_name="Quantity") total_amt = IntegerField(verbose_name="total amount") class Meta: """Meta definition for PurchaseModel.""" verbose_name = 'Purchase' verbose_name_plural = 'Purchases' def __str__(self): return f"{self.name} {self.qty}" class Product(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to='products/') price = models.FloatField() class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' def __str__(self): return self.name class ServiceRequest(models.Model): hr = models.ForeignKey(Human_Resource, on_delete=models.CASCADE,related_name='hr_person') for_user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='client') durations = models.CharField(max_length=100, choices=duration_option) gender = models.CharField(max_length=6, choices=gender_option,default='') age = models.CharField(max_length=30, choices=age_option,default='') request_for = models.TextField(default='') service_is_complete = models.BooleanField(default='True') class Feedback(models.Model): name = CharField(max_length=50) email = EmailField(max_length=50) phone_regex = RegexValidator(regex=r'^\+?1?\d{10,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], max_length=15, blank=True) # validators should be a list message = TextField() dated = DateTimeField(auto_now=True) class Meta: verbose_name = 'Feedback' verbose_name_plural = 'Feedbacks' def __str__(self): return f'feedback from {self.name}' class Contact(models.Model): con_name = models.CharField(max_length=20,null=True) con_mobile = models.CharField(max_length=30, null=True) con_email = models.CharField(max_length=10,null=True) con_purpose = models.CharField(max_length=15,null=True) message = models.TextField(default='')
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,485
Vaishnavi476/final-Year-project
refs/heads/master
/app/migrations/0010_auto_20210624_0148.py
# Generated by Django 3.1.7 on 2021-06-23 20:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0009_contact'), ] operations = [ migrations.AlterField( model_name='servicerequest', name='durations', field=models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=100), ), ]
{"/app/admin.py": ["/app/models.py"], "/app/forms.py": ["/app/models.py"], "/app/views.py": ["/app/forms.py", "/app/models.py"], "/app/urls.py": ["/app/views.py"]}
41,487
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/payments/migrations/0007_auto_20210529_0341.py
# Generated by Django 3.2 on 2021-05-28 22:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('myapp', '0014_auto_20210527_1517'), ('payments', '0006_alter_transaction_made_by'), ] operations = [ migrations.AlterField( model_name='transaction', name='amount', field=models.IntegerField(), ), migrations.AlterField( model_name='transaction', name='made_by', field=models.ForeignKey(default=3, on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='myapp.user'), preserve_default=False, ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,488
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/models.py
from django.db import models from django.utils import timezone # Create your models here. class User(models.Model): Username = models.CharField(max_length=256, unique=True, null=True, blank=True) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) contact = models.CharField(max_length=100) email = models.CharField(max_length=100,unique=True) address = models.TextField() password = models.CharField(max_length=100) Gender = models.CharField(max_length=6) age = models.CharField(max_length=20) Profile_pic = models.FileField(upload_to = 'profile_pic' , default='pic.jpg') def __str__(self): return self.Username class Pass(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE ,null=True, blank=True) Destination = models.CharField(max_length=256, null=True, blank=True) From = models.CharField(max_length=256,null=True, blank=True) To = models.CharField(max_length=256, null=True, blank=True) Distance = models.CharField(max_length=256, null=True, blank=True) Duration = models.CharField(max_length=30, null=True, blank=True) Issue_date = models.CharField(max_length=30,null=True, blank=True) End_date = models.CharField(max_length=30,null=True, blank=True) Pass_amount = models.CharField(max_length=10) def __str__(self): return self.User.Username
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,489
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/payments/migrations/0004_transaction_pay_status.py
# Generated by Django 3.2 on 2021-05-28 20:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payments', '0003_alter_transaction_made_by'), ] operations = [ migrations.AddField( model_name='transaction', name='pay_status', field=models.CharField(blank=True, max_length=256, null=True), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,490
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0015_alter_pass_end_date.py
# Generated by Django 3.2 on 2021-05-30 10:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0014_auto_20210527_1517'), ] operations = [ migrations.AlterField( model_name='pass', name='End_date', field=models.DateField(), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,491
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/payments/migrations/0003_alter_transaction_made_by.py
# Generated by Django 3.2 on 2021-05-27 15:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('myapp', '0014_auto_20210527_1517'), ('payments', '0002_alter_transaction_id'), ] operations = [ migrations.AlterField( model_name='transaction', name='made_by', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='myapp.user'), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,492
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0016_alter_pass_issue_date.py
# Generated by Django 3.2 on 2021-06-02 06:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0015_alter_pass_end_date'), ] operations = [ migrations.AlterField( model_name='pass', name='Issue_date', field=models.DateField(), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,493
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/payments/migrations/0008_alter_transaction_amount.py
# Generated by Django 3.2 on 2021-05-28 22:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payments', '0007_auto_20210529_0341'), ] operations = [ migrations.AlterField( model_name='transaction', name='amount', field=models.IntegerField(null=True), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,494
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0013_alter_user_age.py
# Generated by Django 3.2 on 2021-05-24 05:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0012_user_verify'), ] operations = [ migrations.AlterField( model_name='user', name='age', field=models.CharField(max_length=20), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,495
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0012_user_verify.py
# Generated by Django 3.2 on 2021-05-24 04:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0011_remove_user_verify'), ] operations = [ migrations.AddField( model_name='user', name='verify', field=models.BooleanField(default=False), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,496
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0011_remove_user_verify.py
# Generated by Django 3.2 on 2021-05-24 04:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('myapp', '0010_alter_user_gender'), ] operations = [ migrations.RemoveField( model_name='user', name='verify', ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,497
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0004_alter_user_profile_pic.py
# Generated by Django 3.2 on 2021-04-21 11:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0003_alter_user_profile_pic'), ] operations = [ migrations.AlterField( model_name='user', name='Profile_pic', field=models.FileField(default='pic.jpg', upload_to='profile_pic'), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,498
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0002_passid_pass_charges.py
# Generated by Django 3.2 on 2021-04-20 10:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.AddField( model_name='passid', name='pass_charges', field=models.IntegerField(default=50), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,499
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0003_alter_user_profile_pic.py
# Generated by Django 3.2 on 2021-04-21 11:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_passid_pass_charges'), ] operations = [ migrations.AlterField( model_name='user', name='Profile_pic', field=models.ImageField(default='pic.jpg', upload_to='profile_pic'), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,500
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0010_alter_user_gender.py
# Generated by Django 3.2 on 2021-05-21 10:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0009_alter_user_gender'), ] operations = [ migrations.AlterField( model_name='user', name='Gender', field=models.CharField(max_length=6), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,501
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/payments/models.py
from django.db import models from myapp.models import Pass, User class Transaction(models.Model): made_by = models.ForeignKey(User, related_name='transactions', on_delete=models.CASCADE) pass_id = models.ForeignKey(Pass, related_name='Pass', on_delete=models.CASCADE,null=True, blank=True) made_on = models.DateTimeField(auto_now_add=True) amount = models.IntegerField(null=True) order_id = models.CharField(unique=True, max_length=100, null=True, blank=True) pay_status = models.CharField(max_length=256, null=True, blank=True,) checksum = models.CharField(max_length=100, null=True, blank=True) def save(self, *args, **kwargs): if self.order_id is None and self.made_on and self.id: self.order_id = self.made_on.strftime('PAY2ME%Y%m%dODR') + str(self.id) return super().save(*args, **kwargs) def __str__(self): return self.made_by.Username
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,502
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/views.py
from django.shortcuts import render from django.urls.base import reverse_lazy from .models import * from django.conf import settings from django.core.mail import send_mail import random from django.http import HttpResponse , HttpResponseRedirect from django.urls import reverse from django.template.loader import get_template from xhtml2pdf import pisa from django.views.generic import UpdateView, DeleteView from django.core.exceptions import * from payments.models import * import datetime def render_pdf_view(request , *args, **kwargs): email = request.session['email'] user = User.objects.get(email = email) data = Pass.objects.get(User = user) template_path = 'pass_pdf.html' context = {'data': data,'user':user} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename="{data.User.fname} {data.User.lname} Bus Pass.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response # def pass_pdf(request): # email = request.session['email'] # user = User.objects.get(email = email) # data = Pass.objects.get(User = user) # return render(request,'pass_pdf.html',{"data":data,"user":user}) ########################################################################################### def index(request): try: if request.session['email']: return render(request, "index.html") except: return HttpResponseRedirect(reverse('login')) def login(request): try: if request.session['email']: return HttpResponseRedirect(reverse('index')) except: if request.POST: email = request.POST['email'] password = request.POST['password'] try: user = User.objects.get(email = email) if user: if user.password == password: request.session['email'] = email return HttpResponseRedirect(reverse('index')) else: msg = "Password Does Not Match." return render(request,"login.html",{'msg':msg}) else: msg = "Email Does Not Match." return render(request,"login.html",{'msg':msg}) except Exception as e: msg = "Improper Credentials." return render(request, 'login.html', {'msg':msg}) else: return render(request, "login.html") def signup(request): if request.method == 'POST': global temp temp = { 'Username' : request.POST['Username'], 'fname': request.POST['fname'], 'lname': request.POST['lname'], 'contact': request.POST['contact'], 'email': request.POST['email'], 'address': request.POST['address'], 'password': request.POST['password'], 'c_password': request.POST['c_password'], 'gender': request.POST['Gender'], 'age': request.POST['age'] } otp = random.randint(1000,9999) subject = 'OTP for Sign up' message = f'Hello!! Your OTP for Successfully Signing up is {otp}' email_from = settings.EMAIL_HOST_USER recipient_list = [request.POST['email'], ] send_mail( subject, message, email_from, recipient_list ) return render(request,'otp_verify.html',{'otp':otp,'temp':temp}) else: return render(request,"signup.html") def otp_verify(request): if request.method =="POST": if request.POST['otp'] == request.POST['otp1']: if temp['password'] == temp['c_password']: ur = User.objects.create( Username = temp['Username'], fname = temp['fname'], lname = temp['lname'], contact = temp['contact'], email = temp['email'], address = temp['address'], password = temp['password'], Gender = temp['gender'], age = temp['age'] ) ur.save() return render(request,'login.html') else: return HttpResponse("<h1>Password and Confirm Password Does not match</h1>") else: return HttpResponse("<h1>OTP Not varify</h1>") else: return render(request,"otp_verify.html") def forgot_password(request): if request.method == "POST": email = request.POST['email'] otp = random.randint(111111,999999) try: mail = User.objects.get(email=email) send_mail( 'OTP for New Password', f'Here is your otp for new password: {otp}', settings.EMAIL_HOST_USER, [mail.email], fail_silently=False, ) return render(request,'otp_password.html',{'otp':otp,'mail':mail}) except: return HttpResponse("User Not Valid") else: return render(request,"forgot_password.html") def otp_password(request): if request.method == 'POST': otp = request.POST['otp'] otp1 = request.POST['otp1'] email = request.POST['email'] if otp == otp1: return render(request, 'user_password.html',{'email':email}) else: return HttpResponse("<h1>OTP Verification Failed </h1>") else: return render(request, "login.html") def user_password(request): if request.method == 'POST': email = request.POST['email'] try: email = User.objects.get(email = email) if request.POST['password'] == request.POST['c_password']: if email: email.password = request.POST['password'] email.save() send_mail( 'Password Change', f'Your password changed successfully..', settings.EMAIL_HOST_USER, [email.email], fail_silently=False, ) return HttpResponseRedirect(reverse('login')) else: return HttpResponse("<h1>Password and Confirm Password Does not match...</h1>") except: return HttpResponse("User Not Valid") else: return render(request,"login.html") def logout(request): try: del request.session['email'] return HttpResponseRedirect(reverse('login')) except KeyError: return render(request,'login.html') def header(request): return render(request,'header.html') def pass_form(request): try: if request.method == "POST": email = request.session['email'] user = User.objects.get(email = email) generate = Pass.objects.create( User = user, Destination = request.POST['Destination'], From = request.POST['From'], To =request.POST['To'], Distance = request.POST['Distance'], Duration =request.POST['Duration'], Issue_date = request.POST['Issue_date'], End_date = request.POST['End_date'], Pass_amount = request.POST['Pass_amount'] ) generate.save() return HttpResponseRedirect(reverse('user_pass')) else: return render(request,'pass_form.html') except: return HttpResponse("<h1>User already Exiets..</h1>") def user_pass(request): try: email = request.session['email'] user = User.objects.get(email = email) data = Pass.objects.get(User = user) status = Transaction.objects.filter(pass_id = data).latest('pay_status') date = datetime.date.today().strftime("%d/%m/%Y") return render(request,'user_pass.html',{"data":data,"user":user,"status":status}) except: try: email = request.session['email'] user = User.objects.get(email = email) data = Pass.objects.get(User = user) return render(request,'user_pass.html',{"data":data,"user":user}) except: email = request.session['email'] user = User.objects.get(email = email) return render(request,'user_pass.html',{"user":user}) class UserUpdateView(UpdateView): model = User fields= "__all__" template_name = "user_update.html" success_url = reverse_lazy('logout') def form_valid(self,form): if self.request.session['email'] == self.request.POST['email']: return super().form_valid(form) and HttpResponseRedirect(reverse('user_pass')) else: return super().form_valid(form) class UserDeleteView(DeleteView): model = User success_url = reverse_lazy('logout') template_name = "user_delete.html" class PassUpdateView(UpdateView): model = Pass fields= ['Destination','From','To','Distance','Duration','Issue_date','End_date','Pass_amount'] template_name = "pass_update.html" success_url = reverse_lazy('pay') class PassDeleteView(DeleteView): model = Pass success_url = reverse_lazy('user_pass') template_name = "pass_delete.html"
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,503
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/urls.py
from django.urls import path from . import views urlpatterns = [ path('',views.index, name='index'), path('login/', views.login, name = 'login'), path('signup/', views.signup, name = 'signup'), path('forgot_password/',views.forgot_password,name='forgot_password'), path('otp_verify/',views.otp_verify,name='otp_verify'), path('logout/',views.logout,name='logout'), path('pass_form/',views.pass_form,name='pass_form'), path("user_pass/",views.user_pass,name="user_pass"), path('otp_password/',views.otp_password,name='otp_password'), path('user_password/',views.user_password,name = 'user_password'), path("render_pdf_view/",views.render_pdf_view,name="render_pdf_view"), path("user_update/<int:pk>",views.UserUpdateView.as_view(),name ="user_update"), path("pass_update/<int:pk>",views.PassUpdateView.as_view(),name="pass_update"), path("pass_delete/<int:pk>",views.PassDeleteView.as_view(),name = "pass_delete"), path("user_delete/<int:pk>",views.UserDeleteView.as_view(),name = "user_delete"), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,504
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0014_auto_20210527_1517.py
# Generated by Django 3.2 on 2021-05-27 09:47 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('myapp', '0013_alter_user_age'), ] operations = [ migrations.RemoveField( model_name='passid', name='u_id', ), migrations.RenameField( model_name='pass', old_name='pass_issue_date', new_name='End_date', ), migrations.RenameField( model_name='pass', old_name='pass_amount', new_name='Pass_amount', ), migrations.RemoveField( model_name='pass', name='destination', ), migrations.RemoveField( model_name='pass', name='p_id', ), migrations.RemoveField( model_name='pass', name='pass_duration', ), migrations.RemoveField( model_name='pass', name='qr_image', ), migrations.RemoveField( model_name='pass', name='source', ), migrations.RemoveField( model_name='user', name='is_handicaped', ), migrations.RemoveField( model_name='user', name='verify', ), migrations.AddField( model_name='pass', name='Destination', field=models.CharField(blank=True, max_length=256, null=True), ), migrations.AddField( model_name='pass', name='Distance', field=models.CharField(blank=True, max_length=256, null=True), ), migrations.AddField( model_name='pass', name='Duration', field=models.CharField(blank=True, max_length=30, null=True), ), migrations.AddField( model_name='pass', name='From', field=models.CharField(blank=True, max_length=256, null=True), ), migrations.AddField( model_name='pass', name='Issue_date', field=models.DateField(default=django.utils.timezone.now), ), migrations.AddField( model_name='pass', name='To', field=models.CharField(blank=True, max_length=256, null=True), ), migrations.AddField( model_name='pass', name='User', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='myapp.user'), ), migrations.AddField( model_name='user', name='Username', field=models.CharField(blank=True, max_length=256, null=True, unique=True), ), migrations.DeleteModel( name='LocationDestination', ), migrations.DeleteModel( name='LocationSource', ), migrations.DeleteModel( name='PassId', ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,505
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0001_initial.py
# Generated by Django 3.2 on 2021-04-20 10:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='LocationDestination', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('location_id', models.CharField(max_length=20)), ('location_name', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='LocationSource', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('location_id', models.CharField(max_length=20)), ('location_name', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fname', models.CharField(max_length=100)), ('lname', models.CharField(max_length=100)), ('contact', models.CharField(max_length=100)), ('email', models.CharField(max_length=100, unique=True)), ('address', models.TextField()), ('password', models.CharField(max_length=100)), ('Gender', models.CharField(max_length=6)), ('age', models.IntegerField()), ('Profile_pic', models.FileField(default='pic.jpg', upload_to='profile_pic')), ('is_handicaped', models.BooleanField(default=False)), ('pass_valid', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='PassId', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pass_u_id', models.CharField(max_length=30)), ('issue_date', models.DateField(auto_now_add=True)), ('expiry_date', models.CharField(max_length=30)), ('u_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp.user')), ], ), migrations.CreateModel( name='Pass', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pass_amount', models.CharField(max_length=10)), ('pass_issue_date', models.DateField(auto_now_add=True)), ('pass_duration', models.CharField(max_length=30)), ('qr_image', models.FileField(default=None, upload_to='AllPass')), ('destination', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp.locationdestination')), ('p_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp.passid')), ('source', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp.locationsource')), ], ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,506
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/payments/migrations/0008_transaction_pass_id.py
# Generated by Django 3.2 on 2021-05-30 21:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('myapp', '0015_alter_pass_end_date'), ('payments', '0007_alter_transaction_made_by'), ] operations = [ migrations.AddField( model_name='transaction', name='pass_id', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Pass', to='myapp.pass'), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,507
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/myapp/migrations/0008_user_profile_pic.py
# Generated by Django 3.2 on 2021-04-22 05:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0007_user_verify'), ] operations = [ migrations.AddField( model_name='user', name='Profile_pic', field=models.FileField(default='pic.jpg', upload_to='profile_pic'), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,508
AnniKalani123/E-Bus-Pass-System
refs/heads/master
/payments/migrations/0007_alter_transaction_made_by.py
# Generated by Django 3.2 on 2021-05-30 20:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('myapp', '0015_alter_pass_end_date'), ('payments', '0006_alter_transaction_made_by'), ] operations = [ migrations.AlterField( model_name='transaction', name='made_by', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='myapp.user'), ), ]
{"/payments/models.py": ["/myapp/models.py"], "/myapp/views.py": ["/myapp/models.py", "/payments/models.py"]}
41,511
bidlocoder1422/DataBase1.0
refs/heads/master
/mainWindow.py
# -*- coding: utf-8 -*- # добавить скан договора к компании %3 отдел% # mainWindow : Проверить на Ошибки парсинг xls file %отдел прикладного тестирования% from PyQt5 import QtCore, QtGui, QtWidgets import sys,xlrd from companyAbout import Ui_aboutCompanyWindow from addcompany import addCompanyDialog from bilCard import Ui_bilCard from editCompany import editCompanyDialog def getCompanyList(): companiesListFile=xlrd.open_workbook('data/companiesBase.xlsx') workSheet=companiesListFile.sheet_by_index(0) companies=[] for i in range(1,workSheet.nrows): companies.append(str(workSheet.cell(i,1).value)) return companies def getNumberOfBills(): BillsListFile = xlrd.open_workbook('data/billsBase.xlsx') workSheet = BillsListFile.sheet_by_index(0) bills = [] for i in range(1, workSheet.nrows): bills.append('Счет '+str(int(workSheet.cell(i,0 ).value))+' , ' +workSheet.cell(i,1).value) return bills def getBillData(rowNumber): BillsListFile = xlrd.open_workbook('data/billsBase.xlsx') workSheet = BillsListFile.sheet_by_index(0) billData=[] for i in range(0,7): billData.append(str(workSheet.cell(rowNumber, i).value)) print(type(workSheet.cell(rowNumber, i).value)) return billData class Ui_MainWindow(QtWidgets.QWidget): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(640, 290) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.downloadXLSBtn = QtWidgets.QPushButton(self.centralwidget) self.downloadXLSBtn.setGeometry(QtCore.QRect(320, 10, 261, 23)) self.downloadXLSBtn.setObjectName("downloadXLSBtn") self.uploadXLSBtn = QtWidgets.QPushButton(self.centralwidget) self.uploadXLSBtn.setGeometry(QtCore.QRect(10, 10, 301, 23)) self.uploadXLSBtn.setObjectName("uploadXLSBtn") self.companyListCB = QtWidgets.QComboBox(self.centralwidget) self.companyListCB.setGeometry(QtCore.QRect(10, 50, 291, 22)) self.companyListCB.setObjectName("companyListCB") self.openCompanyCardBtn = QtWidgets.QPushButton(self.centralwidget) self.openCompanyCardBtn.setGeometry(QtCore.QRect(320, 50, 161, 23)) self.openCompanyCardBtn.setObjectName("openCompoanyCardBtn") self.openBilCarBtn = QtWidgets.QPushButton(self.centralwidget) self.openBilCarBtn.setGeometry(QtCore.QRect(320, 90, 161, 23)) self.openBilCarBtn.setObjectName("openBilCarBtn") self.bilChooseCb = QtWidgets.QComboBox(self.centralwidget) self.bilChooseCb.setGeometry(QtCore.QRect(10, 90, 291, 22)) self.bilChooseCb.setObjectName("bilChooseCb") self.addCompanyBtn = QtWidgets.QPushButton(self.centralwidget) self.addCompanyBtn.setGeometry(QtCore.QRect(10, 130, 591, 23)) self.addCompanyBtn.setObjectName("addCompanyBtn") self.editCompanyBtn = QtWidgets.QPushButton(self.centralwidget) self.editCompanyBtn.setGeometry(QtCore.QRect(480, 50, 151, 23)) self.editCompanyBtn.setObjectName("editCompanyBtn") self.UploadExitBtn = QtWidgets.QPushButton(self.centralwidget) self.UploadExitBtn.setGeometry(QtCore.QRect(400, 210, 221, 23)) self.UploadExitBtn.setObjectName("UploadExitBtn") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 21)) self.menubar.setObjectName("menubar") self.menu = QtWidgets.QMenu(self.menubar) self.menu.setObjectName("menu") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionAbout = QtWidgets.QAction(MainWindow) self.actionAbout.setObjectName("actionAbout") self.actionExit = QtWidgets.QAction(MainWindow) self.actionExit.setObjectName("actionExit") self.menu.addAction(self.actionAbout) self.menu.addAction(self.actionExit) self.menubar.addAction(self.menu.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Учет")) self.downloadXLSBtn.setText(_translate("MainWindow", "Загрузить изменения на компьютер")) self.uploadXLSBtn.setText(_translate("MainWindow", "Выгрузить изменения на сервер")) self.openCompanyCardBtn.setText(_translate("MainWindow", "Открыть карточку")) self.openBilCarBtn.setText(_translate("MainWindow", "Открыть краткую сводку")) self.addCompanyBtn.setText(_translate("MainWindow", "Добавить компанию")) self.editCompanyBtn.setText(_translate("MainWindow", "Изменить данные")) self.UploadExitBtn.setText(_translate("MainWindow", "Выгрузить и выйти")) self.menu.setTitle(_translate("MainWindow", "Меню")) self.actionAbout.setText(_translate("MainWindow", "About")) self.actionExit.setText(_translate("MainWindow", "Exit")) self.openCompanyCardBtn.clicked.connect(self.getCompanyCard) self.addCompanyBtn.clicked.connect(self.addCompany) self.openBilCarBtn.clicked.connect(self.getBilCard) self.UploadExitBtn.clicked.connect(self.exitUpdateBtnClicked) self.editCompanyBtn.clicked.connect(self.editCompanyBtnClicked) self.uploadXLSBtn.clicked.connect(self.empttyBtnClicked) self.downloadXLSBtn.clicked.connect(self.empttyBtnClicked) def updateCompaniesList(self): self.companyListCB.clear() self.companyList=getCompanyList() self.companyListCB.addItems(self.companyList) def updateBillsList(self): self.bilChooseCb.clear() self.bilChooseCb.addItems(getNumberOfBills()) @QtCore.pyqtSlot() def getCompanyCard(self): companyCardWindow=QtWidgets.QDialog() companyCard=Ui_aboutCompanyWindow() companyCard.setupUi(companyCardWindow, self.companyListCB.currentText()) companyCardWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose) companyCard.getInfoFromFile(self.companyListCB.currentText()) companyCardWindow.exec_() @QtCore.pyqtSlot() def addCompany(self): addCompanyWindow=QtWidgets.QDialog() addCompany=addCompanyDialog() addCompany.setupUi(addCompanyWindow) addCompanyWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose) addCompanyWindow.exec_() self.updateCompaniesList() @QtCore.pyqtSlot() def getBilCard(self): print(self.bilChooseCb.currentIndex()+1) self.billData=getBillData(self.bilChooseCb.currentIndex() + 1) print(self.billData) bilCardWindow=QtWidgets.QDialog() bilCard=Ui_bilCard() bilCard.setupUi(bilCardWindow, self.billData) bilCardWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose) bilCardWindow.exec_() @QtCore.pyqtSlot() def editCompanyBtnClicked(self): editCompanyWindow=QtWidgets.QDialog() editCompany=editCompanyDialog() editCompany.setupUi(editCompanyWindow) editCompanyWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose) editCompany.setCompanyData(self.companyListCB.currentText()) editCompanyWindow.exec_() @QtCore.pyqtSlot() def exitUpdateBtnClicked(self): app.exit() @QtCore.pyqtSlot() def empttyBtnClicked(self): message=QtWidgets.QMessageBox() message.setIcon(QtWidgets.QMessageBox.Information) message.setText('В следующих версиях') message.exec_() if __name__ == '__main__': app=QtWidgets.QApplication(sys.argv) MainWindow=QtWidgets.QMainWindow() MainWindowObject=Ui_MainWindow() MainWindowObject.setupUi(MainWindow) MainWindowObject.updateCompaniesList() MainWindowObject.updateBillsList() MainWindow.show() sys.exit(app.exec_())
{"/mainWindow.py": ["/companyAbout.py", "/bilCard.py", "/editCompany.py"]}
41,512
bidlocoder1422/DataBase1.0
refs/heads/master
/companyAbout.py
# -*- coding: utf-8 -*- #DONE1!1 from PyQt5 import QtCore, QtGui, QtWidgets import xlrd class Ui_aboutCompanyWindow(object): def setupUi(self, aboutCompanyWindow,companyName): self.companyName=companyName aboutCompanyWindow.setObjectName("aboutCompanyWindow") aboutCompanyWindow.resize(490 , 260) self.companyNameHeaderLabel = QtWidgets.QLabel(aboutCompanyWindow) self.companyNameHeaderLabel.setGeometry(QtCore.QRect(190, 10, 371, 16)) self.companyNameHeaderLabel.setText("") self.companyNameHeaderLabel.setObjectName("companyNameHeaderLabel") self.companyNameInfoLabel = QtWidgets.QLabel(aboutCompanyWindow) self.companyNameInfoLabel.setGeometry(QtCore.QRect(30, 40, 111, 16)) self.companyNameInfoLabel.setObjectName("companyNameInfoLabel") self.companyNameOutput = QtWidgets.QLabel(aboutCompanyWindow) self.companyNameOutput.setGeometry(QtCore.QRect(150, 40, 301, 20)) self.companyNameOutput.setObjectName("companyNameOutput") self.innInfoLabel = QtWidgets.QLabel(aboutCompanyWindow) self.innInfoLabel.setGeometry(QtCore.QRect(30, 70, 31, 16)) self.innInfoLabel.setObjectName("innInfoLabel") self.kppInfoLabel = QtWidgets.QLabel(aboutCompanyWindow) self.kppInfoLabel.setGeometry(QtCore.QRect(30, 100, 41, 20)) self.kppInfoLabel.setObjectName("kppInfoLabel") self.innOutput = QtWidgets.QLabel(aboutCompanyWindow) self.innOutput.setGeometry(QtCore.QRect(70, 70, 141, 20)) self.innOutput.setObjectName("innOutput") self.kppOutput = QtWidgets.QLabel(aboutCompanyWindow) self.kppOutput.setGeometry(QtCore.QRect(70, 100, 141, 20)) self.kppOutput.setObjectName("kppOutput") self.contractNumberLabel = QtWidgets.QLabel(aboutCompanyWindow) self.contractNumberLabel.setGeometry(QtCore.QRect(30, 130, 51, 16)) self.contractNumberLabel.setObjectName("contractNumberLabel") self.contarctNumberOutput = QtWidgets.QLabel(aboutCompanyWindow) self.contarctNumberOutput.setGeometry(QtCore.QRect(80, 130, 161, 20)) self.contarctNumberOutput.setObjectName("contarctNumberOutput") self.typeCompanyLabel = QtWidgets.QLabel(aboutCompanyWindow) self.typeCompanyLabel.setGeometry(QtCore.QRect(30, 160, 41, 16)) self.typeCompanyLabel.setObjectName("typeCompanyLabel") self.typeCompanyLabelOutput = QtWidgets.QLabel(aboutCompanyWindow) self.typeCompanyLabelOutput.setGeometry(QtCore.QRect(60, 160, 111, 16)) self.typeCompanyLabelOutput.setText("") self.typeCompanyLabelOutput.setObjectName("typeCompanyLabelOutput") self.contractNumberLabel = QtWidgets.QLabel(aboutCompanyWindow) self.contractNumberLabel.setGeometry(QtCore.QRect(30, 130, 51, 16)) self.contractNumberLabel.setObjectName("contractNumberLabel") self.contarctNumberOutput = QtWidgets.QLineEdit(aboutCompanyWindow) self.contarctNumberOutput.setGeometry(QtCore.QRect(80, 130, 161, 20)) self.contarctNumberOutput.setObjectName("contactNumberOutput") self.contactNameLabel = QtWidgets.QLabel(aboutCompanyWindow) self.contactNameLabel.setGeometry(QtCore.QRect(240, 70, 101, 16)) self.contactNameLabel.setObjectName("contactNameLabel") self.phoneNumberLabel = QtWidgets.QLabel(aboutCompanyWindow) self.phoneNumberLabel.setGeometry(QtCore.QRect(240, 100, 31, 16)) self.phoneNumberLabel.setObjectName("phoneNumberLabel") self.contactNameOutput = QtWidgets.QLabel(aboutCompanyWindow) self.contactNameOutput.setGeometry(QtCore.QRect(350, 70, 71, 16)) self.contactNameOutput.setObjectName("contactNameOutput") self.phoneNumber = QtWidgets.QLabel(aboutCompanyWindow) self.phoneNumber.setGeometry(QtCore.QRect(280, 100, 191, 16)) self.phoneNumber.setObjectName("phoneNumber") self.adressLabel = QtWidgets.QLabel(aboutCompanyWindow) self.adressLabel.setGeometry(QtCore.QRect(20, 190, 111, 16)) self.adressLabel.setObjectName("adressLabel") self.adressOutput = QtWidgets.QLineEdit(aboutCompanyWindow) self.adressOutput.setGeometry(QtCore.QRect(150, 190, 321, 20)) self.adressOutput.setObjectName("adressOutput") self.postAdressLabel = QtWidgets.QLabel(aboutCompanyWindow) self.postAdressLabel.setGeometry(QtCore.QRect(20, 220, 91, 16)) self.postAdressLabel.setObjectName("postAdressLabel") self.postAdressOutput = QtWidgets.QLineEdit(aboutCompanyWindow) self.postAdressOutput.setGeometry(QtCore.QRect(120, 220, 351, 20)) self.postAdressOutput.setObjectName("postAdressOutput") self.retranslateUi(aboutCompanyWindow) QtCore.QMetaObject.connectSlotsByName(aboutCompanyWindow) def retranslateUi(self, aboutCompanyWindow): _translate = QtCore.QCoreApplication.translate aboutCompanyWindow.setWindowTitle(_translate("aboutCompanyWindow", self.companyName)) self.companyNameInfoLabel.setText(_translate("aboutCompanyWindow", "Название компании: ")) self.innInfoLabel.setText(_translate("aboutCompanyWindow", "ИНН: ")) self.kppInfoLabel.setText(_translate("aboutCompanyWindow", "КПП:")) self.contractNumberLabel.setText(_translate("aboutCompanyWindow", "Договор:")) self.typeCompanyLabel.setText(_translate("aboutCompanyWindow", "Тип:")) self.contactNameLabel.setText(_translate("aboutCompanyWindow", "Контактное лицо: ")) self.phoneNumberLabel.setText(_translate("aboutCompanyWindow", "тел: ")) self.adressLabel.setText(_translate("aboutCompanyWindow", "Юридический адрес")) self.postAdressLabel.setText(_translate("aboutCompanyWindow", "Почтовый адрес")) def getInfoFromFile(self, companyName): companiesListFile = xlrd.open_workbook('data/companiesBase.xlsx') workSheet = companiesListFile.sheet_by_index(0) companyInfo = [] rowNumber = 0 for i in range(1, workSheet.nrows): if workSheet.cell(i, 1).value == companyName: rowNumber = i continue for i in range(1, workSheet.ncols): companyInfo.append(workSheet.cell(rowNumber, i).value) for i in range(len(companyInfo)): if not companyInfo[i]: companyInfo[i]='Неизвестно' if not companyInfo[3]: companyInfo[3]='Нет договора' self.companyNameOutput.setText(companyInfo[0]) self.innOutput.setText(str(int(companyInfo[1]))) self.kppOutput.setText(str(int(companyInfo[2]))) self.contarctNumberOutput.setText(str(companyInfo[3])) self.contactNameOutput.setText(companyInfo[6]) self.phoneNumber.setText(companyInfo[7]) self.adressOutput.setText(companyInfo[8]) self.postAdressOutput.setText(companyInfo[9]) if companyInfo[4]: self.companyNameHeaderLabel.setText('Оригинал договора получен') self.companyNameHeaderLabel.setStyleSheet('color: green') else: self.companyNameHeaderLabel.setText('Оригинал договора не получен') self.companyNameHeaderLabel.setStyleSheet('color: red') self.typeCompanyLabelOutput.setText(str(companyInfo[5]))
{"/mainWindow.py": ["/companyAbout.py", "/bilCard.py", "/editCompany.py"]}
41,513
bidlocoder1422/DataBase1.0
refs/heads/master
/bilCard.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\billcard.ui' # # Created by: PyQt5 UI code generator 5.9 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets import sys, xlrd,math class Ui_bilCard(QtWidgets.QWidget): def setupUi(self, bilCard, billData): bilCard.setObjectName("bilCard") bilCard.resize(640, 224) self.headerLabel = QtWidgets.QLabel(bilCard) self.headerLabel.setGeometry(QtCore.QRect(230, 10, 161, 16)) self.headerLabel.setObjectName("headerLabel") self.companyNameLabel = QtWidgets.QLabel(bilCard) self.companyNameLabel.setGeometry(QtCore.QRect(30, 60, 121, 16)) self.companyNameLabel.setObjectName("companyNameLabel") self.companyNameOutput = QtWidgets.QLabel(bilCard) self.companyNameOutput.setGeometry(QtCore.QRect(140, 60, 401, 16)) self.companyNameOutput.setText("") self.companyNameOutput.setObjectName("companyNameOutput") self.priceLabel = QtWidgets.QLabel(bilCard) self.priceLabel.setGeometry(QtCore.QRect(30, 100, 51, 16)) self.priceLabel.setObjectName("priceLabel") self.priceOutput = QtWidgets.QLabel(bilCard) self.priceOutput.setGeometry(QtCore.QRect(80, 100, 121, 16)) self.priceOutput.setText("") self.priceOutput.setObjectName("priceOutput") self.deliveryYesNoOutput = QtWidgets.QLabel(bilCard) self.deliveryYesNoOutput.setGeometry(QtCore.QRect(220, 130, 141, 20)) self.deliveryYesNoOutput.setText("") self.deliveryYesNoOutput.setObjectName("deliveryYesNoOutput") self.documentTypeLabel = QtWidgets.QLabel(bilCard) self.documentTypeLabel.setGeometry(QtCore.QRect(30, 160, 121, 16)) self.documentTypeLabel.setObjectName("documentTypeLabel") self.documentTypeOutput = QtWidgets.QLabel(bilCard) self.documentTypeOutput.setGeometry(QtCore.QRect(113, 160, 47, 16)) self.documentTypeOutput.setText("") self.documentTypeOutput.setObjectName("documentTypeOutput") self.documentNumberLabel = QtWidgets.QLabel(bilCard) self.documentNumberLabel.setGeometry(QtCore.QRect(30, 190, 91, 16)) self.documentNumberLabel.setObjectName("documentNumberLabel") self.documentNumberOutput = QtWidgets.QLabel(bilCard) self.documentNumberOutput.setGeometry(QtCore.QRect(124, 190, 81, 16)) self.documentNumberOutput.setText("") self.documentNumberOutput.setObjectName("documentNumberOutput") self.numberOfPositionsLabel = QtWidgets.QLabel(bilCard) self.numberOfPositionsLabel.setGeometry(QtCore.QRect(270, 100, 111, 16)) self.numberOfPositionsLabel.setObjectName("numberOfPositionsLabel") self.bilTypeLabel = QtWidgets.QLabel(bilCard) self.bilTypeLabel.setGeometry(QtCore.QRect(270, 190, 61, 16)) self.bilTypeLabel.setObjectName("bilTypeLabel") self.bilTypeOutput = QtWidgets.QLabel(bilCard) self.bilTypeOutput.setGeometry(QtCore.QRect(333, 190, 61, 16)) self.bilTypeOutput.setObjectName("bilTypOutput") self.numberOfPositionsOutput = QtWidgets.QLabel(bilCard) self.numberOfPositionsOutput.setGeometry(QtCore.QRect(400, 100, 47, 16)) self.numberOfPositionsOutput.setObjectName("numberOfPositionsOutput") self.billData=billData self.retranslateUi(bilCard) QtCore.QMetaObject.connectSlotsByName(bilCard) def retranslateUi(self, bilCard): _translate = QtCore.QCoreApplication.translate bilCard.setWindowTitle(_translate("bilCard", "Счет")) self.headerLabel.setText(_translate("bilCard", "Карточка счета ")) self.companyNameLabel.setText(_translate("bilCard", "Название компании: ")) self.priceLabel.setText(_translate("bilCard", "Сумма: ")) self.documentTypeLabel.setText(_translate("bilCard", "Тип документа:")) self.documentNumberLabel.setText(_translate("bilCard", "Номер документа: ")) self.numberOfPositionsLabel.setText(_translate("bilCard", "Количество позиций: ")) self.bilTypeLabel.setText(_translate("bilCard", "Тип счета: ")) self.bilTypeOutput.setText(_translate("bilCard", 'text')) self.companyNameOutput.setText(self.billData[1]) self.priceOutput.setText(self.billData[2]) self.numberOfPositionsOutput.setText(self.billData[5]) self.bilTypeOutput.setText(self.billData[6]) if not self.billData[4]: self.deliveryYesNoOutput.setText('НЕ ОТГРУЖЕН') else: self.deliveryYesNoOutput.setText('ОТГРУЖЕН') self.documentTypeOutput.setText(self.billData[3]) self.documentNumberOutput.setText(self.billData[4])
{"/mainWindow.py": ["/companyAbout.py", "/bilCard.py", "/editCompany.py"]}
41,514
bidlocoder1422/DataBase1.0
refs/heads/master
/editCompany.py
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets import openpyxl,xlwt,xlrd class editCompanyDialog(QtWidgets.QWidget): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(468, 324) self.companyNameInput = QtWidgets.QLineEdit(Dialog) self.companyNameInput.setGeometry(QtCore.QRect(79, 40, 341, 20)) self.companyNameInput.setObjectName("companyNameInput") self.companyNameLbl = QtWidgets.QLabel(Dialog) self.companyNameLbl.setGeometry(QtCore.QRect(7, 43, 71, 16)) self.companyNameLbl.setObjectName("companyNameLbl") self.innLabel = QtWidgets.QLabel(Dialog) self.innLabel.setGeometry(QtCore.QRect(16, 74, 47, 13)) self.innLabel.setObjectName("innLabel") self.innInput = QtWidgets.QLineEdit(Dialog) self.innInput.setGeometry(QtCore.QRect(80, 70, 131, 20)) self.innInput.setObjectName("innInput") self.kppLabel = QtWidgets.QLabel(Dialog) self.kppLabel.setGeometry(QtCore.QRect(250, 75, 47, 13)) self.kppLabel.setObjectName("kppLabel") self.kppInput = QtWidgets.QLineEdit(Dialog) self.kppInput.setGeometry(QtCore.QRect(290, 70, 131, 20)) self.kppInput.setObjectName("kppInput") self.contractNumberInput = QtWidgets.QLineEdit(Dialog) self.contractNumberInput.setGeometry(QtCore.QRect(90, 110, 331, 20)) self.contractNumberInput.setObjectName("contractNumberInput") self.contractLabel = QtWidgets.QLabel(Dialog) self.contractLabel.setGeometry(QtCore.QRect(10, 110, 47, 13)) self.contractLabel.setObjectName("contractLabel") self.originalContractCheckBox = QtWidgets.QCheckBox(Dialog) self.originalContractCheckBox.setGeometry(QtCore.QRect(300, 140, 121, 17)) self.originalContractCheckBox.setObjectName("originalContractCheckBox") self.companyTypeCB = QtWidgets.QComboBox(Dialog) self.companyTypeCB.setGeometry(QtCore.QRect(20, 140, 141, 22)) self.companyTypeCB.setObjectName("companyTypeCB") self.headerLabel = QtWidgets.QLabel(Dialog) self.headerLabel.setGeometry(QtCore.QRect(130, 10, 121, 16)) self.headerLabel.setObjectName("headerLabel") self.acceptBtn=QtWidgets.QPushButton(Dialog) self.acceptBtn.setObjectName("acceptBtn") self.acceptBtn.setGeometry(190,290,75,23) self.acceptBtn.setText('Принять') self.contactNamelabel = QtWidgets.QLabel(Dialog) self.contactNamelabel.setGeometry(QtCore.QRect(10, 180, 111, 16)) self.contactNamelabel.setObjectName("contactNamelabel") self.contactNameIutput = QtWidgets.QLineEdit(Dialog) self.contactNameIutput.setGeometry(QtCore.QRect(123, 179, 113, 20)) self.contactNameIutput.setObjectName("contactNameIutput") self.phoneLabel = QtWidgets.QLabel(Dialog) self.phoneLabel.setGeometry(QtCore.QRect(250, 180, 31, 16)) self.phoneLabel.setObjectName("phoneLabel") self.phoneNumberInput = QtWidgets.QLineEdit(Dialog) self.phoneNumberInput.setGeometry(QtCore.QRect(290, 180, 171, 20)) self.phoneNumberInput.setObjectName("phoneNumberInput") self.adressLabel = QtWidgets.QLabel(Dialog) self.adressLabel.setGeometry(QtCore.QRect(10, 220, 111, 16)) self.adressLabel.setObjectName("adressLabel") self.adressInput = QtWidgets.QLineEdit(Dialog) self.adressInput.setGeometry(QtCore.QRect(130, 220, 331, 20)) self.adressInput.setObjectName("adressInput") self.postAdressLabel = QtWidgets.QLabel(Dialog) self.postAdressLabel.setGeometry(QtCore.QRect(10, 260, 81, 16)) self.postAdressLabel.setObjectName("postAdressLabel") self.postAdressInput = QtWidgets.QLineEdit(Dialog) self.postAdressInput.setGeometry(QtCore.QRect(100, 260, 361, 20)) self.postAdressInput.setObjectName("postAdressInput") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Редактирование контрагента")) self.companyNameLbl.setText(_translate("Dialog", "Имя компании")) self.innLabel.setText(_translate("Dialog", "ИНН")) self.kppLabel.setText(_translate("Dialog", "КПП")) self.contractLabel.setText(_translate("Dialog", "Договор:")) self.originalContractCheckBox.setText(_translate("Dialog", "Получен оригинал")) self.headerLabel.setText(_translate("Dialog", "Изменение данных")) self.companyTypeCB.clear() self.companyTypeCB.addItems(['Покупатель','Поставщик']) self.contactNamelabel.setText(_translate("Dialog", "Конатктное лицо : ")) self.phoneLabel.setText(_translate("Dialog", "тел")) self.acceptBtn.setText(_translate("Dialog", "Принять")) self.adressLabel.setText(_translate("Dialog", "Юридический адрес")) self.postAdressLabel.setText(_translate("Dialog", "Почтоый адрес")) self.acceptBtn.clicked.connect(self.acceptBtnPushed) def setCompanyData(self, companyName): companiesListFile = xlrd.open_workbook('data/companiesBase.xlsx') workSheet = companiesListFile.sheet_by_index(0) companyInfo = [] self.rowNumber = 0 for i in range(1, workSheet.nrows): if workSheet.cell(i, 1).value == companyName: self.rowNumber = i i=workSheet.nrows for i in range(1, workSheet.ncols): companyInfo.append(workSheet.cell(self.rowNumber, i).value) self.companyNameInput.setText(companyInfo[0]) self.innInput.setText(str(int(companyInfo[1]))) self.kppInput.setText(str(int(companyInfo[2]))) self.contractNumberInput.setText(str(companyInfo[3])) self.contactNameIutput.setText(companyInfo[6]) self.phoneNumberInput.setText(companyInfo[7]) self.postAdressInput.setText(companyInfo[8]) self.adressInput.setText(companyInfo[9]) if companyInfo[4]: self.originalContractCheckBox.setChecked(True) if(companyInfo[5]=='покупатель'): self.companyTypeCB.setCurrentIndex(0) else: self.companyTypeCB.setCurrentIndex(1) self.companyInfo=companyInfo print(self.rowNumber) @QtCore.pyqtSlot() def acceptBtnPushed(self): excelFile = openpyxl.load_workbook('data\companiesBase.xlsx') workSheet = excelFile.get_sheet_by_name('sheet1') self.rowNumber=str(self.rowNumber+1) workSheet['B' + self.rowNumber] = self.companyNameInput.text() workSheet['C' + self.rowNumber] = self.innInput.text() workSheet['D' + self.rowNumber] = self.kppInput.text() workSheet['E' + self.rowNumber] = self.contractNumberInput.text() workSheet['F' + self.rowNumber] = int(self.originalContractCheckBox.isChecked()) workSheet['G' + self.rowNumber] = self.companyTypeCB.currentText() workSheet['H' + self.rowNumber] = self.contactNameIutput.text() workSheet['I' + self.rowNumber] = self.phoneNumberInput.text() workSheet['J' + self.rowNumber] = self.postAdressInput.text() workSheet['K' + self.rowNumber] = self.adressInput.text() excelFile.save('data\companiesBase.xlsx') self.acceptBtn.setVisible(0)
{"/mainWindow.py": ["/companyAbout.py", "/bilCard.py", "/editCompany.py"]}
41,515
gtoban/kerasTimeSeries
refs/heads/master
/rnntune.py
import pandas as pd import numpy as np from kerasOOP import keras_ann, cnn_data import os import json numOfInputFiles = 5 def main(): print("Initializing") myAnn = keras_ann() myloc = os.path.expanduser('~') + "/kerasTimeSeries/" myData = cnn_data(dataPath= os.path.expanduser('~') + "/eegData/") # 0 1 2 3 useCandidate = ['', 'topTwo.csv', 'topTen.csv', 'candidate.csv'][0] testing = True optimizeOptimizer = False saveModel = False modelArgs = [] #getModels() small models only for now! #addToModels(modelArgs) print("Collecting Models") if (useCandidate == ''): addToModels(modelArgs) #else: # getCandidates(modelArgs, fname=useCandidate, optimize = optimizeOptimizer) # print(f"Number of Models: {len(modelArgs)}") myAnn.updatePaths(outputPath = os.path.dirname(os.path.realpath(__file__)) + "/") if (testing): myData.readData() else: myData.readData(fnames=inputData()) lowFreq=highFreq=None dataFiles = ",".join(inputData()) cvFolds = 0 if saveModel else 10 valPerc = 0.10 epochs = 1 if saveModel else 100 batchSize = 32 if saveModel else int(((myData.record_count*(1-valPerc))/cvFolds)+1) with open("fileTrainTestParams.txt",'w') as params: params.write(f"dataFiles: {dataFiles}\ncvFolds: {cvFolds}\n") params.write(f"validation_split: {valPerc}\nepoch: {epochs}\n") params.write(f"batchSize: {batchSize}\n") params.write(f"frequency: {lowFreq} - {highFreq}\n") params.write(f"normSTD : {myData.normSTD}\n") params.write(f"normMean : {myData.normMean}") if (saveModel): myAnn.trainModel(modelArgs,myData.data,myData.labels, valSplit=valPerc, epochs=epochs, batchSize=batchSize, visualize=False, saveLoc=myloc) return if (testing): myAnn.parameterSearch(modelArgs[:1],myData.data,myData.labels,valSplit=0.10) else: myAnn.parameterSearch(modelArgs,myData.data,myData.labels,numSplits=cvFolds, valSplit=valPerc, epochs=epochs, batchSize=batchSize, saveModel=saveModel, visualize=False, saveLoc=myloc) def addToModels(modelArgs): #low freq to high freq numOfModels = 100 possibleRecurrentLayers = 5 possibleUnits = [int(val) for val in np.linspace(5,600,num=25)] possibleDenseLayers = 5 maxHiddenUnits = [10,30,50,70,100,120,150,170,200] hiddenUnitsDivisors = [1,2,3,4] denseActivations = ['sigmoid','relu','tanh'] for i in range(numOfModels): numOfRecurrentLayers = int(np.random.randint(1,possibleRecurrentLayers)) denseActivation = denseActivations[np.random.randint(len(denseActivations))] modelArgs.append([{ 'layer': 'input', 'shape': (3,10) }]) # randomly add a timeDistributed Dense layer here if int(np.random.randint(2)) == 1: modelArgs[-1].append({ 'layer': 'dense', 'output': 10, 'activation': denseActivation, 'wrapper': 'timedistributed' }) bidirectional = True if int(np.random.randint(2)) == 1 else False if numOfRecurrentLayers > 1: for dummy in range(numOfRecurrentLayers-1): units = possibleUnits[int(np.random.randint(len(possibleUnits)))] modelArgs[-1].append({ 'layer': 'rnn', 'type' : 'gru', 'units': units, 'return_sequences': True }) bidirectional = True if int(np.random.randint(2)) == 1 else False if bidirectional: modelArgs[-1][-1]['wrapper'] = 'bidirectional' # randomly add a timeDistributed Dense layer here if int(np.random.randint(2)) == 1: modelArgs[-1].append({ 'layer': 'dense', 'output': units*2 if bidirectional else units, 'activation': denseActivation, 'wrapper': 'timedistributed' }) units = possibleUnits[int(np.random.randint(len(possibleUnits)))] timeDist = True if int(np.random.randint(2)) == 1 else False bidirectional = True if int(np.random.randint(2)) == 1 else False modelArgs[-1].append({ 'layer': 'rnn', 'type' : 'gru', 'units': units, 'return_sequences': timeDist }) if bidirectional: modelArgs[-1][-1]['wrapper'] = 'bidirectional' if timeDist: modelArgs[-1].append({ 'layer': 'dense', 'output': units*2 if bidirectional else units, 'activation': denseActivation, 'wrapper': 'timedistributed' }) modelArgs[-1].append({ 'layer': 'flatten'}) divisor = hiddenUnitsDivisors[np.random.randint(len(hiddenUnitsDivisors))] output = maxHiddenUnits[np.random.randint(len(maxHiddenUnits))] for dummy in range(0,int(np.random.randint(possibleDenseLayers))): output = int(output//divisor) if dummy > 0 and output > 5 else output modelArgs[-1].append({ 'layer': 'dense', 'output': output, 'activation': denseActivation }) modelArgs[-1].append({ 'layer': 'dense', 'output': 2, 'activation':'softmax' }) modelArgs[-1].append({ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }) def inputData(): #this is the entire list #return np.array("input001.csv,input002.csv,input011.csv,input012.csv,input031.csv,input032.csv,input041.csv,input042.csv,input081.csv,input082.csv,input091.csv,input101.csv,input112.csv,input142.csv,input151.csv,input152.csv,input161.csv,input162.csv,input171.csv,input172.csv".split-(",")) #These choices were made by which ones had the most REM t = "outinput152.csv,outinput042.csv,outinput171.csv,outinput161.csv,outinput082.csv,outinput091.csv,outinput002.csv,outinput142.csv,outinput031.csv,outinput151.csv,outinput101.csv,outinput032.csv".split(",") return np.array(t[:max( min(numOfInputFiles,len(t)),2)]) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,516
gtoban/kerasTimeSeries
refs/heads/master
/notifyWhenFinished.py
import smtplib, ssl import subprocess import time import sys def sendEmail(password): port = 465 email = "gtoban87@gmail.com" message = "Subject: Job Complete\n\n\n\nThe job is complete" context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com",port,context=context) as server: server.login(email, password) server.sendmail(email,email,message) def sendStatus(password, status): port = 465 email = "gtoban87@gmail.com" message = "Subject: Job Status\n\n\n\n" message += status context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com",port,context=context) as server: server.login(email, password) server.sendmail(email,email,message) def main(): if (len(sys.argv) > 1): password = sys.argv[1] pid = sys.argv[2] else: password = input("Enter password: ") pid = input("Enter PID: ") notDone = True si = 1 while (notDone): #p = subprocess.Popen(["ssh", "compute-0-0","ps","-q",pid], stdout=subprocess.PIPE) p = subprocess.Popen(["ps","-q",pid], stdout=subprocess.PIPE) out = p.communicate()[0] if (len(out.split(b"\n")) < 3): notDone = False else: time.sleep(30) if (si%120 == 0): p = subprocess.Popen(["tail","-n","100","status.txt"], stdout=subprocess.PIPE) status = str(p.communicate()[0]) sendStatus(password, status) si += 1 sendEmail(password) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,517
gtoban/kerasTimeSeries
refs/heads/master
/kerasOOP.py
import numpy as np import json import tensorflow as tf from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import Dense, Conv1D, Flatten, MaxPooling1D, AveragePooling1D, Input, Concatenate, Embedding,LSTM, GRU, TimeDistributed, Bidirectional from tensorflow.keras.callbacks import EarlyStopping, TensorBoard from tensorflow.keras import backend as K, metrics, optimizers from tensorflow.keras.utils import plot_model from sklearn.model_selection import StratifiedKFold from sklearn.metrics import f1_score, confusion_matrix, multilabel_confusion_matrix from scipy import signal as scisig from scipy import fftpack import signal import sys from os import listdir class GracefulKiller: kill_now = False def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self,signum, frame): self.kill_now = True class cnn_data(object): def __init__(self,dataPath="",outputPath=""): self.dataPath = dataPath self.outputPath = outputPath self.normSTD = 1 self.normMean = 1 def readData(self, fnames=["outinput002.csv","outinput142.csv"]): print("Starting Read") self.record_count = 0 for fname in fnames: with open(self.dataPath + fname) as f: for line in f: if (line.strip()): self.record_count += 1 self.record_count -= 2 sample = 0 # records use # 3 eeg epochs in time each with # 5 algorithms producing # 2 predictions for REM vs NonREM self.data = np.zeros((self.record_count,3,5*2)) self.labels = np.zeros((self.record_count,2)) self.obsLabels = np.zeros((self.record_count)) obsLabelsCount = {} for fname in fnames: RVNR = [0,0] #RVNR REM Vs NonREM f = open(self.dataPath + fname) lines = [] lines.append(f.readline().strip()) lines.append(f.readline().strip()) lines.append(f.readline().strip()) while(lines[2]): timeCount = 0 for line in lines: arow = line.split("|") measure_count = 0 for ame in arow[1:]: self.data[sample][timeCount][measure_count] = float(ame) measure_count += 1 timeCount += 1 # use middle time for label if timeCount == 1: self.obsLabels[sample] = arow[0] if arow[0] in obsLabelsCount.keys(): obsLabelsCount[arow[0]] += 1 else: obsLabelsCount[arow[0]] = 1 self.labels[sample][int(arow[0])] = 1 RVNR[int(arow[0])] += 1 sample += 1 lines[0] = lines[1] lines[1] = lines[2] lines[2] = f.readline().strip() f.close() print(f"{fname} -> REM: {RVNR[0]}; NonREM: {RVNR[1]}") for l in obsLabelsCount: print(f"{l} : {obsLabelsCount[l]}") #return self.data, self.labels, self.record_count class ann_data(object): def __init__(self,dataPath="",outputPath=""): self.dataPath = dataPath self.outputPath = outputPath self.normSTD = 1 self.normMean = 1 self.labToInd = {'W':0,'1':1, '2':2, '3': 3, '4': 4, 'R':5} self.indToLab = ['W','1', '2', '3', '4', 'R'] def readData(self, fnames=["input002.csv","input142.csv"]): print("Starting Read") self.record_count = 0 for fname in fnames: with open(self.dataPath + fname) as f: for line in f: if (line.strip()): self.record_count += 1 sample = 0 self.data = np.zeros((self.record_count,3000)) self.labels = np.zeros((self.record_count,2)) self.obsLabels = np.zeros((self.record_count)) obsLabelsCount = {} for fname in fnames: RVNR = [0,0] #RVNR REM Vs NonREM f = open(self.dataPath + fname) line = f.readline().strip() while(line): arow = line.split(",") self.obsLabels[sample] = self.labToInd[arow[0]] if arow[0] in obsLabelsCount.keys(): obsLabelsCount[arow[0]] += 1 else: obsLabelsCount[arow[0]] = 1 self.labels[sample][0 if arow[0] == 'R' else 1] = 1 RVNR[0 if arow[0] == 'R' else 1] += 1 measure_count = 0 for ame in arow[1:]: self.data[sample][measure_count] = float(ame) measure_count += 1 sample += 1 line = f.readline().strip() f.close() print(f"{fname} -> REM: {RVNR[0]}; NonREM: {RVNR[1]}") for l in obsLabelsCount: print(f"{l} : {obsLabelsCount[l]}") #return self.data, self.labels, self.record_count def expandDims(self): print("Expand Dims") self.data = np.expand_dims(self.data,axis=2) print("shape:", self.data.shape) def normalize(self, normSTD = None, normMean = None): print("Normalize") if (normSTD is None): self.normSTD = np.std(self.data) self.normMean = np.mean(self.data) else: self.normSTD = normSTD self.normMean = normMean self.data = np.divide(np.subtract(self.data,self.normMean), self.normSTD) def getFreqBand(freqBand): if (freqBand == 'delta'): return [None, 3.5, 2] elif (freqBand == 'theta'): return [3.5,7.5,5] elif (freqBand == 'alpha'): return [7.5,13.0,10] elif (freqBand == 'beta1'): return [13.0, 25.0, 19] elif (freqBand == 'beta2'): return [25.0, 45.0, 35] def filterFrequencyRange(self, low=None, high=None, order=8): print("Frequency Range") if (low == None and high == None): return sampleFrequency = 100 if (high == None): #Allow high frequency ranges filtb,filta = scisig.butter(order,low/(sampleFrequency/2),btype='highpass') elif (low == None): #allow low frequency ranges filtb,filta = scisig.butter(order,high/(sampleFrequency/2),btype='lowpass') else: filtb,filta = scisig.butter(order,[low/(sampleFrequency/2),high/(sampleFrequency/2)] ,btype='bandpass') myError = 0 try: for i in range(self.data.shape[0]): #print(i) myError = i self.data[i] = scisig.filtfilt(filtb,filta,self.data[i]) except Exception as e: print(f"BAND RANGE ERROR epoch: {myError}") def fourierAll(self): allFreq = [] for i in range(self.data.shape[0]): allFreq.append(fftpack.fft(self.data[i])) return allFreq class keras_ann(object): def __init__(self): self.dataPath = "" self.outputPath = "" self.inputShape = (3000,1) self.killer = GracefulKiller() def updatePaths(self, dataPath = '', outputPath = ''): self.outputPath = outputPath self.dataPath = dataPath def convModel(self, modelArgs=[], inputShape = [3000,1], defaultInput=True): # # For First Layer, input requried # if defaultInput: model = Xtensor = Input(shape=inputShape) # # For all other layers # #print("BUIDLING==================================") indexes = dict.fromkeys(['conv1d','flatten','dense','maxpool1d','avgpool1d','compile','rnn','lstm','input'],0) for modelArg in modelArgs: indexes[modelArg['layer']] += 1 name = f"{modelArg['layer']}{indexes[modelArg['layer']]}" if (modelArg['layer'] == 'input'): model = Xtensor = Input(shape=modelArg['shape']) elif (modelArg['layer'] == 'conv1d'): #print("CONVOLUTION1D===================================================") model = Conv1D(filters=modelArg['no_filters'], kernel_size=modelArg['kernal_size'], padding=modelArg['padding'], activation=modelArg['activation'], name=name )(model)#shape batch, steps, channels elif (modelArg['layer'] == 'flatten'): #print("FLATTEN===================================================") model = Flatten()(model) elif (modelArg['layer'] == 'rnn'): if (modelArg['type'] == 'lstm'): tlstm = LSTM(modelArg['units'], return_sequences = modelArg['return_sequences']) elif (modelArg['type'] == 'gru'): tlstm = GRU(modelArg['units'], return_sequences = modelArg['return_sequences']) if 'wrapper' in modelArg.keys(): if modelArg['wrapper'] == 'timedistributed': model = TimeDistributed(tlstm) (model) elif modelArg['wrapper'] == 'bidirectional': model = Bidirectional(tlstm)(model) elif 'wrappers' in modelArg.keys(): for wrapper in modelArg['wrappers']: if wrapper == 'timedistributed': tlstm = TimeDistributed(tlstm) elif wrapper == 'bidirectional': tlstm = Bidirectional(tlstm) model = tlstm(model) else: model = tlstm(model) elif (modelArg['layer'] == 'dense'): #print("DENSE===================================================") tdense = Dense(modelArg['output'], activation=modelArg['activation'], #kernel_initializer=modelArg['kernel_initializer'], #bias_initializer=modelArg['bias_initializer'], name=name ) if 'wrapper' in modelArg.keys(): if modelArg['wrapper'] == 'timedistributed': model = TimeDistributed(tdense)(model) else: model = tdense(model) elif (modelArg['layer'] == 'maxpool1d'): #print("MAXPOOL===================================================") model = MaxPooling1D(pool_size=modelArg['pool_size'], strides=modelArg['strides'], padding=modelArg['padding'], name=name )(model) elif (modelArg['layer'] == 'avgpool1d'): #print("AVGPOOL===================================================") model = AveragePooling1D(pool_size=modelArg['pool_size'], strides=modelArg['strides'], padding=modelArg['padding'], name=name,)(model) elif (modelArg['layer'] == 'compile'): #print("COMPILECONVOLUTION1D===================================================") model = Model(Xtensor, model) self.compileModel(model,modelArg) return model def getOptimizer(self,optimizer, options): if (optimizer == 'sgd'): return optimizers.SGD(lr=options[0], momentum=options[1], nesterov=options[2]) if (optimizer == 'adam'): return optimizers.Adam(lr=options[0], beta_1=options[1], beta_2=options[2], amsgrad=options[3]) if (optimizer == 'nadam'): return optimizers.Nadam(lr=options[0], beta_1=options[1], beta_2=options[2]) if (optimizer == 'rmsprop'): return optimizers.RMSprop(lr=options[0],rho=options[1]) def compileModel(self,model,modelArg): #NOTE: metrics are not used for training and therefor not really needed. The loss is the important one if ('optimizerOptions' in modelArg.keys()): #print() model.compile(optimizer=self.getOptimizer(modelArg['optimizer'],modelArg['optimizerOptions']), #tf.train.AdamOptimizer(0.001), loss=modelArg['loss'], metrics = ['acc']) #tf.keras.losses.categorical_crossentropy, else: model.compile(optimizer=modelArg['optimizer'], #tf.train.AdamOptimizer(0.001), loss=modelArg['loss'], metrics = ['acc']) #tf.keras.losses.categorical_crossentropy, #source: https://stackoverflow.com/questions/40496069/reset-weights-in-keras-layer def reset_weights(self, model): print("problem1") session = K.get_session() for layer in model.layers: if hasattr(layer, 'kernel_initializer'): layer.kernel.initializer.run(session=session) print("problem2") if hasattr(layer, 'bias_initializer'): layer.bias.initializer.run(session=session) print("problem3") def trainModel(self, paramSets, X, Y, valSplit=0.0, epochs=1, batchSize=None, visualize=False, saveLoc='', defaultInput=True): callBacks = [EarlyStopping(monitor='val_loss',patience=3,restore_best_weights=True)] if (visualize): callBacks.append(TensorBoard(log_dir='./logs', histogram_freq=3, write_graph=False, write_images=False, update_freq='epoch', profile_batch=2, embeddings_freq=0, embeddings_metadata=None)) modelFile = open(self.outputPath + "fileModel.csv", 'w') resultFile = open(self.outputPath + "fileResult.csv",'w') resultFile.write('modelNum|resultType|results\n') modelNum = 0 for paramSet in paramSets: modelFile.write(str(modelNum) + "|") json.dump(paramSet, modelFile) modelFile.write("\n") print("\n\n=================\nTraining Model " + str(modelNum) + "\n=================\n") #print(paramSet, flush=True) try: model = self.convModel(paramSet,defaultInput=defaultInput) print(model.summary()) #model.save_weights('temp_weights.h5') fitHistory = model.fit(X, Y, batch_size=batchSize, verbose=0, validation_split=valSplit, epochs=epochs,callbacks=callBacks ) #resultFile.write(fitHistory.history) #json.dump(fitHistory.history, resultFile) #resultFile.write("\n") for histItem in fitHistory.history: resultFile.write(str(modelNum) + '|' + histItem + '|' + '|'.join([str(item) for item in fitHistory.history[histItem]]) + '\n') modelWeightFile = saveLoc + f'{modelNum}.weights.h5' model.save_weights(modelWeightFile) #model.save(modelWeightFile) except Exception as e: print(str(e)) K.clear_session() modelNum+=1 if self.killer.kill_now: print("killed") break modelFile.close() resultFile.close() def parameterSearch(self, paramSets, X, Y, numSplits=2,valSplit=0.0, epochs=1, batchSize=None,saveModel=False, visualize=False, saveLoc=''): # create CV dat LOOV #numSplits = 2 Kf = StratifiedKFold(n_splits=numSplits) callBacks = [EarlyStopping(monitor='val_loss',patience=3,restore_best_weights=True)] if (visualize): callBacks.append(TensorBoard(log_dir='./logs', histogram_freq=3, write_graph=False, write_images=False, update_freq='epoch', profile_batch=2, embeddings_freq=0, embeddings_metadata=None)) #for each parameter set # make a model # #X = [0,1,2,3,4,5,6,7,8,9] modelFile = open(self.outputPath + "fileModel.csv", 'w') resultFile = open(self.outputPath + "fileResult.csv",'w') resultFile.write("modelNum|True REM|False REM|False NonREM|True NonREM|Acc|Sens|Spec|Recall|Precision|f1score|finalLoss\n") modelNum = 0 for paramSet in paramSets: modelFile.write(str(modelNum) + "|") json.dump(paramSet, modelFile) modelFile.write("\n") print("\n\n=================\nTesting Model " + str(modelNum) + "\n=================\n") print(paramSet, flush=True) try: model = self.convModel(paramSet) print(model.summary()) model.save_weights('temp_weights.h5') j = 0 for trainInd, testInd in Kf.split(X, np.argmax(Y,axis=1)): #print(f"fold: {j}") fitHistory = model.fit(X[trainInd], Y[trainInd], batch_size=batchSize, verbose=0, validation_split=valSplit, epochs=epochs,callbacks=callBacks ) if (saveModel): modelWeightFile = saveLoc + f'{modelNum}.{j}.weights.h5' model.save_weights(modelWeightFile) #model.save(modelWeightFile) Ypred = np.zeros((testInd.shape[0],Y.shape[1])) Yi = 0 for pred in np.argmax(model.predict(X[testInd], batch_size=None), axis=1): Ypred[Yi][pred] = 1 Yi += 1 #NOTE: #confusionMatrix = multilabel_confusion_matrix(Y[testInd], Ypred)[0] ##print(confusionMatrix) ##confusionMatrix = confusion_matrix(np.argmax(Y[testInd], axis=1), np.argmax(Ypred, axis=1)) ##print(confusionMatrix) ##print('f1_score:',f1_score(Y[testInd], Ypred, average='macro')) #resultFile.write(str(modelNum) + "|") ##for row in confusionMatrix: ## for el in row: ## resultFile.write(str(el) + "|") ##"modelNum|True REM|False NonREM|False REM|True NonREM|Acc|Sens|Spec|Recall|Precision|f1score\n" # #tn = confusionMatrix[0][0] #fn = confusionMatrix[1][0] #tp = confusionMatrix[1][1] #fp = confusionMatrix[0][1] tp=tn=fn=fp=0 Yi= 0 for y in Y[testInd]: tp += Ypred[Yi][0]*y[0] fp += max(Ypred[Yi][0]-y[0],0) tn += Ypred[Yi][1]*y[1] fn += max(Ypred[Yi][1]-y[1],0) Yi+=1 acc=sens=spec=prec=rec=f1=0 acc=(tp+tn)/(tp+tn+fp+fn) if (tp+fn > 0): sens=tp/(tp+fn) if (tn+fp > 0): spec=tn/(tn+fp) if (tp+fp > 0): prec=tp/(tp+fp) if (tp+fn > 0): rec=tp/(tp+fn) if (prec+rec > 0): f1=2*((prec*rec)/(prec+rec)) resultFile.write(f"{modelNum}|{tp:.3f}|{fp:.3f}|{fn:.3f}|{tn:.3f}|{acc:.3f}|{sens:.3f}|{spec:.3f}|{rec:.3f}|{prec:.3f}|{f1:.3f}|{fitHistory.history['loss'][-1]:10.3f}\n") print(f"{'Validate':10s}|{'modelNum':10s}|{'tp':10s}|{'fp':10s}|{'fn':10s}|{'tn':10s}|{'acc':10s}|{'sens':10s}|{'spec':10s}|{'rec':10s}|{'prec':10s}|{'f1':10s}|{'loss':10s}\n") print(f"{j:10d}|{modelNum:10d}|{tp:10.3f}|{fp:10.3f}|{fn:10.3f}|{tn:10.3f}|{acc:10.3f}|{sens:10.3f}|{spec:10.3f}|{rec:10.3f}|{prec:10.3f}|{f1:10.3f}|{fitHistory.history['loss'][-1]:10.3f}\n", flush=True) #resultFile.write(str(f1_score(Y[testInd], Ypred, average='macro')) + "|\n") model.load_weights('temp_weights.h5') #print("reset weights") #self.reset_weights(model) #print("reset weights") j+=1 except Exception as e: resultFile.write("error\n") print(str(e)) K.clear_session() modelNum+=1 if self.killer.kill_now: resultFile.write("killed\n") print("killed") break modelFile.close() resultFile.close() def testModel(self, paramSets,X,Y, weights=[], loadLoc=""): print("modelNum|weightSet|True REM|False REM|False NonREM|True NonREM|Acc|Sens|Spec|Recall|Precision|f1score") modelNum=0 for paramSet in paramSets: try: print("loading Model") model = self.convModel(paramSet) for weightSet in weights[modelNum]: print("loading: ", loadLoc + weightSet) model.load_weights(loadLoc + weightSet) Ypred = np.zeros((Y.shape[0],Y.shape[1])) Yi = 0 print("predicting") for pred in np.argmax(model.predict(X, batch_size=None), axis=1): Ypred[Yi][pred] = 1 Yi += 1 tp=tn=fn=fp=0 Yi= 0 for y in Y: tp += Ypred[Yi][0]*y[0] fp += max(Ypred[Yi][0]-y[0],0) tn += Ypred[Yi][1]*y[1] fn += max(Ypred[Yi][1]-y[1],0) Yi+=1 acc=sens=spec=prec=rec=f1=0 acc=(tp+tn)/(tp+tn+fp+fn) if (tp+fn > 0): sens=tp/(tp+fn) if (tn+fp > 0): spec=tn/(tn+fp) if (tp+fp > 0): prec=tp/(tp+fp) if (tp+fn > 0): rec=tp/(tp+fn) if (prec+rec > 0): f1=2*((prec*rec)/(prec+rec)) print(f"{modelNum}|{weightSet}|{tp:.3f}|{fp:.3f}|{fn:.3f}|{tn:.3f}|{acc:.3f}|{sens:.3f}|{spec:.3f}|{rec:.3f}|{prec:.3f}|{f1:.3f}") except Exception as e: print("ERROR",sys.exc_info()[0]) modelNum += 1 def printModel(self, paramSet, weightLoc, X=None): modelNum=0 try: print("paramSet") #print(paramSet) model = self.convModel(paramSet) print(paramSet) #pass print("loading: ", weightLoc) model.load_weights(weightLoc) model.predict(X, batch_size=None) return model.get_layer('conv1d1').get_weights() except Exception as e: print("ERROR",sys.exc_info()[0]) print(e) return None modelNum += 1 def getNorm(self, myDir): normSTD = normMean = None for filename in listdir(myDir): if 'fileTrainTestParams.txt' in filename: with open(myDir + filename) as pfile: for line in pfile: if ('normSTD' in line): normSTD = float(line.split(':')[1]) elif ('normMean' in line): normMean = float(line.split(':')[1]) return [normSTD, normMean] def getWeights(self,weights,myDir): currentID='' ids = [] cidList = {} for filename in listdir(myDir): if ('.h5' in filename): tid = int(filename.split('.')[0]) if (tid not in ids): ids.append(tid) cidList[tid] = [] cidList[tid].append(filename) for myid in sorted(ids): weights.append(cidList[myid]) def saveModelOutput(self, paramSets, X, Y, weights=[], saveLoc='',saveName='output.csv', loadLoc=''): modelNum = 0 predictions = [] print("modelNum|weightSet|True REM|False REM|False NonREM|True NonREM|Acc|Sens|Spec|Recall|Precision|f1score") for paramSet in paramSets: try: #print("loading Model", paramSet) model = self.convModel(paramSet) weightSet = weights[modelNum] #print("loading: ", loadLoc + weightSet) model.load_weights(loadLoc + weightSet) Ypred = np.zeros((Y.shape[0],Y.shape[1])) Yi = 0 #print("predicting") predictions.append(model.predict(X, batch_size=None)) for pred in np.argmax(predictions[-1], axis=1): Ypred[Yi][pred] = 1 Yi += 1 tp=tn=fn=fp=0 Yi= 0 for y in Y: tp += Ypred[Yi][0]*y[0] fp += max(Ypred[Yi][0]-y[0],0) tn += Ypred[Yi][1]*y[1] fn += max(Ypred[Yi][1]-y[1],0) Yi+=1 acc=sens=spec=prec=rec=f1=0 acc=(tp+tn)/(tp+tn+fp+fn) if (tp+fn > 0): sens=tp/(tp+fn) if (tn+fp > 0): spec=tn/(tn+fp) if (tp+fp > 0): prec=tp/(tp+fp) if (tp+fn > 0): rec=tp/(tp+fn) if (prec+rec > 0): f1=2*((prec*rec)/(prec+rec)) print(f"{modelNum}|{weightSet}|{tp:.3f}|{fp:.3f}|{fn:.3f}|{tn:.3f}|{acc:.3f}|{sens:.3f}|{spec:.3f}|{rec:.3f}|{prec:.3f}|{f1:.3f}") except Exception as e: print("ERROR",sys.exc_info()[0]) modelNum += 1 #for prediction in predictions: # TO DO STACK AND PRINT PREDICTIONS #print(np.array(predictions).shape) with open(saveLoc + saveName,'w') as saveFile: for i in range(len(predictions[0])): line = str(np.argmax(Y[i])) + '|' + '|'.join([str(pred) for pred in predictions[0][i]]) for j in range(1,5): line += '|' + '|'.join([str(pred) for pred in predictions[j][i]]) line += '\n' saveFile.write(line) #print(line) #allPred = np.concatenate(predictions, axis=1) #print(allPred.shape) #print(predictions[0]) def buildModelStack(self, X,Y,convModel=[],auto=[],mem=[],dense=[],order=[]): #X = np.array(X) #Y = np.array(Y) Xtensor = Input(shape=X.shape[1:]) print("Xtensor") print(X.shape) num_filters = 1 convLayers = [] #Delta Frequencies < 3Hz #high pass (no low pass needed) convLayers.append(Conv1D(filters=1, kernel_size=33, padding='same', activation='relu')(Xtensor)) # Filter to find good wavelets convLayers[-1] = Conv1D(filters=num_filters, kernel_size=66, padding='same', activation='relu')(convLayers[-1]) #Theta Frequencies 3.5-7.5 Hz #Low pass convLayers.append(Conv1D(filters=1, kernel_size=33, padding='same', activation='relu')(Xtensor)) #High pass convLayers[-1] = Conv1D(filters=1, kernel_size=13, padding='same', activation='relu')(convLayers[-1]) convLayers[-1] = Conv1D(filters=num_filters, kernel_size=20, padding='same', activation='relu')(convLayers[-1]) #Alpha Frequencies 7.5-13 Hz #Low pass convLayers.append(Conv1D(filters=1, kernel_size=13, padding='same', activation='relu')(Xtensor)) #High pass convLayers[-1] = Conv1D(filters=1, kernel_size=8, padding='same', activation='relu')(convLayers[-1]) convLayers[-1] = Conv1D(filters=num_filters, kernel_size=10, padding='same', activation='relu')(convLayers[-1]) #Beta(1) Frequencies 13-25 Hz #Low pass convLayers.append(Conv1D(filters=1, kernel_size=8 , padding='same', activation='relu')(Xtensor)) #high pass convLayers[-1] = Conv1D(filters=1, kernel_size=4, padding='same', activation='relu')(convLayers[-1]) convLayers[-1] = Conv1D(filters=num_filters, kernel_size=5, padding='same', activation='relu')(convLayers[-1]) #Beta(2) Frequencies > 25 Hz #Low pass convLayers.append(Conv1D(filters=1, kernel_size=4, padding='same', activation='relu')(Xtensor)) convLayers[-1] = Conv1D(filters=num_filters, kernel_size=3, padding='same', activation='relu')(convLayers[-1]) print("ConvLayers") flattenLayers = [] flattenModels = [] for convLayer in convLayers: flattenLayers.append(Flatten()(convLayer)) flattenModels.append(Model(Xtensor,flattenLayers[-1])) print("flattenLayers") denseLayers = [] for flattenLayer in flattenLayers: denseLayers.append(Dense(2, activation='softmax')(flattenLayer)) print("denseLayers") convTrainModels = [] for denseLayer in denseLayers: convTrainModels.append(Model(Xtensor,denseLayer)) convTrainModels[-1].compile(optimizer="adam",loss="categorical_crossentropy") convTrainModels[-1].fit(X,Y) print("convTrainModels") #encodeLayers = [] #for flattenLayer in flattenLayers: # encodeLayers.append(Dense(3000)(flattenLayer)) # print(flattenLayer.shape) #print("ensoderLayers") #decodeLayers = [] #for encodeLayer in encodeLayers: # decodeLayers.append(Dense(num_filters*3000)(encodeLayer)) #print("decodeLayers") #decoderModels = [] #for decodeLayer,flattenModel in zip(decodeLayers, flattenModels): # decoderModels.append(Model(Xtensor,decodeLayer)) # decoderModels[-1].compile(optimizer="adam",loss="mse") # decoderModels[-1].fit(X, flattenModel.predict(X)) #print("decodeModels") #print(convTrainModels) #classModel = Concatenate()([flattenLayer for flattenLayer in flattenLayers]) #classModel = Embedding( #classModel = Dense(100, activation="relu")(classModel) #classModel = Dense(100, activation="relu")(classModel) newData = np.hstack([convTrainModel.predict(X) for convTrainModel in convTrainModels]) Data = np.zeros(shape=(newData.shape[0]-2,10,10)) i=0 for n in np.arange(9,newData.shape[0],1): for j in np.arange(10): for k in np.arange(10): Data[i][j][k] = newData[n-j][k] i+=1 #Data = [[newData[n-2],newData[n-1],newData[n]] for n in np.arange(2,newData.shape[0],1)] #newData = np.ndarray([convTrainModel.predict(X).flatten() for convTrainModel in convTrainModels]).flatten('F') #print(Data.shape) print(Data[0]) #return timeTensor = Input(shape=[10,10]) classModel = LSTM(1000)(timeTensor) #classModel = Flatten()(classModel) classModel = Dense(2, activation="softmax")(classModel) classModel = Model(timeTensor, classModel) classModel.compile(optimizer="adam",loss="categorical_crossentropy") classModel.fit(Data,Y[2:]) print("ClassModel") Ypred = np.zeros((X.shape[0],Y.shape[1])) print("zeros") Yi = 0 for pred in np.argmax(classModel.predict(Data, batch_size=None), axis=1): Ypred[Yi][pred] = 1 Yi += 1 print("prediction") tp=tn=fn=fp=0 Yi= 0 for y in Y[2:]: tp += Ypred[Yi][0]*y[0] fp += max(Ypred[Yi][0]-y[0],0) tn += Ypred[Yi][1]*y[1] fn += max(Ypred[Yi][1]-y[1],0) Yi+=1 print("tp,tn,fp,fn") acc=sens=spec=prec=rec=f1=0 acc=(tp+tn)/(tp+tn+fp+fn) if (tp+fn > 0): sens=tp/(tp+fn) if (tn+fp > 0): spec=tn/(tn+fp) if (tp+fp > 0): prec=tp/(tp+fp) if (tp+fn > 0): rec=tp/(tp+fn) if (prec+rec > 0): f1=2*((prec*rec)/(prec+rec)) modelNum = 1 print(f"{'modelNum':8s}|{'tp':8s}|{'fp':8s}|{'fn':8s}|{'tn':8s}|{'acc':8s}|{'sens':8s}|{'spec':8s}|{'rec':8s}|{'prec':8s}|{'f1':8s}\n") print(f"{modelNum:8d}|{tp:8.3f}|{fp:8.3f}|{fn:8.3f}|{tn:8.3f}|{acc:8.3f}|{sens:8.3f}|{spec:8.3f}|{rec:8.3f}|{prec:8.3f}|{f1:8.3f}\n")
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,518
gtoban/kerasTimeSeries
refs/heads/master
/printResults.py
import pandas as pd import numpy as np import sys import json from os import walk, path, listdir def main(): if (len(sys.argv) < 2): print("id number required") exit(0) idNum = f"{int(sys.argv[1]):05d}" myDir = path.expanduser('~') + "/localstorage/kerasTimeSeries/modelResults" if (path.isdir(myDir)): myDir += "/" else: myDir = path.expanduser('~') for filename in listdir(myDir): if (idNum in filename): if ("Result" in filename): #False NonREM|True NonREM|Acc|Sens|Spec results = pd.read_csv(myDir + filename, sep='|')#, usecols=['modelNum','True REM','False REM']) #print(results['True REM'] > 0 results['f1Avg'] = results[['modelNum','f1score']].groupby('modelNum').transform(np.average) results['zeroSens']= results[['modelNum','Sens']].groupby('modelNum').transform(np.prod) results['zeroSpec']= results[['modelNum','Spec']].groupby('modelNum').transform(np.prod) results = results[results['modelNum'].isin(results[(results['zeroSens']>0) & (results['zeroSpec'] >0)]['modelNum'])] #results = results[(results["False REM"] > 0) | (results["True REM"] > 0)] if ("Model" in filename): models = pd.read_csv(myDir + filename, sep="|", header=None,names=['modelNum','model']) #print(filename) #return #models = models[models['modelNum'] in results['modelNum']] data = pd.merge(results,models,on='modelNum', how='inner') data[['tp_sum','tn_sum']] = data[['modelNum','True REM','False REM']].groupby('modelNum').transform(np.sum) data['t_ratio'] = np.divide(data['tp_sum'],data['tn_sum']+np.finfo(float).eps) data=data.sort_values(by=['f1Avg','modelNum'], ascending=False) print(f"modelNum|tp|fp |tratio|Spec NR|Sens R|kernelInit|biasInit|optimizer|kernelSize|numKernels|activation|pool|numDense|sizes") for index, row in data.iterrows(): modelInfo = json.loads(row['model']) modelNum = row['modelNum'] tp = int(row['True REM']) fp = int(row['False REM']) spec = float(row['Spec']) sens = float(row['Sens']) tratio = row['t_ratio'] kernelSize = 0 numKernels = 0 activation = "" pool = 'No' numDense = 0 denseNodes = [] kernelInit = 'glorot_uniform' biasInit = 'zeros' optimizer = 'adam' for layer in modelInfo: if (layer['layer'] == 'conv1d'): numKernels = int(layer['no_filters']) kernelSize = int(layer['kernal_size']) activation = layer['activation'] try: kernelInit = layer['kernel_initializer'] biasInit = layer['bias_initializer'] except: pass elif (layer['layer'] == 'dense'): numDense += 1 denseNodes.append(layer['output']) elif ('pool' in layer['layer']): pool = layer['layer'] elif('compile' in layer['layer']): try: optimizer = layer['optimizer'] except: pass print(f"{modelNum:3d}|{tp:3d}|{fp:3d}|{tratio:.3f}|{spec:.3f}|{sens:.3f}|{kernelInit}|{biasInit}|{optimizer}|{kernelSize:3d}|{numKernels:4d}|{activation:5s}|{pool:3s}|{numDense:3d}|" + ",".join([f"{size}" for size in denseNodes])) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,519
gtoban/kerasTimeSeries
refs/heads/master
/testRNN.py
import pandas as pd import numpy as np from kerasOOP import keras_ann, cnn_data import os import json from os import listdir numOfInputFiles = 5 def main(): print("Initializing") myAnn = keras_ann() myloc = os.path.expanduser('~') + "/kerasTimeSeries/myweights/rnn" myloc = '/nfshome/gst2d/localstorage/kerasTimeSeries/myweights/rnn' myData = cnn_data(dataPath= os.path.expanduser('~') + "/eegData/") tloc = myloc myloc += '/' for fname in listdir(myloc): if ('fileModel' in fname and '~' not in fname): useCandidate = myloc+str(fname) testing = True modelArgs = [] #getModels() small models only for now! #addToModels(modelArgs) print(useCandidate) mod = pd.read_csv(useCandidate, sep='|', header=0) print(mod.columns) for index, candidate in pd.read_csv(useCandidate, sep='|', header=0).iterrows(): modelArgs.append(json.loads(candidate["model"])) print(f"Number of Models: {len(modelArgs)}") weights = [] myAnn.getWeights(weights,myloc) print(weights) myAnn.updatePaths(outputPath = os.path.dirname(os.path.realpath(__file__)) + "/") myData.readData(fnames=inputData()) myAnn.testModel(modelArgs,myData.data,myData.labels,weights=weights,loadLoc=myloc) def inputData(): #this is the entire list #return np.array("input001.csv,input002.csv,input011.csv,input012.csv,input031.csv,input032.csv,input041.csv,input042.csv,input081.csv,input082.csv,input091.csv,input101.csv,input112.csv,input142.csv,input151.csv,input152.csv,input161.csv,input162.csv,input171.csv,input172.csv".split-(",")) #These choices were made by which ones had the most REM t = "outinput152.csv,outinput042.csv,outinput171.csv,outinput161.csv,outinput082.csv,outinput091.csv,outinput002.csv,outinput142.csv,outinput031.csv,outinput151.csv,outinput101.csv,outinput032.csv".split(",") return np.array(t[:max( min(numOfInputFiles,len(t)),2)]) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,520
gtoban/kerasTimeSeries
refs/heads/master
/getFrequencies.py
import numpy as np def main(): print("Initializing") myloc = os.path.expanduser('~') + "/kerasTimeSeries/" myData = ann_data(dataPath= os.path.expanduser('~') + "/eegData/") myAnn.updatePaths(outputPath = os.path.dirname(os.path.realpath(__file__)) + "/") testing = True if (testing): myData.readData() else: myData.readData(fnames=inputData()) fourier = np.ndarray(myData.fourierAll()) print (fourier.shape) print(fourier[0]) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,521
gtoban/kerasTimeSeries
refs/heads/master
/bestSore.py
import pandas as pd import numpy as np import sys import json from os import walk, path, listdir def main(): if (len(sys.argv) < 3): print("test ID range [min max) required") exit(0) try: amin = int(sys.argv[1]) amax = int(sys.argv[2]) if (amin >= amax): t = amin amin = amax amax = amin except Exception as e: print("Did not enter integer ranges like this: min max") exit(0) myDir = path.expanduser('~') + "/localstorage/kerasTimeSeries/modelResults" if (path.isdir(myDir)): myDir += "/" else: myDir = path.expanduser('~') dataColumns = ['modelNum', 'True REM', 'False REM', 'False NonREM', 'True NonREM','Acc', 'Sens', 'Spec', 'Recall', 'Precision', 'f1score', 'finalLoss','f1Avg', 'zeroSens', 'zeroSpec', 'model', 'testID'] candidates = pd.DataFrame(columns=dataColumns) #["testID","modelNum",'f1Avg',"model"] for id in range(amin,amax): idNum = f"{int(id):05d}" for filename in listdir(myDir): if (idNum in filename): if ("Result" in filename): #False NonREM|True NonREM|Acc|Sens|Spec results = pd.read_csv(myDir + filename, sep='|')#, usecols=['modelNum','True REM','False REM']) #print(results['True REM'] > 0 results['f1Avg'] = results[['modelNum','f1score']].groupby('modelNum').transform(np.average) results['zeroSens']= results[['modelNum','Sens']].groupby('modelNum').transform(np.prod) results['zeroSpec']= results[['modelNum','Spec']].groupby('modelNum').transform(np.prod) results = results[results['modelNum'].isin(results[(results['zeroSens']>0) & (results['zeroSpec'] >0)]['modelNum'])] #results = results[(results["False REM"] > 0) | (results["True REM"] > 0)] if ("Model" in filename): models = pd.read_csv(myDir + filename, sep="|", header=None,names=['modelNum','model']) data = pd.merge(results,models,on='modelNum', how='inner') data = data.assign(testID=idNum) #print(data.columns) candidates = candidates.append(data, ignore_index=True) candidates['f1Avg'] = candidates[['model','f1score']].groupby('model').transform(np.average) candidates['f1Med'] = candidates[['model','f1score']].groupby('model').transform(np.median) candidates['specAvg'] = candidates[['model','Spec']].groupby('model').transform(np.average) candidates['sensAvg'] = candidates[['model','Sens']].groupby('model').transform(np.average) candidates['sensMin'] = candidates[['model','Sens']].groupby('model').transform(np.min) candidates['accAvg'] = candidates[['model','Acc']].groupby('model').transform(np.average) candidates['recAvg'] = candidates[['model','Recall']].groupby('model').transform(np.average) candidates['precAvg'] = candidates[['model','Precision']].groupby('model').transform(np.average) candidates.drop_duplicates(subset=["model"],inplace=True) candidates=candidates.sort_values(by=['sensMin'], ascending=False) print(candidates[["testID","modelNum","f1Avg","model"]]) print(candidates.iloc[0]["model"]) for metric in ['f1Avg','f1Med','sensAvg','sensMin', 'recAvg', 'precAvg', 'accAvg']: top = 4 top = top if candidates.shape[0] > top else candidates.shape[0] print() print( '='*20) print( ' '*8,metric) print( '='*20) candidates=candidates.sort_values(by=[metric], ascending=False) print(f"testID|modelNum|f1Avg|f1Med|Spec NR|Sens R|acc|sensMin|Recall|Precision|kernelInit|biasInit|optimizer|optoptions|kernelSize|numKernels|activation|pool|numDense|sizes") print(f"testID|modelNum|f1Avg|f1Med|Spec NR|Sens R|acc|sensMin|Recall|Precision|kernelInit|biasInit|optimizer|optoptions|lstms|units|bidirectional|numDense|sizes") for index, row in candidates.iloc[:top].iterrows(): modelInfo = json.loads(row['model']) modelNum = row['modelNum'] testID = row['testID'] spec = float(row['specAvg']) sens = float(row['sensAvg']) f1Avg = row['f1Avg'] f1Med = row['f1Med'] acc, sensMin, recall, prec = (row['accAvg'],row['sensMin'],row['recAvg'],row['precAvg']) kernelSize = 0 numKernels = 0 activation = "" pool = 'No' numDense = 0 denseNodes = [] kernelInit = 'glorot_uniform' biasInit = 'zeros' optimizer = 'adam' optoptions = 'none' units = 0 lstms = 0 bidirectional = 'false' for layer in modelInfo: if (layer['layer'] == 'conv1d'): numKernels = int(layer['no_filters']) kernelSize = int(layer['kernal_size']) activation = layer['activation'] try: kernelInit = layer['kernel_initializer'] biasInit = layer['bias_initializer'] except: pass elif (layer['layer'] == 'dense'): numDense += 1 denseNodes.append(layer['output']) elif ('pool' in layer['layer']): pool = layer['layer'] elif('compile' in layer['layer']): try: optimizer = layer['optimizer'] except: pass try: optoptions = ','.join([ str(opt) for opt in layer['optimizerOptions']]) except: optoptions = 'none' elif ('lstm' in layer['layer']): lstms += 1 units = layer['units'] try: if (layer['wrapper'] == 'bidirectional'): bidirectional = 'true' except: pass #print(f"{testID}|{modelNum:3d}|{f1Avg:.3f}|{f1Med:.3f}|{spec:.3f}|{sens:.3f}|{acc:.3f}|{sensMin:.3f}|{recall:.3f}|{prec:.3f}|{kernelInit}|{biasInit}|{optimizer}|{optoptions}|{kernelSize:3d}|{numKernels:4d}|{activation:5s}|{pool:3s}|{numDense:3d}|" + ",".join([f"{size}" for size in denseNodes])) print(f"{testID}|{modelNum:3d}|{f1Avg:.3f}|{f1Med:.3f}|{spec:.3f}|{sens:.3f}|{acc:.3f}|{sensMin:.3f}|{recall:.3f}|{prec:.3f}|{kernelInit}|{biasInit}|{optimizer}|{optoptions}|{lstms}|{units}|{bidirectional}|{numDense:3d}|" + ",".join([f"{size}" for size in denseNodes])) candidates=candidates.sort_values(by=['sensAvg'], ascending=False) topten = candidates.iloc[:4] topten[["testID","modelNum","model"]].to_csv("topTwo.csv",sep="|",index=False,quoting=3) #csv.QUOTE_NONE main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,522
gtoban/kerasTimeSeries
refs/heads/master
/graphModel.py
import pandas as pd import numpy as np import json import os from os import listdir from kerasOOP import keras_ann, ann_data from modelBuilder import ModelBuilder import sys #NOTE: FLAG FOR TESTING SMALL MODELS ONLY!! smallModelOnly = True numOfInputFiles = 10 def main(): if (len(sys.argv) < 2): freqBand = 'theta' else: freqBand = sys.argv[1] print("Initializing") myAnn = keras_ann() mybuild = ModelBuilder() myloc = os.path.expanduser('~') + "/localstorage/kerasTimeSeries/" weightPath=os.path.expanduser('~') + "/localstorage/kerasTimeSeries/myweights/" + freqBand + "/" print("Collecting Models") weights = [] modelArgs = [] print("GET PARAMS") mybuild.getCandidates(modelArgs, fname=weightPath+"topTwo.csv", optimize = False) myAnn.getWeights(weights,weightPath) #============= # for collecting data #============= print("GET PARAMS") myData = ann_data(dataPath= os.path.expanduser('~') + "/eegData/") [normSTD, normMean] = myAnn.getNorm(weightPath) [lowFreq, highFreq, _] = ann_data.getFreqBand(freqBand) testing = True if (testing): myData.readData() else: pass#myData.readData(fnames=inputData()) #myData.filterFrequencyRange(low=lowFreq, high=highFreq) myData.expandDims() myData.normalize(normSTD=normSTD, normMean=normMean) #print(weights) print("PRINT MODEL") myAnn.printModel(modelArgs, weights=weights,printLoc=myloc, loadLoc=weightPath,X=myData.data,Y=myData.labels) print("DONE") main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,523
gtoban/kerasTimeSeries
refs/heads/master
/updateCandidates.py
import pandas as pd import numpy as np import sys import json from os import walk, path, listdir def main(): if (len(sys.argv) < 2): print("test ID required") exit(0) elif (len(sys.argv) < 3): amin = amax = -1 idNum = f"{int(sys.argv[1]):05d}" else: try: amin = int(sys.argv[1]) amax = int(sys.argv[2]) if (amin >= amax): t = amin amin = amax amax = amin except Exception as e: print("Did not enter integer ranges like this: min max") exit(0) myDir = path.expanduser('~') + "/localstorage/kerasTimeSeries/modelResults" if (path.isdir(myDir)): myDir += "/" else: myDir = path.expanduser('~') candidates = pd.read_csv("candidate.csv", sep="|") print(candidates) if (amin == -1): candidates = candidates[candidates['model'].isin(getPassingCandidates(myDir, idNum))] else: for tid in range(amin,amax): idNum = f"{int(sys.argv[1]):05d}" candidates = candidates[candidates['model'].isin(getPassingCandidates(myDir, idNum))] print(candidates) #candidates.to_csv("candidate.csv",sep="|",index=False,quoting=3) def getPassingCandidates(myDir, idNum): for filename in listdir(myDir): if (idNum in filename): #False NonREM|True NonREM|Acc|Sens|Spec if ("Result" in filename): results = pd.read_csv(myDir + filename, sep='|')#, usecols=['modelNum','True REM','False REM']) #print(results['True REM'] > 0 results['f1Avg'] = results[['modelNum','f1score']].groupby('modelNum').transform(np.average) results['zeroSens']= results[['modelNum','Sens']].groupby('modelNum').transform(np.prod) results['zeroSpec']= results[['modelNum','Spec']].groupby('modelNum').transform(np.prod) results = results[results['modelNum'].isin(results[(results['zeroSens']>0) & (results['zeroSpec'] >0)]['modelNum'])] #results = results[(results["False REM"] > 0) | (results["True REM"] > 0)] if ("Model" in filename): models = pd.read_csv(myDir + filename, sep="|", header=None,names=['modelNum','model']) data = pd.merge(results,models,on='modelNum', how='inner') data.drop_duplicates(subset=["modelNum"],inplace=True) return data['model'] main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,524
gtoban/kerasTimeSeries
refs/heads/master
/getCandidates.py
import pandas as pd import numpy as np import sys import json from os import walk, path, listdir def main(): if (len(sys.argv) < 3): print("test ID range [min max) required") exit(0) try: amin = int(sys.argv[1]) amax = int(sys.argv[2]) if (amin >= amax): t = amin amin = amax amax = amin except Exception as e: print("Did not enter integer ranges like this: min max") exit(0) myDir = path.expanduser('~') + "/localstorage/kerasTimeSeries/modelResults" if (path.isdir(myDir)): myDir += "/" else: myDir = path.expanduser('~') candidates = pd.DataFrame(columns=["testID","modelNum","model"]) for id in range(amin,amax): idNum = f"{int(id):05d}" for filename in listdir(myDir): if (idNum in filename): if ("Result" in filename): #False NonREM|True NonREM|Acc|Sens|Spec results = pd.read_csv(myDir + filename, sep='|')#, usecols=['modelNum','True REM','False REM']) #print(results['True REM'] > 0 results['f1Avg'] = results[['modelNum','f1score']].groupby('modelNum').transform(np.average) results['zeroSens']= results[['modelNum','Sens']].groupby('modelNum').transform(np.prod) results['zeroSpec']= results[['modelNum','Spec']].groupby('modelNum').transform(np.prod) results = results[results['modelNum'].isin(results[(results['zeroSens']>0) & (results['zeroSpec'] >0)]['modelNum'])] #results = results[(results["False REM"] > 0) | (results["True REM"] > 0)] if ("Model" in filename): models = pd.read_csv(myDir + filename, sep="|", header=None,names=['modelNum','model']) data = pd.merge(results,models,on='modelNum', how='inner') data = data.assign(testID=idNum) candidates = candidates.append(data[["testID","modelNum","model"]], ignore_index=True) candidates.drop_duplicates(subset=["testID","modelNum"],inplace=True) candidates.to_csv("candidate.csv",sep="|",index=False,quoting=3) #csv.QUOTE_NONE main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,525
gtoban/kerasTimeSeries
refs/heads/master
/kerasNN.py
import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv1D, Flatten print(tf.version.VERSION) print(tf.keras.__version__) model = Sequential() model.add(Conv1D(filters=32, kernel_size=10, activation="relu", input_shape=(3000,1))) #shape batch, steps, channels model.add(Conv1D(filters=16, kernel_size=10, activation="relu")) model.add(Flatten()) model.add(Dense(2, activation="softmax")) model.compile(optimizer=tf.train.AdamOptimizer(0.001), loss=tf.keras.losses.categorical_crossentropy, metrics=[tf.keras.metrics.categorical_accuracy]) record_count = 0 with open("input002.csv") as f: for line in f: if (line.strip()): record_count += 1 f = open("input002.csv") line = f.readline().strip() data = np.zeros((record_count,3000)) labels = np.zeros((record_count,2)) sample = 0 while (line): arow = line.split(",") labels[sample][1 if arow[0] == 'W' else 0] = 1 measure_count = 0 for ame in arow[1:]: data[sample][measure_count] = ame sample += 1 line = f.readline().strip() print("shape:", data.shape) data = np.expand_dims(data,axis=2) print("shape:", data.shape) model.fit(data, labels, epochs=1, batch_size=record_count)
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,526
gtoban/kerasTimeSeries
refs/heads/master
/tune.py
import pandas as pd import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv1D, Flatten from tensorflow.keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import RandomizedSearchCV from kerasOOP import keras_ann, ann_data import os import json #NOTE: FLAG FOR TESTING SMALL MODELS ONLY!! smallModelOnly = True numOfInputFiles = 5 def main(): print("Initializing") myAnn = keras_ann() myloc = os.path.expanduser('~') + "/kerasTimeSeries/" myData = ann_data(dataPath= os.path.expanduser('~') + "/eegData/") #0 1 2 3 4 freqBand = ['delta','theta','alpha','beta1','beta2'][4] [lowFreq, highFreq, kernelsize] = ann_data.getFreqBand(freqBand) lowFreq = highFreq = None # 0 1 2 3 useCandidate = ['', 'topTwo.csv', 'topTen.csv', 'candidate.csv'][3] testing = True optimizeOptimizer = False saveModel = True modelArgs = [] #getModels() small models only for now! #addToModels(modelArgs) print("Collecting Models") if (useCandidate == ''): addToModelsTest_FrequencyFilters(modelArgs, addConvFilters=False, manyFilters=False, numKeepIndexes=100, kernalPreset=kernelsize) else: getCandidates(modelArgs, fname=useCandidate, optimize = optimizeOptimizer) # myAnn.updatePaths(outputPath = os.path.dirname(os.path.realpath(__file__)) + "/") if (testing): myData.readData() else: myData.readData(fnames=inputData()) myData.filterFrequencyRange(low=lowFreq, high=highFreq) myData.expandDims() myData.normalize() dataFiles = ",".join(inputData()) cvFolds = 0 if saveModel else 10 valPerc = 0.10 epochs = 1 if saveModel else 100 batchSize = 32 if saveModel else int(((myData.record_count*(1-valPerc))/cvFolds)+1) with open("fileTrainTestParams.txt",'w') as params: params.write(f"dataFiles: {dataFiles}\ncvFolds: {cvFolds}\n") params.write(f"validation_split: {valPerc}\nepoch: {epochs}\n") params.write(f"batchSize: {batchSize}\n") params.write(f"frequency: {lowFreq} - {highFreq}\n") params.write(f"normSTD : {myData.normSTD}\n") params.write(f"normMean : {myData.normMean}") if (saveModel): myAnn.trainModel(modelArgs,myData.data,myData.labels, valSplit=valPerc, epochs=epochs, batchSize=batchSize, visualize=False, saveLoc=myloc) return if (testing): myAnn.parameterSearch(modelArgs[:10],myData.data,myData.labels,valSplit=0.10) else: myAnn.parameterSearch(modelArgs,myData.data,myData.labels,numSplits=cvFolds, valSplit=valPerc, epochs=epochs, batchSize=batchSize, saveModel=saveModel, visualize=False, saveLoc=myloc) def inputData(): #this is the entire list #return np.array("input001.csv,input002.csv,input011.csv,input012.csv,input031.csv,input032.csv,input041.csv,input042.csv,input081.csv,input082.csv,input091.csv,input101.csv,input112.csv,input142.csv,input151.csv,input152.csv,input161.csv,input162.csv,input171.csv,input172.csv".split-(",")) #These choices were made by which ones had the most REM t = "input152.csv,input042.csv,input171.csv,input161.csv,input082.csv,input091.csv,input002.csv,input142.csv,input031.csv,input151.csv,input101.csv,input032.csv".split(",") return np.array(t[:max( min(numOfInputFiles,len(t)),2)]) def getCandidates(modelArgs, fname="candidate.csv", optimize = False): for index, candidate in pd.read_csv(fname, sep='|').iterrows(): modelArgs.append(json.loads(candidate["model"])) if (optimize): numOfCandidates = len(modelArgs) for cid in range(numOfCandidates): c = modelArgs[cid] for layer in c: if (layer["layer"] == 'compile'): #['adam','sgd','rmsprop','nadam'] keepFirst = False try: if (len(layer['optimizerOptions']) > 0): keepFirst = True else: keepFirst = False except: keepFirst = False if (layer['optimizer'] == 'sgd'): addSGD(modelArgs, c, int(100/numOfCandidates), keepFirst) if (layer['optimizer'] == 'adam'): addAdam(modelArgs, c, int(100/numOfCandidates), keepFirst) if (layer['optimizer'] == 'nadam'): addNAdam(modelArgs, c, int(100/numOfCandidates), keepFirst) if (layer['optimizer'] == 'rmsprop'): addRMSprop(modelArgs, c, int(100/numOfCandidates), keepFirst) def addAdam(modelArgs, tmodel, numKeepIndexes, keepFirst): target = tmodel learningRates = [0.1,0.01,0.001,0.0001] beta1s = [0.98,0.99,0.999,0.9999] beta2s = [0.98,0.99,0.999,0.9999] amsgrads = [True,False] total = len(learningRates) * len(beta1s) * len(beta2s) * len(amsgrads) ci = 0 for i in range(len(target)): if (target[i]['layer'] == 'compile'): ci = i first = True keepIndexes = np.concatenate((np.array([0]),np.random.randint(1,total,size=numKeepIndexes-1))) index = 0 for lr, beta1, beta2, amsgrad in [(lr, beta1, beta2, amsgrad) for lr in learningRates for beta1 in beta1s for beta2 in beta2s for amsgrad in amsgrads]: if (index not in keepIndexes): index += 1 continue if (first): if (not keepFirst): target[ci]['optimizerOptions'] = [lr, beta1, beta2, amsgrad] else: target[ci]['optimizerOptions'] = [lr, beta1, beta2, amsgrad] modelArgs.append(target) first = False target = tmodel.copy() index += 1 def addNAdam(modelArgs, tmodel, numKeepIndexes, keepFirst): target = tmodel learningRates = [0.1,0.01,0.001,0.0001] beta1s = [0.98,0.99,0.999,0.9999] beta2s = [0.98,0.99,0.999,0.9999] total = len(learningRates) * len(beta1s) * len(beta2s) ci = 0 for i in range(len(target)): if (target[i]['layer'] == 'compile'): ci = i first = True keepIndexes = np.concatenate((np.array([0]),np.random.randint(1,total,size=numKeepIndexes-1))) index = 0 for lr, beta1, beta2 in [(lr, beta1, beta2) for lr in learningRates for beta1 in beta1s for beta2 in beta2s]: if (index not in keepIndexes): index += 1 continue if (first): if (not keepFirst): target[ci]['optimizerOptions'] = [lr, beta1, beta2] else: target[ci]['optimizerOptions'] = [lr, beta1, beta2] modelArgs.append(target) first = False target = tmodel.copy() index += 1 def addSGD(modelArgs,tmodel, numKeepIndexes, keepFirst): target = tmodel learningRates = [0.1,0.01,0.001,0.0001] momentums = [0.0,0.1,0.3,0.5,0.7,0.9,0.99] nesterovs = [True,False] total = len(learningRates) * len(momentums) * len(nesterovs) ci = 0 for i in range(len(target)): if (target[i]['layer'] == 'compile'): ci = i first = True keepIndexes = np.concatenate((np.array([0]),np.random.randint(1,total,size=numKeepIndexes-1))) index=0 for lr, mo, nesterov in [(lr, mo, nesterov) for lr in learningRates for mo in momentums for nesterov in nesterovs]: if (index not in keepIndexes): index += 1 continue if (first): if (not keepFirst): target[ci]['optimizerOptions'] = [lr, mo, nesterov] else: target[ci]['optimizerOptions'] = [lr, mo, nesterov] modelArgs.append(target) first = False target = tmodel.copy() index += 1 def addRMSprop(modelArgs,tmodel, numKeepIndexes, keepFirst): target = tmodel learningRates = [0.1,0.01,0.001,0.0001] rhos = [0.0,0.1,0.3,0.5,0.7,0.9,0.99] total = len(learningRates) * len(rhos) ci = 0 for i in range(len(target)): if (target[i]['layer'] == 'compile'): ci = i first = True keepIndexes = np.concatenate((np.array([0]),np.random.randint(1,total,size=numKeepIndexes-1))) index=0 for lr, rho in [(lr, rho) for lr in learningRates for rho in rhos]: if (index not in keepIndexes): index += 1 continue if (first): if (not keepFirst): target[ci]['optimizerOptions'] = [lr, rho] else: target[ci]['optimizerOptions'] = [lr, rho] modelArgs.append(target) first = False target = tmodel.copy() index += 1 def addToModelsTest_FrequencyFilters(modelArgs, addConvFilters=True, manyFilters = False , numKeepIndexes = 1000, kernalPreset=-1): useStartingDividers = False #low freq to high freq convFilters = { 66:[33], 20:[33,13], 10:[13,8], 5 :[8,4], 3 :[4] } if kernalPreset < 1: kernalSizes = [3,5,10,20,66] else: kernalSizes = [kernalPreset] if (manyFilters): numFilters = [20,50,100,200,500] else: numFilters = range(5,11,5) #use 5 and 10 only if (useStartingDividers): layerSizeStarters = range(1,11) else: layerSizeStarters = [10,50,100,200,400,800] layerSizeDecreases = range(1,6) hiddenLayers = range(1,11) poolTypes = ['maxpool1d','avgpool1d',None] poolSizes = [2,4,8,12,24] strideDownscaleFactors = [1,2,3,4,None] activationFunctions = ['relu','tanh','sigmoid'] kernelInitializers = ['zeros','ones','random_normal','random_uniform', 'glorot_normal','glorot_uniform','he_normal','he_uniform'] biasInitializers = ['zeros','ones','random_normal','random_uniform', 'glorot_normal','glorot_uniform','he_normal','he_uniform'] optimizers = ['adam','sgd','rmsprop','nadam'] totalSize = len(kernalSizes) * len(numFilters) * len(layerSizeStarters) totalSize *= len(layerSizeDecreases) * len(hiddenLayers) totalSize *= len(poolTypes) * len(poolSizes) * len(strideDownscaleFactors) print(f"totalSize: {totalSize}") keepIndexes = np.random.randint(0,totalSize,size=numKeepIndexes) index = 0 for kernalSize, numFilter, layerSizeStarter, layerSizeDecrease, hiddenLayer, poolType, poolSize, strideDownscaleFactor in [(kernalSize, numFilter, layerSizeStarter, layerSizeDecrease, hiddenLayer, poolType, poolSize, strideDownscaleFactor) for kernalSize in kernalSizes for numFilter in numFilters for layerSizeStarter in layerSizeStarters for layerSizeDecrease in layerSizeDecreases for hiddenLayer in hiddenLayers for poolType in poolTypes for poolSize in poolSizes for strideDownscaleFactor in strideDownscaleFactors]: #skip = layerSizeDecrease > max(2,hiddenLayer) skip = poolSize > kernalSize skip = skip and (numFilter > 20 and poolType is None) if (skip): continue if (index not in keepIndexes): index += 1 continue activation = activationFunctions[int(np.random.randint(0,len(activationFunctions)))] kernelInitializer = kernelInitializers[int(np.random.randint(0,len(kernelInitializers)))] biasInitializer = biasInitializers[int(np.random.randint(0,len(biasInitializers)))] optimizer = optimizers[int(np.random.randint(0,len(optimizers)))] modelArgs.append([]) if (addConvFilters): for convFilter in convFilters[kernalSize]: modelArgs[-1].append({ 'layer': 'conv1d', 'no_filters' : 1, 'kernal_size': convFilter, 'padding' : 'same', 'activation' : activation, 'kernel_initializer': kernelInitializer, 'bias_initializer': biasInitializer }) modelArgs[-1].append({ 'layer': 'conv1d', 'no_filters' : numFilter, 'kernal_size': kernalSize, 'padding' : 'same', 'activation' : activation, 'kernel_initializer': kernelInitializer, 'bias_initializer': biasInitializer }) if (poolType is not None): modelArgs[-1].append({ 'layer': poolType, 'pool_size': poolSize, 'strides':strideDownscaleFactor, 'padding':'valid' }) modelArgs[-1].append({ 'layer': 'flatten' }) if (useStartingDividers): layerSize = int((numFilter*3000)/layerSizeStarter) else: layerSize = layerSizeStarter for hid in range(hiddenLayer): modelArgs[-1].append({ 'layer': 'dense', 'output': layerSize, 'activation':activation, 'kernel_initializer': kernelInitializer, 'bias_initializer': biasInitializer }) layerSize = int(layerSize/layerSizeDecrease) if (layerSize < 5): break modelArgs[-1].append({ 'layer': 'dense', 'output': 2, 'activation':'softmax', 'kernel_initializer': kernelInitializer, 'bias_initializer': biasInitializer }) modelArgs[-1].append({ 'layer': 'compile', 'optimizer': optimizer, 'loss': 'categorical_crossentropy', 'metrics':['acc'] }) index += 1 def addToModels(modelArgs): #low freq to high freq modelArgs.append( [ { 'layer': 'conv1d', 'no_filters': 66, 'kernal_size':5, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 20, 'kernal_size':10, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 10, 'kernal_size':15, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 5, 'kernal_size':20, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 3, 'kernal_size':25, 'activation':'relu' },{ 'layer': 'flatten' },{ 'layer': 'dense', 'output': 2, 'activation':'softmax' },{ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }]) #high to low freq modelArgs.append( [ { 'layer': 'conv1d', 'no_filters': 3, 'kernal_size':25, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 5, 'kernal_size':20, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 10, 'kernal_size':15, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 20, 'kernal_size':10, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 66, 'kernal_size':5, 'activation':'relu' },{ 'layer': 'flatten' },{ 'layer': 'dense', 'output': 2, 'activation':'softmax' },{ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }]) layers5 = [{ 'layer': 'conv1d', 'no_filters': 3, 'kernal_size':25, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 5, 'kernal_size':20, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 10, 'kernal_size':15, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 20, 'kernal_size':10, 'activation':'relu' },{ 'layer': 'conv1d', 'no_filters': 66, 'kernal_size':5, 'activation':'relu' }] # A small model for each of the 5 conv layers with and without maxpooling. Potential preparation for ensemble. for layer in layers5: #without max pooling modelArgs.append([]) modelArgs[-1].append(layer) modelArgs[-1].append({ 'layer': 'flatten' }) modelArgs[-1].append({ 'layer': 'dense', 'output': 2, 'activation':'softmax' }) modelArgs[-1].append({ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }) #with max pooling modelArgs.append([]) modelArgs[-1].append(layer) modelArgs[-1].append({ 'layer': 'maxpool1d', 'pool_size': 10, 'strides':None, 'padding':'valid' }) modelArgs[-1].append({ 'layer': 'flatten' }) modelArgs[-1].append({ 'layer': 'dense', 'output': 2, 'activation':'softmax' }) modelArgs[-1].append({ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }) if smallModelOnly: return #Mix and match features randomly (5 convolution layers (order: 5->120, 4->120, 3->60, 2->20, total->320), maxPooling (5) (1600), number of dense layers (1-5) etc (nodes: 50,100,200,400,500,800)) possibleNumOfNodes = [50,100,200,400,500,800] possiblePoolSize = [5,10,20,40,80] for i in range(100): modelArgs.append([]) #how many conv layers numConLayers = np.random.randint(2,6) #add a random list of layers of specified length for layerIndex in np.random.randint(0,5,size=numConLayers): modelArgs[-1].append(layers5[layerIndex]) # add maxpooling? if (np.random.randint(2) == 1): modelArgs[-1].append({ 'layer': 'maxpool1d', 'pool_size': possiblePoolSize[np.random.randint(len(possiblePoolSize))], 'strides':None, 'padding':'valid'}) # add a flatten layer modelArgs[-1].append({ 'layer': 'flatten' }) # pick a random number of dense layers primarily picking 1 numDenseLayers = min(max(int(np.random.normal(1,scale=2.5)), 1),5) for layerNum in range(numDenseLayers-1): modelArgs[-1].append({ 'layer': 'dense', 'output': possibleNumOfNodes[np.random.randint(len(possibleNumOfNodes))], 'activation':'softmax'}) modelArgs[-1].append({ 'layer': 'dense', 'output': 2, 'activation':'softmax' }) modelArgs[-1].append({ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }) def getModels(): modelArgs = [] #modelArgs.append( # [ # { # 'layer': 'conv1d', # 'no_filters': 64, # 'kernal_size':10, # 'activation':'relu' # },{ # 'layer': 'conv1d', # 'no_filters': 32, # 'kernal_size':10, # 'activation':'relu' # },{ # 'layer': 'flatten' # },{ # 'layer': 'dense', # 'output': 2, # 'activation':'softmax' # },{ # 'layer': 'compile', # 'optimizer': 'adam', # 'loss': 'categorical_crossentropy', # 'metrics':['acc'] # }]) # #modelArgs.append( # [ # { # 'layer': 'conv1d', # 'no_filters': 128, # 'kernal_size':10, # 'activation':'relu' # },{ # 'layer': 'conv1d', # 'no_filters': 64, # 'kernal_size':10, # 'activation':'relu' # },{ # 'layer': 'flatten' # },{ # 'layer': 'dense', # 'output': 2, # 'activation':'softmax' # },{ # 'layer': 'compile', # 'optimizer': 'adam', # 'loss': 'categorical_crossentropy', # 'metrics':['acc'] # }]) #Automatic Sleep Stage Scoring with Single-Channel EEG Using CNNs modelArgs.append( [ { 'layer': 'conv1d', 'no_filters': 20, 'kernal_size':200, 'activation':'relu' },{ 'layer': 'maxpool1d', 'pool_size': 20, 'strides':None, 'padding':'valid' },{ 'layer': 'conv1d', 'no_filters': 400, 'kernal_size':20, 'activation':'relu' },{ 'layer': 'maxpool1d', 'pool_size': 10, 'strides':None, 'padding':'valid' },{ 'layer': 'flatten' },{ 'layer': 'dense', 'output': 500, 'activation':'relu' },{ 'layer': 'dense', 'output': 500, 'activation':'relu' },{ 'layer': 'dense', 'output': 2, 'activation':'softmax' },{ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }]) #THIS ONE IS TO BIG TO TRAIN ON ORION00 #Real-time human activity recognition from accelerometer data using CNN modelArgs.append( [ { 'layer': 'conv1d', 'no_filters': 196, 'kernal_size':12, 'activation':'relu' },{ 'layer': 'maxpool1d', 'pool_size': 4, 'strides':None, 'padding':'valid' },{ 'layer': 'flatten' },{ 'layer': 'dense', 'output': 500, 'activation':'relu' },{ 'layer': 'dense', 'output': 2, 'activation':'softmax' },{ 'layer': 'compile', 'optimizer': 'adam', 'loss': 'categorical_crossentropy', 'metrics':['acc'] }]) return modelArgs def f1_score(self, y_true, y_pred): true_neg = 0 true_pos = 0 false_neg = 0 flase_pos = 0 for i in len(y_true): true = np.argmax(y_true[i]) pred = np.argmax(y_pred[i]) if (pred == 1): if (true == pred): true_pos += 1 else: false_pos += 1 else: if (true == pred): true_neg += 1 else: false_neg += 1 precision = true_pos/(true_pos+false_pos) recall = true_pos/(true_pos+false_neg) return 2 * ((precision*recall)/(precision+recall)) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,527
gtoban/kerasTimeSeries
refs/heads/master
/makeConvData.py
import numpy as np import json from os import listdir, path from kerasOOP import ann_data, keras_ann def main(): # load models and weights print("Initializing") myAnn = keras_ann() mySaveLoc = path.expanduser('~') + "/eegData/" myLoadLoc = path.expanduser('~') + "/localstorage/kerasTimeSeries/myweights/" myData = ann_data(dataPath= path.expanduser('~') + "/eegData/") allWeights = [] models = [] freqs = ['delta','theta','alpha','beta1','beta2'] # there are several models to choose from, # manually choose the index of the model modelChoice = {} for freq in freqs: modelChoice[freq] = 0 modelChoice['delta'] = 1 for freq in freqs: weights = [] myAnn.getWeights(weights,myLoadLoc + freq) allWeights.append(myLoadLoc + freq + '/' + weights[modelChoice[freq]][0]) #print(weights) #print(weights[modelChoice[freq]][0]) for filename in listdir(myLoadLoc + freq): if 'Model' in filename: with open(myLoadLoc + freq + '/' + filename) as tfile: modelIdtemp = 0 while modelIdtemp < modelChoice[freq]: tfile.readline() modelIdtemp += 1 #print(f"model: {modelIdtemp}") models.append(json.loads(tfile.readline().split('|')[-1].strip())) #print(allWeights[-1], models[-1], '\n') t = "input081.csv,input091.csv,input011.csv,input162.csv,input002.csv,input171.csv,input151.csv,input031.csv,input041.csv,input152.csv,input142.csv,input101.csv,input042.csv,input012.csv,input032.csv,input112.csv,input161.csv,input001.csv,input082.csv,input172.csv".split(",") i = 0 for inputfile in t: print() print('='*16) print(inputfile) myData.readData(fnames=[inputfile]) [normSTD, normMean] = myAnn.getNorm(myLoadLoc + freq + '/') myData.expandDims() myData.normalize(normSTD=normSTD, normMean=normMean) myAnn.saveModelOutput(models,myData.data,myData.labels, weights=allWeights, saveLoc=mySaveLoc,saveName='out' + inputfile, loadLoc='') i += 1 # for every sourceFile # read file # convert to convData main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,528
gtoban/kerasTimeSeries
refs/heads/master
/storeFiles.py
import subprocess import datetime import sys import os def main(): if (len(sys.argv) < 2): print("id number required") exit(0) idNumI = int(sys.argv[1]) d = datetime.date.today() idDate = f"{idNumI:05d}.{d.year}{d.month:02d}{d.day:02d}." model = idDate + "fileModel.csv" result = idDate + "fileResult.csv" params = idDate + "fileTrainTestParams.txt" status = idDate + "status.txt" if (os.stat("fileModel.csv").st_size > 0): p = subprocess.Popen(["cp", "fileModel.csv", model]) if (os.stat("fileResult.csv").st_size > 0): p = subprocess.Popen(["cp", "fileResult.csv", result]) if (os.stat("fileTrainTestParams.txt").st_size > 0): p = subprocess.Popen(["cp", "fileTrainTestParams.txt", params]) if (os.stat("status.txt").st_size > 0): p = subprocess.Popen(["cp", "status.txt", status]) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,529
gtoban/kerasTimeSeries
refs/heads/master
/getFourier.py
import pandas as pd import numpy as np import os import json from kerasOOP import keras_ann, ann_data from matplotlib import pyplot as plt from sklearn.cluster import KMeans from scipy import stats #import progressbar numOfInputFiles = 5 def main(): myloc = os.path.expanduser('~') + "/kerasTimeSeries/" myData = ann_data(dataPath= os.path.expanduser('~') + "/eegData/") testing = True if (testing): myData.readData() else: myData.readData(fnames=inputData()) #myData.filterFrequencyRange(low=2, high=45, order=8) fourier = np.array(myData.fourierAll()) npnts = fourier.shape[1] #fourier = np.abs(fourier/npnts)**2 #fourier = np.abs(fourier)**2 topHowMany = fourier.shape[1] n_clusters = 5 getTopFreqs(myData, fourier, topHowMany = topHowMany, label = None, freqLims = [2,35], n_clusters = n_clusters) for label in myData.indToLab: getTopFreqs(myData, fourier, topHowMany = topHowMany, label = label, freqLims = [2,35], n_clusters = n_clusters) #print(fourier.shape) #print(fourier[0]) #mylegend = [] ##print(myData.labels[0]) ##print(myData.data[0][:30]) ##return # #for i in range(5): # plt.figure() # plt.plot(hz,np.abs(fourier[100]/npnts)**2) # #plt.figure() ##plt.figure() ##for i in range(5): ## plt.plot(myData.data[i]) ## #mylegend.append('R' if myData.labels[i][0] == 1 else 'NR') ##plt.legend(mylegend) #plt.show() def inputData(): #this is the entire list #return np.array("input001.csv,input002.csv,input011.csv,input012.csv,input031.csv,input032.csv,input041.csv,input042.csv,input081.csv,input082.csv,input091.csv,input101.csv,input112.csv,input142.csv,input151.csv,input152.csv,input161.csv,input162.csv,input171.csv,input172.csv".split-(",")) #These choices were made by which ones had the most REM t = "input152.csv,input042.csv,input171.csv,input161.csv,input082.csv,input091.csv,input002.csv,input142.csv,input031.csv,input151.csv,input101.csv,input032.csv".split(",") return np.array(t[:max( min(numOfInputFiles,len(t)),2)]) def getTopFreqs(data, tfourier, topHowMany = 5, label = None, freqLims = [None,None], n_clusters = 5): if label is not None: indices = np.where(data.obsLabels == data.labToInd[label]) fourier = np.copy(tfourier[indices]) #hz = hz[indices] print(f"for label: {label}") else: fourier = np.copy(tfourier) print(f"for all labels") npnts = tfourier.shape[1] srate = 100 hz = np.linspace(0,srate//2,npnts) topFreqs = np.zeros(topHowMany*fourier.shape[0]) low = 0 high = 0 print("Combining Frequencies") #bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength) count = 0 for f in fourier: if freqLims[0] is None and freqLims[1] is None: a = f thz = hz elif freqLims[1] is None: indices = np.where(hz > freqLims[0]) a = f[indices] thz = hz[indices] elif freqLims[0] is None: indices = np.where(hz < freqLims[1]) a = f[indices] thz = hz[indices] else: indices = np.where(hz > freqLims[0]) a = f[indices] thz = hz[indices] indices = np.where(thz < freqLims[1]) a = a[indices] thz = thz[indices] topmost = min(topHowMany,a.shape[0]) high += topmost if topmost > 0: if topmost == thz.shape[0]: topFreqs[low:high] = thz else: topFreqs[low:high] = thz[np.argsort(a)[-topmost:]] #topFreqs.append(thz[np.argsort(a)[-topmost:]]) low += topmost count += 1 #bar.update(count) print("clustering") kmeans = KMeans(n_clusters=n_clusters).fit(np.array(topFreqs).reshape((-1,1))) print(kmeans.cluster_centers_) print(stats.describe(topFreqs)) main()
{"/rnntune.py": ["/kerasOOP.py"], "/testRNN.py": ["/kerasOOP.py"], "/graphModel.py": ["/kerasOOP.py"], "/tune.py": ["/kerasOOP.py"], "/makeConvData.py": ["/kerasOOP.py"], "/getFourier.py": ["/kerasOOP.py"]}
41,562
Anonymous0064/CyberUserBot
refs/heads/master
/userbot/modules/lyrics.py
# CYBERUSERBOT - Luciferxz # import os import lyricsgenius import asyncio from userbot.events import register from userbot import CMD_HELP, GENIUS from userbot.cmdhelp import CmdHelp # ██████ LANGUAGE CONSTANTS ██████ # from userbot.language import get_value LANG = get_value("lyrics") # ████████████████████████████████ # @register(outgoing=True, pattern="^.lyrics(?: |$)(.*)") async def lyrics(lyric): if r"-" in lyric.text: pass else: await lyric.edit(LANG['WRONG_TYPE']) return if GENIUS is None: await lyric.edit( LANG['GENIUS_NOT_FOUND']) return else: genius = lyricsgenius.Genius(GENIUS) try: args = lyric.text.split('.lyrics')[1].split('-') artist = args[0].strip(' ') song = args[1].strip(' ') except: await lyric.edit(LANG['GIVE_INFO']) return if len(args) < 1: await lyric.edit(LANG['GIVE_INFO']) return await lyric.edit(LANG['SEARCHING'].format(artist, song)) try: songs = genius.search_song(song, artist) except TypeError: songs = None if songs is None: await lyric.edit(LANG['NOT_FOUND'].format(artist, song)) return if len(songs.lyrics) > 4096: await lyric.edit(LANG['TOO_LONG']) with open("lyrics.txt", "w+") as f: f.write(f"{LANG['LYRICS']} \n{artist} - {song}\n\n{songs.lyrics}") await lyric.client.send_file( lyric.chat_id, "lyrics.txt", reply_to=lyric.id, ) os.remove("lyrics.txt") else: await lyric.edit(f"{LANG['LYRICS']} \n`{artist} - {song}`\n\n```{songs.lyrics}```") return @register(outgoing=True, pattern="^.singer(?: |$)(.*)") async def singer(lyric): if r"-" in lyric.text: pass else: await lyric.edit(LANG['WRONG_TYPE']) return if GENIUS is None: await lyric.edit( LANG['GENIUS_NOT_FOUND']) return else: genius = lyricsgenius.Genius(GENIUS) try: args = lyric.text.split('.singer')[1].split('-') artist = args[0].strip(' ') song = args[1].strip(' ') except: await lyric.edit(LANG['GIVE_INFO']) return if len(args) < 1: await lyric.edit(LANG['GIVE_INFO']) return await lyric.edit(LANG['SEARCHING'].format(artist, song)) try: songs = genius.search_song(song, artist) except TypeError: songs = None if songs is None: await lyric.edit(LANG['NOT_FOUND'].format(artist, song)) return await lyric.edit(LANG['SINGER_LYRICS'].format(artist, song)) await asyncio.sleep(1) split = songs.lyrics.splitlines() i = 0 while i < len(split): try: if split[i] != None: await lyric.edit(split[i]) await asyncio.sleep(2) i += 1 except: i += 1 await lyric.edit(LANG['SINGER_ENDED']) return CmdHelp('lyrics').add_command( 'lyrics', ' <sənədçi adı> - <musiqi adı>', 'Musiqi sözlərini gətirər.', 'lyrics System Of a Down - Scince' ).add_command( 'singer', ' <sənədçi adı> - <musiqi adı>', 'Musiqi oxuyar.', 'singer System Of a Down - Scince' ).add()
{"/userbot/modules/lyrics.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/store.py": ["/userbot/events.py", "/userbot/__init__.py", "/userbot/main.py"], "/userbot/modules/glitcher.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/utils/__init__.py"], "/userbot/modules/github.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/stickers.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/main.py"], "/userbot/modules/memes.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/modules/admin.py"], "/userbot/modules/blacklist.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/usernames.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/afk.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/main.py"], "/userbot/modules/auto.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/events.py": ["/userbot/__init__.py"], "/userbot/modules/Reklam.py": ["/userbot/events.py"], "/userbot/modules/song.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/utils/__init__.py"], "/userbot/modules/social.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/shazam.py": ["/userbot/events.py", "/userbot/modules/shazam_helper/communication.py", "/userbot/modules/shazam_helper/algorithm.py"], "/userbot/modules/filter.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/tag.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/scrapers.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/utils/__init__.py"], "/userbot/modules/stick.py": ["/userbot/events.py"], "/userbot/modules/cybermisc.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/avtopp.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/ezanvakti.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/botfather.py": ["/userbot/events.py"], "/userbot/modules/unvoice.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/anti_spambot.py": ["/userbot/__init__.py"], "/userbot/modules/autopp.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/rename.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/utils/__init__.py"], "/userbot/modules/rgb.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/spotify.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/utils/chrome.py": ["/userbot/__init__.py"], "/userbot/utils/__init__.py": ["/userbot/utils/chrome.py"], "/userbot/modules/evaluators.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/notes.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/mention.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/qrcode.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/gdrive.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/qoroskop.py": ["/userbot/events.py"], "/userbot/modules/www.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/zip.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/utils/__init__.py"], "/userbot/modules/elan.py": ["/userbot/events.py"], "/main.py": ["/userbot/__init__.py"], "/userbot/modules/covid19.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/__helpme.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/vaxt.py": ["/userbot/events.py"], "/userbot/modules/dil.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/galeri.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/main.py", "/userbot/modules/sql_helper/galeri_sql.py"], "/userbot/modules/cevir.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/scrapers_bot.py": ["/userbot/events.py", "/userbot/__init__.py", "/userbot/modules/admin.py"], "/userbot/modules/remove_bg.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/admin.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/main.py", "/userbot/modules/sql_helper/gban_sql.py"], "/userbot/modules/dyno.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/fontlar.py": ["/userbot/events.py"], "/userbot/modules/spammer.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/rose.py": ["/userbot/events.py"], "/userbot/modules/many_bot.py": ["/userbot/events.py"], "/userbot/modules/shazam_helper/communication.py": ["/userbot/modules/shazam_helper/user_agent.py"], "/userbot/modules/sudo.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/degistir.py": ["/userbot/modules/sql_helper/mesaj_sql.py", "/userbot/__init__.py", "/userbot/events.py", "/userbot/main.py"], "/userbot/modules/pyarat.py": ["/userbot/events.py", "/userbot/helpers/p.py"], "/userbot/modules/pmpermit.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/main.py"], "/userbot/modules/alive.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/misc.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/durum.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/ocr.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/playstore.py": ["/userbot/events.py"], "/userbot/modules/snips.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/liste.py": ["/userbot/__init__.py", "/userbot/events.py", "/userbot/modules/sql_helper/gban_sql.py"], "/userbot/main.py": ["/userbot/__init__.py", "/userbot/modules/sql_helper/mesaj_sql.py", "/userbot/modules/sql_helper/galeri_sql.py"], "/userbot/modules/lydia.py": ["/userbot/events.py", "/userbot/__init__.py"], "/userbot/modules/clive.py": ["/userbot/__init__.py", "/userbot/events.py"], "/userbot/modules/aria.py": ["/userbot/__init__.py", "/userbot/events.py"]}