Esempio n. 1
0
    def _get_projects(data_path: str) -> List[Project]:
        project_ids = []
        if exists(data_path):
            project_ids.extend(sorted(listdir(data_path)))

        return [
            Project(data_path, project_id) for project_id in project_ids
            if Project.is_project(join(data_path, project_id))
        ]
Esempio n. 2
0
    def run(self, data_entity_lists: DataEntityLists):
        project_ids = []
        if exists(self.data_path):
            project_ids.extend(sorted(listdir(self.data_path)))

        projects = [
            Project(self.data_path, project_id) for project_id in project_ids
            if Project.is_project(join(self.data_path, project_id))
            and not self.__is_filtered(project_id, data_entity_lists)
        ]
        if not projects:
            logger = logging.getLogger("tasks.collect_projects")
            logger.warning("Filtered all projects!")

        return projects
Esempio n. 3
0
def create_project(event, context):
    """
    Creates new project from passed information.

    Expected data values(and their defaults):
        id(generates new uuid4 if none passed)
        name('')
        git_link('')
        contributors({})
        hours_goal(0)
        due_date(None)
        pledges({})

    :param event:
    :param context:
    :return: None
    """
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.info('got event{}'.format(event))

    data = json.loads(event['body'])
    #
    # gives Project class the responsibility for handling
    # data validation for the new Project, rather than
    # duplicating that code here.
    project = model.store_project(Project(**data))
    return {'statusCode': 200, 'body': json.dumps(project)}
    def onOpenRecentProject(self) -> None:
        """
		This slot is run when the user selects to open a recent project.
		
		:return: None
		:rtype: NoneType
		"""

        self.setProject(Project.load(self.sender().text()))
Esempio n. 5
0
def project_creation_handler():
    project_name = generate_name(style="hyphen")
    while current_user.get_project(project_name) is not None:
        project_name = generate_name(style="hyphen")
    db_sess = create_session()
    p = Project(project_name, current_user)
    db_sess.add(p)
    db_sess.commit()
    db_sess.close()
    return redirect(url_for("web_interface.project_view", name=project_name))
Esempio n. 6
0
    def __init__(self, base_path: str, project_id: str, version_id: str):
        self._base_path = base_path
        self.version_id = version_id
        self.project_id = project_id
        self.id = "{}.{}".format(project_id, version_id)

        from data.project import Project
        self.__project = Project(base_path, project_id)

        self.path = join(self.__project.path, Project.VERSIONS_DIR, version_id)
        self._version_file = join(self.path, ProjectVersion.VERSION_FILE)  # type: str
        self._misuses_dir = join(self.__project.path, Project.MISUSES_DIR)  # type: str
        self._YAML = {}
        self._MISUSES = None
        self._PATTERNS = None
Esempio n. 7
0
    def _browseForExistingProject(self) -> None:
        """
		Opens a file dialog when the user clicks on the existing project's "..." button to choose an
		existing .fcl file.
		
		:return: None
		:rtype: NoneType
		"""
        fileDialog = QFileDialog()
        fileDialog.setFileMode(QFileDialog.ExistingFile)
        fileDialog.setDirectory(expanduser("~"))
        fileDialog.setNameFilter("Facile Project File (*.fcl)")
        fileDialog.fileSelected.connect(
            lambda url: self._setOldProject(Project.load(url)))
        fileDialog.exec_()
    def onOpenProjectTriggered(self) -> None:
        """
		This slot is run when the user elects to open an existing project.
		
		A file dialog is open with the .fcl filter. Once the user selects a project, it will be loaded into Facile.
		
		:return: None
		:rtype: NoneType
		"""

        fileDialog = QFileDialog()
        fileDialog.setFileMode(QFileDialog.ExistingFile)
        fileDialog.setDirectory(os.path.expanduser("~"))
        fileDialog.setNameFilter("Facile Project File (*.fcl)")
        fileDialog.fileSelected.connect(
            lambda url: self.setProject(Project.load(url)))
        fileDialog.exec_()
Esempio n. 9
0
    def __init__(self, base_path: str, project_id: str, misuse_id: str):
        self._base_path = base_path
        self.project_id = project_id
        self.misuse_id = misuse_id
        self.id = "{}.{}".format(project_id, misuse_id)

        from data.project import Project
        self.__project = Project(base_path, project_id)

        self.path = join(self.__project.path, Project.MISUSES_DIR, misuse_id)
        self.misuse_file = join(self.path, Misuse.MISUSE_FILE)

        self.__location = None
        self.__fix = None

        self._YAML = None
        self._PATTERNS = []
