示例#1
0
 def Add_section(self):
     """Метод добавления нового отдела"""
     os.system("clear")
     # Проверка на заполненность списка отделов
     if self._count < self._size:
         # Добавление первого отдела
         if self._count == 0:
             section_name = ""
             # Ввод названия отдела
             while not section_name.isalpha():
                 os.system("clear")
                 section_name = input("Введите название отдела: ")
             new_section = Section(section_name)
             self._section.Set_right(new_section)
             self._count += 1
         # Добавление 2-го и более отдела
         else:
             search = ""
             # Поиск отдела
             while not search.isalpha():
                 os.system("clear")
                 print("Поиск отдела до или после которого хотите добавить")
                 search = input("Название отдела: ")
             choice = 0
             # Выбор добавления до или после
             while choice != 1 and choice != 2:
                 # Защита от ввода букв
                 try:
                     print("1 - добавить до\n2 - добавить после")
                     choice = int(input("Ваш ответ: "))
                 except ValueError:
                     os.system("clear")
                     print("Ошибка! Введите число 1 или 2")
             finded_section = self.Check_add_section(search, choice)
             # Отдел найден
             if finded_section != False:
                 new_name = ""
                 # Ввод названия нового отдела
                 while not new_name.isalpha():
                     new_name = input("Введите название отдела: ")
                 new_section = Section(new_name)
                 new_section.Set_right(finded_section.Get_right())
                 finded_section.Set_right(new_section)
                 self._count += 1
             # Отдел не найден
             else:
                 print("Отдел не найден!")
     # Список заполнен
     else:
         print("Количество отделов заполнено")
示例#2
0
def find_sections(image, border, sections, board_settings):
    thresholded = utils.threshold(image, board_settings["grid_color"])
    dilated = utils.dilate(thresholded,
                           iter_num=int(board_settings["dilation"]))
    eroded = utils.erode(dilated, iter_num=int(board_settings["erosion"]))
    black_sections = cv2.bitwise_or(eroded, border)

    white_sections = cv2.bitwise_not(black_sections)

    im, contours, hierarchy = cv2.findContours(white_sections.copy(),
                                               cv2.RETR_EXTERNAL,
                                               cv2.CHAIN_APPROX_NONE)
    contours = sorted(contours, key=cv2.contourArea, reverse=True)

    for i in range(len(contours)):
        if cv2.contourArea(contours[i]) * int(board_settings[
                "min_section_scale"]) > image.shape[0] * image.shape[1]:

            section_num = i + 1
            cimg = np.zeros_like(white_sections)
            cv2.drawContours(cimg, contours, i, color=255, thickness=-1)
            rect = cv2.boundingRect(contours[i])

            sections[str(section_num)] = Section(cimg, str(section_num), rect)
        else:
            break

    return sections
示例#3
0
def create_section_from_info(info):
    section = Section(info["start_point"], get_end_point(), info["is_steps"], 0, info["ground_type"])
    if "steps_num" in info.keys():
        section.steps_num = info["steps_num"]
    if "rail" in info.keys():
        section.rail = info["rail"]
    return section
示例#4
0
    def __init__(self, fileName, keys, stick, stones, helps, ball, bar, rightBall, level, game):
        """
        Initialize a challenge

	        @param self -- the challenge
            @param fileName -- a string that contains the sound name 
            @param keys -- the key vector
            @param stick -- the stick
            @param stones -- the stones
            @param helps -- the helps
            @param ball -- the left ball that it is used in the animation
            @param bar -- the grey bar that it is used in the animation
            @param rightBall -- the right ball that it is used in the animation
            @param level -- the challenge level
            @param game -- the game
	    
		"""
		
        self.fileName = fileName
        self.music = Sound()
        self.music.setFileName("sound/music/" + fileName)
        self.section = Section()
        self.section.setFileName("sound/section/" + fileName)
        self.section.setKeys(keys)
        self.stick = stick
        self.animation = Animation(stones, keys, helps, ball, rightBall, bar, game)
        self.ball = ball
        self.level = level
        self.attempts = 0
        self.game = game
