def test_loadbalancer(self): """ testing scaling up and down threads """ # scaling up dummy_checks = 1000 self.create_dummy_checks(dummy_checks, 60) self.config.set("Checker", "latency_spawn_thread", "1") self.config.set("Checker", "latency_calculate", "5") self.config.set("Checker", "spawn_thread_max", "2") self.config.set("Checker", "delete_thread_max", "30") self.monitor_engine = checker.start_checker( self.config, self.config.get("Checker", "test_db"), 1, 10000, 2 ) time.sleep(3) last_threads = self.monitor_engine['active_monitor_threads'] time.sleep(30) threads = self.monitor_engine['active_monitor_threads'] self.assertTrue(threads > last_threads) last_threads = threads time.sleep(30) threads = self.monitor_engine['active_monitor_threads'] self.assertTrue(threads > last_threads) self.monitor_engine.shutdown() # scaling down self.delete_dummy_checks(dummy_checks - 3) self.config.set("Checker", "latency_spawn_thread", "1") self.config.set("Checker", "latency_calculate", "5") self.config.set("Checker", "spawn_thread_max", "10") self.config.set("Checker", "delete_thread_max", "2") self.monitor_engine = checker.start_checker( self.config, self.config.get("Checker", "test_db"), 100, 10000, 2 ) time.sleep(3) last_threads = self.monitor_engine['active_monitor_threads'] time.sleep(30) threads = self.monitor_engine['active_monitor_threads'] self.assertTrue(threads < last_threads) last_threads = threads time.sleep(30) threads = self.monitor_engine['active_monitor_threads'] self.assertTrue(threads < last_threads)
def add_supplier(self): temp_supplier = supplier(self.text) check.search_supplier(temp_supplier) temp_supplier.index = len(self.suppliers) self.suppliers.append(temp_supplier) number_of_articles = len(temp_supplier.articles) + len( temp_supplier.messages) temp_supplier.name_label = tk.Label(self.window, text=self.text, background='#0c4361', fg='white') temp_supplier.name_label.place(y=(len(self.suppliers) * 50), x=0) self.window.update() if (temp_supplier.highest_warning == 2): temp_supplier.warning_label = tk.Label(self.window, image=self.hwarning_photo, background='#0c4361') temp_supplier.warning_label.place(y=(len(self.suppliers) * 50) - 5, x=910) elif (temp_supplier.highest_warning == 1): temp_supplier.warning_label = tk.Label(self.window, image=self.lwarning_photo, background='#0c4361') temp_supplier.warning_label.place(y=(len(self.suppliers) * 50) - 5, x=910) temp_supplier.article_label = tk.Label(self.window, text=number_of_articles, background='#0c4361', fg='white') temp_supplier.article_label.place(y=(len(self.suppliers) * 50), x=890) temp_supplier.Separator = ttk.Separator(self.window, orient='horizontal') temp_supplier.Separator.place(y=(len(self.suppliers) * 50) + 40, x=0, relwidth=1) temp_supplier.drop_button = tk.Button( self.window, command=lambda: self.__slide(temp_supplier.index)) temp_supplier.drop_button.config(image=self.arrow_photo, width='43', height='42', relief=tk.FLAT, background='#0c4361') temp_supplier.drop_button.place(y=(len(self.suppliers) * 50) - 8, x=950) self.window.update() return temp_supplier
def iniciar(self): self.AST = Nodo_Programa("PROGRAMA", "", []) puntero_ast = self.AST puntero_token = 0 if (self.parsear_programa(0) == True): checker = Checker(self.AST) informe = checker.checkear() if (type(informe) != str): #no hay errores de tipos return else: print(informe) else: self.generar_error()
def correctAll(): body = request.json words = list(Checker.correct_core(body["text"])) return json.dumps({ 'all': words }, ensure_ascii=False, indent=2).encode('utf8')
def correctBest(): body = request.json item = table.get_item(Key={'Input': body["text"]}) if 'Item' in item: return json.dumps({ 'best': item['Item']['Corrected'] }, ensure_ascii=False, indent=2).encode('utf8') words = list(Checker.correct_core(body["text"])) best_match = '' for word in words: if type(word) == list: best_match += word[0] else: best_match += word table.put_item(Item={'Input': body["text"], 'Corrected': best_match}) return json.dumps({ 'best': best_match }, ensure_ascii=False, indent=2).encode('utf8')
def test_dns(self): """ testing pyDNS ip resolution """ domain = ("medtelligent.com", "174.36.81.144") cursor = self.connection.cursor() cursor.execute(""" INSERT INTO LocalSchedule ( global_schedule_id, monitor_point_id, port, service_type, frequency, next_check_time, fqdn ) VALUES ( 1, 1, 80, "icmp.ping", 10, NOW(), "%s" ) """ % domain[0]) cursor.close() self.connection.commit() self.monitor_engine = checker.start_checker( self.config, self.config.get("Checker", "test_db"), 10, 10000, 2 ) time.sleep(5) self.assertEqual(self.monitor_engine.get('last_resolved_dns'), domain)
def __init__(self, row, col, p): """ Intializes board: M = number of rows N = number of columns P = number of rows containing initial checker pieces Adds the white checkers and black checkers to the board based on the board variables (M,N,P) provided. N*P should be even to ensure that both players get the same number of checker pieces at the start @param row: number of rows in the board @param col: number of columns in the board @param p: number of rows to be filled with checker pieces at the start @return : @raise : """ self.tie_counter = 0 self.tie_max = 40 self.row = row self.col = col self.p = p self.board = [] self.saved_move = [] #self.saved_move = [Move([]),[],False] for row in range(self.row): self.board.append([]) for col in range(self.col): self.board[row].append(Checker.Checker(".", [row, col])) self.black_count = 0 self.white_count = 0
def test_spike_distribution(self): """ testing check spike distribution """ self.create_dummy_checks(1000, 60) self.monitor_engine = checker.start_checker( self.config, self.config.get("Checker", "test_db"), 10, 10000, 2 ) time.sleep(5) chunk, total = self.monitor_engine['feeder_throttle'] self.assertTrue(chunk < total) old_total = total time.sleep(5) chunk, total = self.monitor_engine['feeder_throttle'] self.assertTrue(chunk < total) self.assertTrue(total < old_total) old_total = total time.sleep(5) chunk, total = self.monitor_engine['feeder_throttle'] self.assertTrue(chunk < total) self.assertTrue(total < old_total) old_total = total
def main(): words = English.words particles = English.particles using = True corrections = True print("Welcome to a terrible low level japanese translator!") while (using): try: if (corrections): print("Corrections are on") else: print("Corrections are off") print("Press 1 to translate japanese to english") print("Press 2 to translate english to japanese") print("Press 3 to toggle corrections on or off") print("Press 4 to quit") choice = int(input()) while (choice > 4 or choice < 1): print("Please select a valid choice") choice = int(input()) if (choice == 1): print("Please enter a space between each word AND particle") print("Please enter the sentence you would like to translate") sentence = input() hiraganaSentence = Translate.TranslateHiragana(sentence) print() print('Hiragana: ', hiraganaSentence) sentenceList = English.ToEnglish(sentence) print('Translation: ', sentenceList[0]) print() if (corrections): Checker.IsCorrect(sentenceList[1], sentenceList[0]) elif (choice == 2): print("Please enter the sentence you would like to translate") sentence = input() japaneseSentences = Japanese.ToJapanese(sentence) print() print('Romanji:', japaneseSentences[1]) print('Hiragana:', japaneseSentences[0]) print() elif (choice == 3): if (corrections): print("Corrections have been switched to off") corrections = False else: print("Corrections have been switched to on") corrections = True elif (choice == 4): print("Thanks for using it :)") using = False except Error.UnknownWordError as e: print(e) except: print("Please enter a valid entry")
def go(self, text_dump_filename, template_information, pdf_file_with_path, output_file_with_path): logger = Logger.getLogger() olb = ObjectLayoutContainer.getInstance() olb.parse_pdf(pdf_file_with_path, text_dump_filename) try: template_file_name = TemplateChoser.get_template_name( template_information) except Exception as ex: logger.error(str(ex)) return plugin_manager = None plugin_name = self._get_plugin_name(template_file_name) if plugin_name is not None: plugin_manager = PluginManager.getInstance() plugin_manager.load_plugin(plugin_name) logger.info('Loaded plugin %s', plugin_name) dict_of_field_values = FieldExtractor.extract_fields( template_file_name) self._transform_field_values(plugin_manager, dict_of_field_values) dict_of_line_items = LineItemExtractor.extract_line_items( template_file_name) self._transform_lineitem_values(plugin_manager, dict_of_line_items) check_status = Checker.check_total(plugin_manager, template_file_name, dict_of_field_values, dict_of_line_items) if len(dict_of_field_values) > 0 or len(dict_of_line_items) > 0 or len( check_status) > 0: extracted_data = {} if len(dict_of_field_values) > 0: extracted_data["fields"] = dict_of_field_values if len(dict_of_line_items) > 0: extracted_data["lineitems"] = dict_of_line_items if len(check_status) > 0: extracted_data["checkstatus"] = check_status logger.info("Check Status Match = %s", str(check_status["match_status"])) returned_extraced_value = self._invoke_post_processor( plugin_manager, extracted_data) with io.open(output_file_with_path, 'w', encoding='utf-8') as f: f.write( str( json.dumps(returned_extraced_value, ensure_ascii=False, indent=4)))
def main(): socket = Server(PORT) data = {'any': ['INPUT'], IP1: ['INPUT'], IP2: ['INPUT']} board = Checker() while True: input_data, address = socket.watch(data) if input_data != 'CHECK': print(input_data) input_data = input_data.split() address = address[0] if input_data[0] == 'CHECK': data[address].append('INPUT') elif input_data[0] == 'MOVE': if address in board.active_player: x1, y1 = int(input_data[1]), int(input_data[2]) x2, y2 = int(input_data[3]), int(input_data[4]) err = board.move(x1, y1, x2, y2, address) if err: board.change_player() for ip in data: data[ip].append('OUTPUT' + ' ' + ' '.join(input_data[1:])) else: data[address].append('ERROR wrong step') else: data[address].append('ERROR wrong player') elif input_data[0] == 'LOGIN': found = False need_place = True for i in data: if address == i: need_place = False break for i in data: if i in DEFAULT_IP and need_place: data.pop(i) data[address] = [] data[address].append('SUCCESS ' + address) if board.white == (2, 4): board.set_white((address, 3)) elif board.black == (1, 3): board.set_black((address, 4)) found = True break if not need_place: data[address].append('SUCCESS ' + address) if not found: data[address].append('ERROR cant connection')
def __check(self, key, value): func = Checker.Checker(value) updated = [x for x in self.data[key] if func.is_not_found(x)] if not func.found: updated.append(value) if not updated: self.data.pop(key) else: self.data[key] = updated
def __init__(self, number): self.number = number self.column = 0 self.row = 0 self.ma = [0] * self.number * self.number self.matrix = np.array(self.ma).reshape(self.number, self.number) self.queue = deque() print('Inited') self.check = Checker.Checkers()
def initialize_game(self): """ Intializes game. Adds the white checkers and black checkers to the board based on the board variables (M,N,P) when the game starts @param : @return : @raise : """ self.check_initial_variable() for i in reversed(range(self.p)): for j in range((self.p - i - 1) % 2, self.col, 2): # put white pieces i_white = self.row - self.p + i self.board[i_white][j] = Checker.Checker("W", [i_white, j]) # put black pieces if (self.row % 2 + self.p % 2) % 2: # row,p = even,odd or odd,even if i % 2: # odd row, shift to the left and attach a piece to the end when needed if j - 1 >= 0: self.board[i][j-1] = Checker.Checker("B", [i, j-1]) if j == self.col - 2 and not self.col % 2: self.board[i][self.col-1] = Checker.Checker("B", [i,self.col-1]) else: # even row, shift to the right and attach a piece to the beginning when needed if j + 1 <= self.col - 1: self.board[i][j+1] = Checker.Checker("B", [i,j+1]) if (j == self.col - 1 or j == self.col - 2) and not self.p % 2: self.board[i][0] = Checker.Checker("B", [i,0]) else: # row,p = even,even or odd,odd self.board[i][j] = Checker.Checker("B", [i,j]) self.white_count += 1 self.black_count += 1
def face_to_Geom_Plane(face): ''' Returns a Geom_Plane if ok, raise error otherwise ''' if not face.ShapeType()==TopAbs_FACE: print '%s is not a TopAbs_FACE. Conversion impossible' return None if Checker.face_is_plane(face): hs = BRep_Tool().Surface(face) downcast_result = Handle_Geom_Plane().DownCast(hs) return downcast_result.GetObject() else: print 'The face %s can not be converted to a plane'%face return None
def check(): """ ask to enter number,return 1 for negative othewise 0 :return: 0 or 1 """ num = input('Введите число ') num = ch.floatCheck(num) print(num) if num < 0: return 1 else: return 0
def face_to_Geom_Plane(face): ''' Returns a Geom_Plane if ok, raise error otherwise ''' if not face.ShapeType() == TopAbs_FACE: print '%s is not a TopAbs_FACE. Conversion impossible' return None if Checker.face_is_plane(face): hs = BRep_Tool().Surface(face) downcast_result = Handle_Geom_Plane().DownCast(hs) return downcast_result.GetObject() else: print 'The face %s can not be converted to a plane' % face return None
def print_all(text): words = list(Checker.correct_core(text)) print('\n' + text) best_match = 'Fixed: ' for word in words: if type(word) == list: best_match += word[0] else: best_match += word print(best_match + '\n') for word in words: print(word)
def task5min(): if now > today3pm: print 'market close' exit() for symbol in symbol5: time.sleep(0.9) symbol = symbol.rstrip() print '30min checking #' + symbol + '\n' try: send, msg, rate = checker.checkSymbol(symbol, cfg.interval5, '30min', True) except: continue if send and rate > 2: sendMsg(msg) s.enter(cfg.timeInterval5min, 1, task5min, ()) pass
def executePlan(self): passNumber = 0 for filtre in plannedFiltersList: passNumber += 1 streamInType, streamOutType = getPlannedStreams(passNumber) if passNumber > 1: inBinFilename = self.streamObj.outBinFilename self.streamObj.setInFilename(inBinFilename) inBinFilename = self.streamObj.inBinFilename outBinFilename = self.streamObj.outBinFilename logLine = "%s filter %d streamIn %s streamIn %s" % (time.ctime(), filtre, inBinFilename, outBinFilename) self.logFile.write(logLine) self.streamObj.setStreamIn(streamInType) self.streamObj.setStreamOut(streamOutType) self.runner.setStreamObj(streamObj) checkerObj = chkr.getCheckerObjById(filtre, self.jogosObj) self.runner.setCheckerObj(checkerObj) self.runner.run()
def authorized(self, user: str, password: str) -> bool: if isinstance(user, str) and isinstance(password, str) is False: print("Неверный тип данных!") return False if not os.path.exists(user): print('Неверные данные!') return False with open(os.path.abspath(user) + '/USER_INFO/password.txt', 'r') as file: user_password = file.read() if Checker.Checker().check_password(user_password, password): with open(os.path.abspath(user) + '/USER_INFO/enc_key.txt', 'rb') as byte_enc_key_file: self.__user_secret_key = byte_enc_key_file.read() return True else: print('Неверные данные!') return False
import ctypes import sys import os #File Imports import Checker import StartDriver #Alert Box def Mbox(text, style): #Style: (0 = Ok) (4 = Yes/No) return ctypes.windll.user32.MessageBoxW(0, text, "GMeet Opener", style) #MAIN course, link, endTime = Checker.checkClass() if (course == None): Mbox("You have no class scheduled", 0) else: StartDriver.start() StartDriver.openGmeet(link) text = "Joined meet link for " + course + ". Do you want to enable autoclose for this class at " + endTime + "?" response = Mbox(text, 4) if (response == 6 ): #6 is the ID for YES. Check end of script for more info. StartDriver.autoClose(endTime) sys.exit() # ctypes messagebox return values # MB_OK = 0
""" Визначити і вивести на екран і цифри цілого числа n. """ import Checker as ch ch.greet(2, 'Визначити і вивести на екран і цифри цілого числа n.') while True: n = input('Введіть число') n = ch.intCheck(n) rasr = 10 memory = 0 while True: temp = int((n % rasr - memory) / rasr * 10) memory += temp * (rasr / 10) print(temp) if memory == n: break rasr *= 10 ans = input('Ще раз?(+ якщо так)') if ans != '+': break
class Connection: """An SSL connection.""" clientPostConnectionCheck = Checker.Checker() serverPostConnectionCheck = _serverPostConnectionCheck m2_bio_free = m2.bio_free m2_ssl_free = m2.ssl_free def __init__(self, ctx, sock=None): self.ctx = ctx self.ssl = m2.ssl_new(self.ctx.ctx) if sock is not None: self.socket = sock else: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._fileno = self.socket.fileno() self._timeout = self.socket.gettimeout() if self._timeout is None: self._timeout = -1.0 self.ssl_close_flag = m2.bio_noclose if self.ctx.post_connection_check is not None: self.set_post_connection_check_callback \ (self.ctx.post_connection_check) def __del__(self): if getattr(self, 'sslbio', None): self.m2_bio_free(self.sslbio) if getattr(self, 'sockbio', None): self.m2_bio_free(self.sockbio) if self.ssl_close_flag == m2.bio_noclose and getattr( self, 'ssl', None): self.m2_ssl_free(self.ssl) self.socket.close() def close(self): m2.ssl_shutdown(self.ssl) def clear(self): """ If there were errors in this connection, call clear() rather than close() to end it, so that bad sessions will be cleared from cache. """ return m2.ssl_clear(self.ssl) def set_shutdown(self, mode): m2.ssl_set_shutdown1(self.ssl, mode) def get_shutdown(self): return m2.ssl_get_shutdown(self.ssl) def bind(self, addr): self.socket.bind(addr) def listen(self, qlen=5): self.socket.listen(qlen) def ssl_get_error(self, ret): return m2.ssl_get_error(self.ssl, ret) def set_bio(self, readbio, writebio): """ Explicitly set read and write bios """ m2.ssl_set_bio(self.ssl, readbio._ptr(), writebio._ptr()) def set_client_CA_list_from_file(self, cafile): """ Set the acceptable client CA list. If the client returns a certificate, it must have been issued by one of the CAs listed in cafile. Makes sense only for servers. @param cafile: Filename from which to load the CA list. """ m2.ssl_set_client_CA_list_from_file(self.ssl, cafile) def set_client_CA_list_from_context(self): """ Set the acceptable client CA list. If the client returns a certificate, it must have been issued by one of the CAs listed in context. Makes sense only for servers. """ m2.ssl_set_client_CA_list_from_context(self.ssl, self.ctx.ctx) def setup_addr(self, addr): self.addr = addr def set_ssl_close_flag(self, flag): """ By default, SSL struct will be freed in __del__. Call with m2.bio_close to override this default. """ if flag not in (m2.bio_close, m2.bio_noclose): raise ValueError("flag must be m2.bio_close or m2.bio_noclose") self.ssl_close_flag = flag def setup_ssl(self): # Make a BIO_s_socket. self.sockbio = m2.bio_new_socket(self.socket.fileno(), 0) # Link SSL struct with the BIO_socket. m2.ssl_set_bio(self.ssl, self.sockbio, self.sockbio) # Make a BIO_f_ssl. self.sslbio = m2.bio_new(m2.bio_f_ssl()) # Link BIO_f_ssl with the SSL struct. m2.bio_set_ssl(self.sslbio, self.ssl, m2.bio_noclose) def _setup_ssl(self, addr): """Deprecated""" self.setup_addr(addr) self.setup_ssl() def set_accept_state(self): m2.ssl_set_accept_state(self.ssl) def accept_ssl(self): return m2.ssl_accept(self.ssl, self._timeout) def accept(self): """Accept an SSL connection. The return value is a pair (ssl, addr) where ssl is a new SSL connection object and addr is the address bound to the the other end of the SSL connection.""" sock, addr = self.socket.accept() ssl = Connection(self.ctx, sock) ssl.addr = addr ssl.setup_ssl() ssl.set_accept_state() ssl.accept_ssl() check = getattr(self, 'postConnectionCheck', self.serverPostConnectionCheck) if check is not None: if not check(self.get_peer_cert(), ssl.addr[0]): raise Checker.SSLVerificationError, 'post connection check failed' return ssl, addr def set_connect_state(self): m2.ssl_set_connect_state(self.ssl) def connect_ssl(self): return m2.ssl_connect(self.ssl, self._timeout) def connect(self, addr): self.socket.connect(addr) self.addr = addr self.setup_ssl() self.set_connect_state() ret = self.connect_ssl() check = getattr(self, 'postConnectionCheck', self.clientPostConnectionCheck) if check is not None: if not check(self.get_peer_cert(), self.addr[0]): raise Checker.SSLVerificationError, 'post connection check failed' return ret def shutdown(self, how): m2.ssl_set_shutdown(self.ssl, how) def renegotiate(self): """Renegotiate this connection's SSL parameters.""" return m2.ssl_renegotiate(self.ssl) def pending(self): """Return the numbers of octets that can be read from the connection.""" return m2.ssl_pending(self.ssl) def _write_bio(self, data): return m2.ssl_write(self.ssl, data, self._timeout) def _write_nbio(self, data): return m2.ssl_write_nbio(self.ssl, data) def _read_bio(self, size=1024): if size <= 0: raise ValueError, 'size <= 0' return m2.ssl_read(self.ssl, size, self._timeout) def _read_nbio(self, size=1024): if size <= 0: raise ValueError, 'size <= 0' return m2.ssl_read_nbio(self.ssl, size) def write(self, data): if self._timeout != 0.0: return self._write_bio(data) return self._write_nbio(data) sendall = send = write def read(self, size=1024): if self._timeout != 0.0: return self._read_bio(size) return self._read_nbio(size) recv = read def setblocking(self, mode): """Set this connection's underlying socket to _mode_.""" self.socket.setblocking(mode) if mode: self._timeout = -1.0 else: self._timeout = 0.0 def settimeout(self, timeout): """Set this connection's underlying socket's timeout to _timeout_.""" self.socket.settimeout(timeout) self._timeout = timeout if self._timeout is None: self._timeout = -1.0 def fileno(self): return self.socket.fileno() def getsockopt(self, *args): return apply(self.socket.getsockopt, args) def setsockopt(self, *args): return apply(self.socket.setsockopt, args) def get_context(self): """Return the SSL.Context object associated with this connection.""" return m2.ssl_get_ssl_ctx(self.ssl) def get_state(self): """Return the SSL state of this connection.""" return m2.ssl_get_state(self.ssl) def verify_ok(self): return (m2.ssl_get_verify_result(self.ssl) == m2.X509_V_OK) def get_verify_mode(self): """Return the peer certificate verification mode.""" return m2.ssl_get_verify_mode(self.ssl) def get_verify_depth(self): """Return the peer certificate verification depth.""" return m2.ssl_get_verify_depth(self.ssl) def get_verify_result(self): """Return the peer certificate verification result.""" return m2.ssl_get_verify_result(self.ssl) def get_peer_cert(self): """Return the peer certificate; if the peer did not provide a certificate, return None.""" c = m2.ssl_get_peer_cert(self.ssl) if c is None: return None # Need to free the pointer coz OpenSSL doesn't. return X509.X509(c, 1) def get_peer_cert_chain(self): """Return the peer certificate chain; if the peer did not provide a certificate chain, return None.""" c = m2.ssl_get_peer_cert_chain(self.ssl) if c is None: return None # No need to free the pointer coz OpenSSL does. return X509.X509_Stack(c) def get_cipher(self): """Return an M2Crypto.SSL.Cipher object for this connection; if the connection has not been initialised with a cipher suite, return None.""" c = m2.ssl_get_current_cipher(self.ssl) if c is None: return None # XXX Need to free the pointer? return Cipher(c) def get_ciphers(self): """Return an M2Crypto.SSL.Cipher_Stack object for this connection; if the connection has not been initialised with cipher suites, return None.""" c = m2.ssl_get_ciphers(self.ssl) if c is None: return None # XXX Need to free the pointer? return Cipher_Stack(c) def get_cipher_list(self, idx=0): """Return the cipher suites for this connection as a string object.""" return m2.ssl_get_cipher_list(self.ssl, idx) def set_cipher_list(self, cipher_list): """Set the cipher suites for this connection.""" return m2.ssl_set_cipher_list(self.ssl, cipher_list) def makefile(self, mode='rb', bufsize=-1): return socket._fileobject(self, mode, bufsize) def getsockname(self): return self.socket.getsockname() def getpeername(self): return self.socket.getpeername() def set_session_id_ctx(self, id): ret = m2.ssl_set_session_id_context(self.ssl, id) if not ret: raise SSLError(m2.err_reason_error_string(m2.err_get_error())) def get_session(self): sess = m2.ssl_get_session(self.ssl) return Session(sess) def set_session(self, session): m2.ssl_set_session(self.ssl, session._ptr()) def get_default_session_timeout(self): return m2.ssl_get_default_session_timeout(self.ssl) def get_socket_read_timeout(self): return timeout.struct_to_timeout( self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, 8)) def get_socket_write_timeout(self): return timeout.struct_to_timeout( self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, 8)) def set_socket_read_timeout(self, timeo): assert isinstance(timeo, timeout.timeout) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeo.pack()) def set_socket_write_timeout(self, timeo): assert isinstance(timeo, timeout.timeout) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, timeo.pack()) def get_version(self): "Return the TLS/SSL protocol version for this connection." return m2.ssl_get_version(self.ssl) def set_post_connection_check_callback(self, postConnectionCheck): self.postConnectionCheck = postConnectionCheck
if __name__ == '__main__': # Parse command line options from optparse import OptionParser parser = OptionParser() parser.add_option("-c", "--config", dest="config_file", help="Configuration file with local settings") (options, args) = parser.parse_args() # Open up the configuration file and read for later use from ConfigParser import ConfigParser config = ConfigParser() config.read(options.config_file) # Setup logging logging.basicConfig() Checker.createLogger(config, ["checker"]) # Setup and run the server sqlhub.processConnection = connectionForURI(config.get("Checker", "db")) immediate_checker.updateConfig(config) try: port = config.getint('Checker', 'immediate_check_server_port') except: port = 9090 run(host='0.0.0.0', port=port, reloader=False, debug=False) """checker = ImmediateChecker(config) print checker.check('service', schedule = { "monitor_point_id" : 1, "fqdn": "google.com", "ip_address": None, "port": 80, "service_type": "tcp.http.fullpage" }, metadata = { "http_match_type": "present_exact", "http_match_string": "Gmail2", "http_request_type": "GET" })
""" Розрахунок за формулой """ import Checker as ch ch.greet(2 ,'Розрахунок за формулой') while True: n = input('Введіть n') n = ch.nCheck(n) x = input('Введіть x') x = ch.floatCheck(x) p = 1 for i in range(1, n + 1): p *= (i + x) print('Відповідь:%.4f' % p) ans=input('Ще раз?(+ якщо так)') if ans != '+': break
self.board[target_point[0]][target_point[1]].color = "." self.board[target_point[0]][target_point[1]].is_king = False for saved_enemy in temp_saved_move[1]: #self.saved_move[1]: x, y, c, k = saved_enemy self.board[x][y].color = c self.board[x][y].is_king = k self.saved_move.pop(-1) else: raise Exception("Cannot undo operation") if __name__ == "__main__": b = Board(10, 10, 2) b.board[4][3] = Checker.Checker("W", [4, 3]) b.board[4][5] = Checker.Checker("W", [4, 5]) b.board[6][5] = Checker.Checker("W", [6, 5]) b.board[8][1] = Checker.Checker("B", [8, 1]) b.board[2][7] = Checker.Checker("W", [2, 7]) b.board[2][5] = Checker.Checker("W", [2, 5]) b.board[2][3] = Checker.Checker("W", [2, 3]) b.board[8][1].become_king() b.show_board() m = b.get_all_possible_moves("B")[0][0] b.make_move(m, "B") b.show_board() b.undo() b.show_board()
controlador = Controlador(f) i = controlador.verificar_Archivo() if i == 1: sc = Scanner Tokens = sc.verificar_Scanner(controlador.get_Archivo()) sc.getReportErrors() #print (Tokens) if (sc.getReportErrors() == 0): Tree = Parser.iniciar_Parser(Tokens) if (Parser.get_reportErrors() is True): print( "\n\n*********************************************************\n----------> Inicio proceso ANALISIS SEMANTICO\n\n" ) visitor = Checker.Checker() Checker.Checker.check(Tree) print( "\n\nImprimiendo arbol decorado...\n----------------------------------------------------------------\n" ) impresion = ImprimirArbol.ImprimirArbol(Tree) impresion.imprime_Arbol(Tree) else: print("--------------------------------------------------") else: print( "\n---------------------------------------------------\n Se obtuvieron errores en el analisis sintactico" )
import Checker sep= ' ' Checker.greet(3, 'Замінити перші 3 символи слів, що мають обрану довжину, на символ') while True: words = input('Введить речення ') print('Введить задану довжину:', end='') leng = Checker.nCheck() newWords = str('') for word in words.split(sep): if len(word) == leng: newWords += '*'+word[3:]+sep else: newWords = newWords + (word + sep) print(newWords) if input('Бажаєте продовжити(+)') != '+': break
def __init__(self, _black, position, control_type): self.color = WHITE if not _black else BLACK self.checker = None if control_type == NONE else Checker( control_type, position)
import Checker as ch import re def pars(lis, separ='0'): mainTemp = [] temp = [] for i in range(len(lis)): if lis[i] != separ: temp.append(lis[i]) else: mainTemp.append(temp) temp = [] mainTemp.append(temp) return mainTemp while True: ch.greet(5, 'Перетворити однорівневий список у список із вкладеними списками, згідно з визначеними умовами. ') rawList = input('Введіть елемнти списку через пробіл з родільником "0" ').split(' ') newList = pars(rawList) print(newList) if input('Бажаєте продовжити(+)') != '+': break
import itertools import Checker as ch while True: a = {'1', '2', 'ee', 'ww', 'a', 'd'} b = {'1', 'd', "tt", '4', '3'} u = {'1', '2', '3', '4', 'a', 'b', 'c', 'd', 'ee', 'tt', 'ww'} ch.greet(5, '') c = a.union(b) print('Обєднаяння: ', c) c = a & b print('Перетин: ', c) c = a - b print('a-b : ', c) c = b - a print('b-a : ', c) c = a ^ b print('сіметрична різниця: ', c) c = [] for element in itertools.product(a, b): c.append(element) print('aхb: ', c) c = [] for element in itertools.product(b, a): c.append(element) print('bxa: ', c) c = u - a print("'a: ", c) c = u - b print("'b: ", c) c = (a.union(b)) - (a - b) print('F= ', c)
self.board[x][y].color = c self.board[x][y].is_king = k if c == "W": self.white_count += 1 if c == "B": self.black_count += 1 self.tie_counter -= 1 self.saved_move.pop(-1) else: raise Exception("Cannot undo operation") if __name__ == "__main__": b = Board(7, 7, 2) b.board[1][3] = Checker.Checker("W", [1, 3]) b.show_board() m = b.get_all_possible_moves("W")[0][0] b.make_move(m, "W") b.show_board() m = b.get_all_possible_moves("W")[0][0] b.make_move(m, "W") b.show_board() m = b.get_all_possible_moves("W")[0][0] b.make_move(m, "W") b.show_board() print("Undo") b.undo() b.show_board() print("Undo")
###################################################################################################################################### #Below is the example code of HCD. # #ATTENTION:ALL OF YOUR PERSONAL DATA WILL BE STORAGED IN ./COURSES.TXT,./TEST.TXT,./PERINFO.TXT # # ###################################################################################################################################### import preMain import weather import sys from Info import logger import Checker import os import ExpFunc if not os.path.exists('./update.zip'): Checker.checkUpdate() Checker.settingsChecker() logger.info("checking config......done") ExpFunc.extra() def weatheroop(): print( "---------------------------------------天气情况---------------------------------------" ) wea = weather.weather() print(wea.future(0, 1, 2, 3)) print( "-------------------------------------------------------------------------------------" ) def perinforet():
def make_move(self, move, turn): """ Makes Move on the board @param move: Move object provided by the StudentAI, Uses this parameter to make the move on the board @param turn: this parameter tracks the current turn. either player 1 (white) or player 2(black) @return: @raise InvalidMoveError: raises this objection if the move provided isn't valid on the current board """ temp_saved_move = [Move([]), [], False] if type(turn) is int: if turn == 1: turn = 'B' elif turn == 2: turn = 'W' else: raise InvalidMoveError move_list = move.seq move_to_check = [] ultimate_start = move_list[0] ultimate_end = move_list[-1] is_start_checker_king = self.board[ultimate_start[0]][ ultimate_start[1]].is_king past_positions = [ultimate_start] capture_positions = [] for i in range(len(move_list) - 1): move_to_check.append((move_list[i], move_list[i + 1])) # e.g move = Move((0,0)-(2,2)-(0,4)) # move_to_check = [((0,0),(2,2)),((2,2),(0,4))] if_capture = False self.tie_counter += 1 saved_enemy_position = [] for t in range(len(move_to_check)): start = move_to_check[t][0] # e.g. (0,0) target = move_to_check[t][1] # e.g. (2,2) if self.is_valid_move( start[0], start[1], target[0], target[1], turn) or (if_capture and abs(start[0] - target[0]) == 1): # invailid move or attempting to make a single move after capture self.board[start[0]][start[1]].color = "." self.board[target[0]][target[1]].color = turn self.board[target[0]][target[1]].is_king = self.board[ start[0]][start[1]].is_king self.board[start[0]][start[1]].become_man() past_positions.append(target) if abs(start[0] - target[0]) == 2: # capture happened if_capture = True self.tie_counter = 0 capture_position = ((start[0] + (target[0] - start[0]) // 2), (start[1] + (target[1] - start[1]) // 2)) # calculate capture position capture_positions.append(capture_position) # record capture position saved_enemy_position.append( (capture_position[0], capture_position[1], self.board[ capture_position[0]][capture_position[1]].color, self.board[capture_position[0]][ capture_position[1]].is_king)) self.board[capture_position[0]][ capture_position[1]] = Checker.Checker( ".", [capture_position[0], capture_position[1]]) # capture if turn == "B": self.white_count -= 1 else: self.black_count -= 1 if (turn == 'B' and target[0] == self.row - 1 ): # and not self.board[target[0]][target[1]].is_king): if not is_start_checker_king: temp_saved_move[2] = True self.board[target[0]][target[1]].become_king() #self.saved_move[2] = True elif (turn == 'W' and target[0] == 0 ): # and not self.board[target[0]][target[1]].is_king): if not is_start_checker_king: temp_saved_move[2] = True self.board[target[0]][target[1]].become_king() #self.saved_move[2] = True else: temp_saved_move[2] = False #self.saved_move[2] = False else: for failed_capture in capture_positions: # recover failed captures self.board[failed_capture[0]][ failed_capture[1]] = Checker.Checker( self.opponent[turn], [failed_capture[0], failed_capture[1]]) for failed_position in past_positions: # recover failed moves self.board[failed_position[0]][ failed_position[1]] = Checker.Checker( ".", [failed_position[0], failed_position[1]]) self.board[ultimate_start[0]][ ultimate_start[1]] = Checker.Checker( turn, [ultimate_start[0], ultimate_start[1]]) raise InvalidMoveError temp_saved_move[0] = copy.deepcopy( move) #self.saved_move[0] = copy.deepcopy(move) temp_saved_move[ 1] = saved_enemy_position #self.saved_move[1] = saved_enemy_position self.saved_move.append(temp_saved_move)
""" Підрахувати кількість негативних серед чисел а, b, с (ввести з клавіатури). """ import Checker as ch ch.greet( 1, "Підрахувати кількість негативних серед чисел а, b, с (ввести з клавіатури)." ) def check(): """ ask to enter number,return 1 for negative othewise 0 :return: 0 or 1 """ num = input('Введите число ') num = ch.floatCheck(num) print(num) if num < 0: return 1 else: return 0 count = 0 for i in range(3):