Esempio n. 10
0
def job(context):
    bot = context.job.context.bot
    session = db_session.create_session()
    mail = session.query(Mail).get(context.job.context.user_data['chat_id'])
    parser = context.job.context.user_data['parser']
    updates = parser.get_updates(mail.projects[-1].id if mail.projects else None)
    if updates:
        new_projects = [upd['id'] for upd in updates if upd['id'] not in [p.id for p in mail.projects]]
        for p_id in new_projects:
            mail.projects.append(Project(id=p_id))
        if len(mail.projects) - 30 > 0:
            for _ in range(len(mail.projects) - 30):
                session.delete(mail.projects.pop(0))
        session.merge(mail)
        session.commit()
    for update in filter(lambda x: x['id'] in new_projects, updates[::-1]):
        message = '\n'.join([f'<b>{key}</b>: {val}' for key, val in list(update.items())[2:]])
        markup = InlineKeyboardMarkup([[InlineKeyboardButton('Открыть', url=update['url'])]])
        bot.send_message(mail.id, message, parse_mode=ParseMode.HTML,
                         disable_web_page_preview=True,
                         reply_markup=markup)
    session.close()
Esempio n. 11
0
    def __init__(self, project: Project, parent: QWidget = None):
        """
		Constructs a ManageProjectDialog object.
		
		:param parent: the widget to nest this dialog inside of. If None, this dialog will be a window.
		:type parent: PySide2.QtWidgets.QWidget
		"""

        super(ManageProjectDialog, self).__init__(parent)
        self.ui = Ui_ManageProjectDialog()
        self.ui.setupUi(self)
        self.setWindowTitle("Manage Project")

        self._project = project

        self.ui.locationEdit.setText(project.getProjectDir())
        self.ui.nameEdit.setText(project.getName())
        self.ui.descriptionEdit.setText(project.getDescription())
        self.ui.appEdit.setText(project.getExecutableFile())
        if project.getBackend() in backends:
            idx = backends.index(project.getBackend())
        else:
            idx = 2
        self.ui.backendEdit.setCurrentIndex(idx)
Esempio n. 12
0
    def setup(self):
        self.temp_dir = mkdtemp(prefix="mubench-test-project_")

        self.project_id = "-project-"
        self.project_path = join(self.temp_dir, self.project_id)
        self.uut = Project(self.temp_dir, self.project_id)
	def test_ComponentActionCodeGeneration(self):
		"""
		This function makes sure that the method signatures are generated
		correctly for any action with an arbitrary number of ports.
		"""

		app = QApplication([])

		proj = Project('test', 'test project', '', 'uia')
		tguim = proj.getTargetGUIModel()

		comp1 = Component(tguim)  # should have id 0
		comp2 = Component(tguim)  # should have id 1

		spec1 = ActionSpecification.fromFile('../../../database/component_actions/click.action')
		spec2 = ActionSpecification.fromFile('../../../database/component_actions/write.action')

		a1 = ComponentAction(comp1, spec1)
		a2 = ComponentAction(comp2, spec2)

		method1 =  '''\
	def _4_click(self) -> None:
		"""
		Left-click a component.

		:return: None
		:rtype: NoneType
		"""

		comp = self.findComponent(4)

		try:
			comp.set_focus()
			comp.click()
		except:
			print("The action 'click' was not executed correctly on component with ID 4. Please contact support to fix this issue.")

'''
		method2 = '''\
	def _5_write(self, value: str) -> None:
		"""
		Write to a component.

		:param value: Value to be written.
		:type value: str
		:return: None
		:rtype: NoneType
		"""

		comp = self.findComponent(5)

		try:
			comp.set_edit_text(value)
		except:
			print("The action 'write' was not executed correctly on component with ID 5. Please contact support to fix this issue.")

'''
		print([li for li in difflib.ndiff(a1.getMethod(), method1) if li[0] != ' '])

		print([li for li in difflib.ndiff(a2.getMethod(), method2) if li[0] != ' '])

		self.assertTrue(a1.getMethod().replace(" "*4, "\t").strip() == method1.replace(" "*4, "\t").strip())
		self.assertTrue(a2.getMethod().replace(" "*4, "\t").strip() == method2.replace(" "*4, "\t").strip())
	def test_ActionPipelineCodeGeneration(self):
		"""
		This function makes sure that the code is generated
		correctly for any action pipeline.
		"""
		app = QApplication([])

		proj = Project('test', 'test project', '', 'uia')
		tguim = proj.getTargetGUIModel()

		ap = ActionPipeline()  # should have id 0
		ap2 = ActionPipeline()  # should have id 1

		ap.setName('custom1')
		ap.setAnnotation('testing the first pipeline')

		p = pt.Port()
		p.setName("value")
		p.setDataType(str)
		p.setAnnotation("Value to be written.")
		p.setOptional(False)
		ap.addInputPort(p)

		ap2.setName('custom2')
		ap2.setAnnotation('testing the second pipeline')

		p1 = pt.Port()
		p1.setName("value")
		p1.setDataType(str)
		p1.setAnnotation("Value to be written.")
		p1.setOptional(False)
		ap2.addInputPort(p1)

		comp1 = Component(tguim)  # should have id 2
		comp2 = Component(tguim)  # should have id 3
		comp3 = Component(tguim)  # should have id 4
		comp4 = Component(tguim)  # should have id 5

		spec1 = ActionSpecification.fromFile('../../../database/component_actions/click.action')
		spec2 = ActionSpecification.fromFile('../../../database/component_actions/write.action')
		spec3 = ActionSpecification.fromFile('../../../database/component_actions/read.action')

		a1 = ComponentAction(comp1, spec1) #6 and so on
		a2 = ComponentAction(comp2, spec1)
		a3 = ComponentAction(comp3, spec2)
		a4 = ComponentAction(comp4, spec3)

		aw1 = ActionWrapper(a1, ap)
		aw2 = ActionWrapper(a2, ap)
		aw3 = ActionWrapper(a3, ap)
		aw5 = ActionWrapper(ap, ap2)
		aw4 = ActionWrapper(a4, ap2)

		ap.connect(p, aw3.getInputPorts()[0])
		ap2.connect(p1, aw5.getInputPorts()[0])

		method1 = '''\
	def custom1(self, value: str) -> None:
		"""
		testing the first pipeline

		:param value: Value to be written.
		:type value: str
		:return: None
		:rtype: NoneType
		"""

		self._6_click()
		self._7_click()
		self._8_write(value)

'''

		method2 = '''\
	def custom2(self, value: str) -> None:
		"""
		testing the second pipeline

		:param value: Value to be written.
		:type value: str
		:return: None
		:rtype: NoneType
		"""

		self.custom1(value)
		a = self._9_read()

'''

		print([li for li in difflib.ndiff(ap.getMethod(), method1) if li[0] != ' '])
		print(ap.getMethod())
		print([li for li in difflib.ndiff(ap2.getMethod(), method2) if li[0] != ' '])
		print(ap2.getMethod())

		self.assertTrue(ap.getMethod() == method1)
		self.assertTrue(ap2.getMethod() == method2)