示例#5
0
    def get_note_and_section_name(self, section_name):
        note_name = self.get_text("یادداشت جدید", "نام یادداشت:")
        if not note_name:
            reply = QMessageBox.question(
                self, 'پیام', "نام خالی است. دوباره امتحان میکنید؟",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.get_note_and_section_name()
            else:
                return

        if section_name is None:
            section_name = self.get_text("بخش", "نام بخش:")
            if not note_name:
                reply = QMessageBox.question(
                    self, 'پیام', "نام بخش خالی است. دوباره امتحان میکنید؟",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if reply == QMessageBox.Yes:
                    self.get_note_and_section_name()
                else:
                    return

        section = None
        for s in self.notebook.sections:
            if s.name == section_name:
                section = s

        if section is None:
            section = Section(section_name)
            self.notebook.add_section(section)

        note = Note(note_name, "")
        section.add_note(note)
        return note, section_name
示例#6
0
def populateSections(newsDate, articlesInSection):
    """Returns a list of Section objects """
    sections = []
    for section_title, articles in list(articlesInSection.items()):
        sectionObj = Section(section_title,articles, newsDate)
        sections.append(sectionObj)
    
    return sections
示例#7
0
def load_sections(filename):
    filepath = basepath + filename
    df = pandas.read_csv(filepath)

    sections = {}
    for _, row in df.iterrows():
        section = Section(row['SEC11'], row['lat'], row['lon'])
        sections[row['SEC11']] = section

    return sections
示例#8
0
    def __init__(self, json_data):
        self.boardNum = 0
        self.array = []
        self.lowProbabilityCell = None
        self.newSolvedQueue = []
        self.oldSolvedQueue = []
        self.sections = []

        # Populate cells onto the board
        for row in range(9):
            row_array = []
            for col in range(9):
                row_array.append(Cell(row, col))
            self.array.append(row_array)

        # Set initial conditions
        for jsonObj in json_data:
            self.array[jsonObj['row']][jsonObj['column']].set_value(
                jsonObj['value'])
            self.newSolvedQueue.append(
                self.array[jsonObj['row']][jsonObj['column']])

        # Setup sections
        for rowSection in range(3):
            for colSection in range(3):
                current_section = []
                for actualRow in range(3):
                    for actualCol in range(3):
                        current_section.append(
                            self.array[rowSection * 3 +
                                       actualRow][colSection * 3 + actualCol])
                self.sections.append(Section(current_section))
        for rowSection in range(9):
            current_section = []
            for curCol in range(9):
                current_section.append(self.array[rowSection][curCol])
            self.sections.append(Section(current_section))
        for colSection in range(9):
            current_section = []
            for curRow in range(9):
                current_section.append(self.array[curRow][colSection])
            self.sections.append(Section(current_section))
示例#9
0
	def setSound(self, sectionFileName):
		"""
        Set a sound ball

    		@param self -- the ball
            @param sectionFileName -- a related section filename  
	    
		"""
		self.sectionFileName = sectionFileName
		self.section = Section()
		self.section.setFileName("sound/section/" + sectionFileName)
示例#10
0
    def json_to_notebook(nb):
        nb = json.loads(nb)
        notebook = Notebook(nb[0])

        for s in nb[1]:
            print(s[0])
            notebook.add_section(Section(s[0]))
            for n in s[1]:
                print(n)
                notebook.sections[-1].add_note(Note(n[0], n[1]))
        return notebook
    def createSection(self, boardId, sectionTitle):
        section = Section(title=sectionTitle)

        section.save()

        sectionId = section.id
        board = self.__getBoardById(boardId)

        board.addSectionId(sectionId)

        return sectionId
示例#12
0
def parse_section(soup, section_number):
    curr_section = Section()
    curr_section.section_number = section_number
    curr_section.type = get_soup_string_value(soup.find("type"))

    curr_section.days_of_the_week = get_soup_string_value(
        soup.find("daysoftheweek"))
    startString = get_soup_string_value(soup.find("start"))
    curr_section.start_time = parse_time(startString)
    endString = get_soup_string_value(soup.find("end"))
    curr_section.end_time = parse_time(endString)
    return curr_section
示例#13
0
    def handle_add_section(self):
        section_name = self.get_text("بخش جدید", "نام بخش:")
        if not section_name:
            reply = QMessageBox.question(
                self, 'پیام', "نام بخش خالی است. دوباره امتحان میکنید؟",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.handle_add_section()
            else:
                return

        self.notebook.add_section(Section(section_name))
        self.network.update_notebook(self.notebook)
示例#14
0
 def __init__(self, name, size):
     """Инициализация Организации
     Параметры функции:
         - name - название организации
         - size - количество отделов
     Свойства:
         _name - название организации
         _size - максимальное количество отделов
         _section - ссылка на список отделов
         _count - количество добавленных отделов"""
     self._name = name
     self._size = size
     self._section = Section("start")
     self._count = 0
示例#15
0
 def Download_from_file(self):
     """Загрузка из файла"""
     self.All_dell()
     section = self._section
     # Обработчик исключений
     try:
         new_line = ""
         # Открытие файла data.txt на чтение
         with open("data.txt", "r") as f:
             # Проход по строкам файла
             while True:
                 new_line = f.readline()
                 new_line = new_line.strip(" \n")
                 # Если строка пуста, то завершается загрузка из файла
                 if len(new_line) == 0:
                     break
                 # Строка содержит метку отдела
                 if new_line == "Отдел:":
                     new_line = f.readline()
                     new_line = new_line.strip(" \n")
                     # проверка на наличие ошибок в названии отдела
                     if not new_line.isalpha():
                         print("Ошибка в названии отдела в файле!")
                         break
                     # Добавление отдела, если список не заполнен
                     if self._count < self._size:
                         new_section = Section(new_line)
                         section.Set_right(new_section)
                         section = new_section
                         self._count += 1
                     # Максимальное количество отделов заполнено
                     else:
                         print("Ошибка! Число отдедов превышено.")
                         break
                 # Строка содержит метку сотрудника
                 elif new_line == "Сотрудник:":
                     new_line = f.readline()
                     new_line = new_line.strip(" \n")
                     major_line = f.readline()
                     major_line = major_line.strip(" \n")
                     # Данные полей сотрудника имеют ошибки
                     if not new_line.isalpha() or not major_line.isalpha():
                         print("Ошибка в файле!В полях сотрудника должны быть только буквы!")
                         break
                     section.Download_add(new_line, major_line)
                 # Строка не равна ни одной метке
                 else:
                     print("Ошибка!")
     except FileNotFoundError:
         print("Файл не найден в данной директории!")
 def __init__(self, survey_name):
     self.survey_sections = {}
     self.survey_name = survey_name
     self.user_q_answers = []
     self.eligiable_section = 'You are not qualified'
     self.questions_section_1 = [
         'Q1-1?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
         'Q1-2?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
         'Q1-3?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
     ]
     self.section_1 = Section(
         'section1',
         'This is section 1 and because of the quilifying question 1',
         self.questions_section_1)
     self.questions_section_2 = [
         'Q2-1?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
         'Q2-2?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
         'Q2-3?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
     ]
     self.section_2 = Section(
         'section2',
         'This is section 2 and because of the quilifying question 2',
         self.questions_section_2)
     self.questions_section_3 = [
         'Q3-1?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
         'Q3-2?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
         'Q3-3?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n',
     ]
     self.section_3 = Section(
         'section3',
         'This is section 3 and because of the quilifying question 3',
         self.questions_section_3)
     self.survey_sections = {
         0: self.section_1,
         1: self.section_2,
         2: self.section_3
     }
示例#17
0
 def default(self, d):
     if d is None:
         return None
     if 'name' in d and 'section_list' in d:
         object = Course(d)
         section_list_dict = d["section_list"]
         object.section_list = list()
         for section_dict in section_list_dict:
             object.section_list.append(self.default(section_dict))
         return object
     elif 'section_number' in d and 'type' in d:
         object = Section(d)
         return object
     else:
         return d
示例#18
0
    def load_sections(self):
        """
        This method will load all of the sections to the template.
        Each section will become its own attribute according to the template
        e.g. logon_username section will turn into t.logon_username which is type(t.logon_username) == Sections()
        """
        config = RawConfigParser()
        config.read(self.file_path)
        sections = config._sections

        for sec in sections:
            new_section = Section()
            new_section.set_name(sec)
            new_section.template = self
            for attr in sections[sec]:
                new_section.set_attribute(attr, sections[sec][attr])
            setattr(self, sec, new_section)
示例#19
0
    def test_get_global_stiffness(self):
        true = self.assertTrue
        n1 = Node(1, Point())
        n2 = Node(2, Point(4, 3, 0))
        section = Section(1, 0, 1000, 0, 0.1, 0, 0.001, 0)
        beam = Beam2D(1, n1, n2, section, 0)

        q = beam.get_global_stiffness('pos_origin')
        a = array([[12.83456, 9.55392, 0.144, -12.83456, -9.55392, 0.144],
                   [9.55392, 7.26144, -0.192, -9.55392, -7.26144, -0.192],
                   [0.144, -0.192, 0.8, -0.144, 0.192, 0.4],
                   [-12.83456, -9.55392, -0.144, 12.83456, 9.55392, -0.144],
                   [-9.55392, -7.26144, 0.192, 9.55392, 7.26144, 0.192],
                   [0.144, -0.192, 0.4, -0.144, 0.192, 0.8]])
        for i in range(6):
            for j in range(6):
                true(isclose(q[i, j], a[i, j]))
示例#20
0
    def test_get_internal_force(self):
        true = self.assertTrue
        n1 = Node(1, Point())
        n2 = Node(2, Point(4, 3, 0))
        section = Section(1, 0, 1000, 0, 0.1, 0, 0.001, 0)
        beam = Beam2D(1, n1, n2, section, 0)
        dofs1 = beam.node1.dofs

        dofs1[0].d = 0.1
        dofs1[1].d = 0.1

        force = beam.get_internal_force('d', 'pos_origin')
        ans = array([[2.238848], [1.681536], [-0.0048], [-2.238848],
                     [-1.681536], [-0.0048]])

        for i in range(6):
            true(isclose(force[i, 0], ans[i, 0]))
示例#21
0
    def __init__(self, config):
        """ 
            The class is initialized with a path to a configuration file passed 
            via config, or a file-like object.
        """
        self.parser = SafeConfigParser()

        if isinstance(config, basestring):
            self.config_path = config
            config = open(self.config_path, "r")
        else:
            self.config_path = None

        self.parser.readfp(config)

        for section in self.parser.sections():
            options = self.parser.items(section)
            options = map(lambda op: Option(*op), options)
            self.add_section(Section(section, options))
示例#22
0
    def add_section(self, section):
        """
            Adds a new section to the config. If section is str, it's converted
            to Section object. If section is Section, it's left untouched. 

            If a section with the same name does not already exists in the 
            config, it's added, and the function returns True. If such section 
            already exists, the call is ignored, and the function return False.
        """
        if isinstance(section, Section):
            section_name = section.name
        elif isinstance(section, str):
            section_name = section
            section = Section(section)
        else:
            raise TypeError("section should be either str or Section")

        if not self.__dict__.has_key(section_name):
            setattr(self, section_name, section)
            return True
        else:            
            return False
示例#23
0
    )

    # under construction
    # 目標はradare2の劣化版みたいな解析機能
    parser.add_argument("--detail",
                        help="analyze binary for detail information",
                        action="store_true")

    args = parser.parse_args()

    # analyze binary
    # todo: 不要な解析を無視
    elf = ELF(args.elf)  # _write4
    libc = ELF(args.libc) if args.libc else None

    sect = Section(elf)
    functions = Functions(elf)
    plt = elf.plt
    got = elf.got

    # dump simple
    if not args.symbols:
        print("")
        # dump sections
        print("[+]: all sections")
        sect.dump_all_sections()

        print("")
        # all functions
        # todo: 関数の中身を調べる方法(ローカル変数の数やできるなら初期値も調べたい)
        print("[+]: all functions")
    Question('Question 2', '(a) \n(b) \n(c) \n(d) \n'),
    Question('Question 3', '(a) \n(b) \n(c) \n(d) \n')
]

# Create a new instance of the Survey class called my_survey and pass it the qualifying questions
my_survey = Survey(qualifying_questions)

# Run the start survey method on the new instance of Survey
my_survey.start_survey()

# Run the ask qualifying questions method
my_survey.ask_qualifying_questions()

# Create a new instance of the Section class called wednesday_section
wednesday_section = Section(
    'This section will ask you 3 questions about the Wednesday night tutorials',
    wednesday_questions)
saturday_section = Section(
    'This section will ask you 3 questions about the Saturday workshops',
    saturday_questions)

# Run the wednesday section IF qualifying question 1 was answered with 'a'
if my_survey.user_answers_qualifying[0] == 'a':
    wednesday_section.start_wednesday_section()
else:
    print('Catch up section')

if my_survey.user_answers_qualifying[1] == 'a':
    saturday_section.start_saturday_section()
else:
    print('Catch up section')
示例#25
0
 def setUp(self):
     n1 = Node(1, Point(0, 0, 0))
     n2 = Node(2, Point(0, 1, 0))
     material = Section(1, 1.0, 10000, 0, 100, 1000, 1000, 2000)
     rayleigh = 'damping'
     self.beam = Beam2D(1, n1, n2, material, rayleigh)
示例#26
0
redis = redis.Redis()

sections = {}
section = {}
turnout = {}
sensor = {}
signal = {}
train = {}

# Set up Sections
for s_in in data["sections"]:
    try:
        s_in["currentDirection"]
    except:
        s_in["currentDirection"] = False
    section[s_in["id"]] = Section(s_in["id"], s_in["directions"],
                                  s_in["currentDirection"])
    sections[section[s_in["id"]]] = 1

for s_in in data["turnouts"]:
    turnout[s_in["id"]] = Turnout(s_in["id"], s_in["section"], redis,
                                  "turnout_action")
    section[s_in["section"]].setTurnout(turnout[s_in["id"]])

# Iterate over the sections in the config to set next and previous, which is ALSO an ITTERATION!
# This does not define which section is connected!
for s_in in data["sections"]:
    try:
        s_in["forward"]
    except:
        pass
    else:
示例#27
0
 def update(self, *args, **kwargs):
     for arg in args:
         # String argument
         if type(arg) == type(''):  # Possible path to XML?
             import pyrecon.tools.handleXML as xml
             try:  # given full path to .ser file
                 self.update(*xml.process(arg))
                 self.path = arg
                 self.name = arg.split('/')[len(arg.split('/')) -
                                            1].replace('.ser', '')
             except:  # given directory path instead of path to .ser file
                 path = arg
                 if path[-1] != '/':
                     path += '/'
                 path = path + str(
                     [f for f in os.listdir(path) if '.ser' in f].pop())
                 self.update(*xml.process(path))
                 self.path = path
                 self.name = path.split('/')[len(path.split('/')) -
                                             1].replace('.ser', '')
         # Dictionary
         elif type(arg) == type({}):
             for key in arg:
                 if key in self.__dict__:
                     self.__dict__[key] = arg[key]
         # List
         elif type(arg) == type([]):
             for item in arg:
                 # Contour
                 if item.__class__.__name__ == 'Contour':
                     self.contours.append(item)
                 # ZSection
                 elif item.__class__.__name__ == 'ZContour':
                     self.zcontours.append(item)
                 # Section
                 elif item.__class__.__name__ == 'Section':
                     self.sections.append(item)
         # Contour
         elif arg.__class__.__name__ == 'Contour':
             self.contours.append(arg)
         # ZSection
         elif arg.__class__.__name__ == 'ZContour':
             self.zcontours.append(item)
         # Section
         elif arg.__class__.__name__ == 'Section':
             self.sections.append(arg)
     for kwarg in kwargs:
         # Load sections
         if 'sections' in kwargs:
             if kwargs['sections'] == True:
                 print('Attempting to load sections...'),
                 ser = os.path.basename(self.path)
                 serfixer = re.compile(re.escape('.ser'), re.IGNORECASE)
                 sername = serfixer.sub('', ser)
                 # look for files with 'seriesname'+'.'+'number'
                 p = re.compile('^' + sername + '[.][0-9]*$')
                 sectionlist = [
                     f for f in os.listdir(self.path.replace(ser, ''))
                     if p.match(f)
                 ]
                 # create and append Sections for each section file
                 path = self.path.replace(os.path.basename(self.path), '')
                 for sec in sectionlist:
                     section = Section(path + sec)
                     if section.index is not None:  #===
                         self.update(section)
                 # sort sections by index
                 self.sections = sorted(self.sections,
                                        key=lambda Section: Section.index)
                 print(' SUCCESS!')
示例#28
0
 def setUp(self):
     n1 = Node(1, Point())
     n2 = Node(2, Point(3, 4, 0))
     section = Section(1, 1, 1000, 0, 0.1, 0.001, 0, 0)
     self.truss = Truss2D(1, n1, n2, section, 0.1)
示例#29
0
def section():
    from Section import Section
    return Section()
示例#30
0
from Notebook import Notebook
from Note import Note
from Section import Section
from Network import Network
import time

if __name__ == '__main__':
    nt = Notebook('a')
    nt.add_section(Section('مشکلات'))
    nt.add_section(Section('مستقلات'))
    nt.sections[0].add_note(Note('مناسب', 'مهارت های ابتدایی'))
    nt.sections[1].add_note(Note('تعهد', 'به زمانه های پلید'))

    net = Network("http://127.0.0.1:8000/noteserver/")
    net.login_user('a', 'aa')
    res = net.set_timer("*****@*****.**", "testi", time.time() + 50)