Esempio n. 15
0
def create_project(project_id: str,
                   base_path: str = "-test-",
                   meta: Dict[str, Any] = None):
    project = Project(base_path, project_id)
    project._YAML = {} if meta is None else meta
    return project
Esempio n. 16
0
def create_project(project_id: str, base_path: str = "", meta: Dict[str, Any] = None):
    project = Project(base_path, project_id)
    project._YAML = meta
    return project
Esempio n. 17
0
    def accept(self) -> None:
        """
		This method is called when the user clicks the "OK" button.
		
		It will validate all of the user's input and show error messages if
		any information is invalid.
		
		:emits: projectCreated if a project was successfully created
		:return: None
		:rtype: NoneType
		"""

        name = self.ui.project_name_edit.text()
        description = self.ui.description_edit.toPlainText()
        projectDir = self.ui.project_folder_edit.text()
        appExe = self.ui.executable_file_edit.text()

        # clear error message
        self.ui.error_label.setText("")

        # detect any errors
        errors = []
        if not self.ui.project_name_edit.text():
            errors.append("Need project name")
        if not self.ui.description_edit.toPlainText():
            errors.append("Need project description")

        # Check for valid project directory.
        if not projectDir:
            errors.append("Need to select project folder")
        else:
            isAlreadyProject = False
            for file in os.listdir(projectDir):
                if file[-4:] == ".fcl":
                    isAlreadyProject = True
                    break

            if isAlreadyProject:
                errors.append(
                    "The selected project directory already belongs to a different project. Please select another."
                )

        # Check for valid target application executable
        if not appExe:
            errors.append("Need to select target application executable")
        else:
            if not isExecutable(appExe):
                errors.append("Target application must be an executable file.")
            elif not appBitnessMatches(appExe):
                pyBit = getPythonBitness()
                appBit = getExeBitness(appExe)
                errors.append(
                    "{} bit Python cannot control {} bit application".format(
                        pyBit, appBit))

        # Check for valid framework
        frameworkOption = self._radioBtnGroup.checkedButton()
        framework = frameworkOption.text()
        if frameworkOption == self.ui.option_Other:
            framework = self.ui.other_edit.text()
        if not framework:
            errors.append("Must specify which framework is being used")

        # check for valid backend
        backendWidget = frameworkOption.parentWidget()
        backend = ""
        if isinstance(backendWidget, QGroupBox):
            backend = backendWidget.title()
        else:
            # TODO: Get best backend for target application. (using function from TGUIIL)
            pass

        # if there are any errors, show them, then return.
        if len(errors) != 0:
            errMsg = "Errors:\n"
            for err in errors:
                errMsg += "\t" + err + "\n"
            self.ui.error_label.setText(errMsg)
            return

        # if there are no errors, create a new project, emit the projectCreated signal, and
        # call the super-class's accept method to perform the default behavior.
        else:
            newProject = Project(name,
                                 description,
                                 appExe,
                                 backend,
                                 projectDir=projectDir)
            self.projectCreated.emit(newProject)
            return QDialog.accept(self)
Esempio n. 18
0
 def test_accepts_project_path(self):
     create_file(join(self.project_path, Project.PROJECT_FILE))
     assert Project.is_project(self.project_path)
Esempio n. 19
0
 def test_rejects_non_project_path(self):
     assert not Project.is_project(self.temp_dir)