def testSet(triangle): options = [triangle, triangle[2:4] + triangle[0:2] + triangle[4::], triangle[4::] + triangle[0:2] + triangle[2:4]] for j in options: print j keyboard() if not testOrigin(j): return False return True
def testOrigin(points): try: line = [points[2] - points[0], points[3] - points[1]] except: keyboard() normal = [-line[1], line[0]] print "normal: ", normal print "line: ", line print "origin: ", sign(dot(normal, [0-points[0], 0-points[1]])) print "test_point: ", sign(dot(normal, [points[4] - points[0],points[5] - points[0]])) print if sign(dot(normal, [0-points[0], 0-points[1]])) == sign(dot(normal, [points[4] - points[0],points[5] - points[0]])): return True else: return False
def vk_id(dictionary, students_file): students = files.json_load(students_file) decoding = files.json_load('json/decoding_exams') for i in dictionary.keys(): k = regular(r'\w*-11', i) date = regular(r'\d\d[.]\d\d[.]\d\d\d\d', i) text = "Привет! Обновились результаты экзамена " + keys_values(decoding, k[0]) + ". Ты можешь посмотреть их на сайте РЦОИ: res11.rcoi.net. \n\n Если ты узнал свой результат, ты можешь отписаться от этого экзамена, написав мне 'перестать следить' и выбрав соответствующий экзамен. Если результатов экзамена не видно в личном кабинете, возможно, они появятся чуть позже. Я сообщу тебе, как только узнаю об изменениях." for s in students[i]: vkapi.send(text, s, token, keyboard.keyboard([]))
def plotLines(data): perpDist = lambda x,y,rho, theta: ((x*cos(theta) + y*sin(theta)) - rho) imageSize = [100,100] yScale = 1./10 xScale = 1./10 distTol = 0.1 center = [int(imageSize[0]/2), int(imageSize[1]/2)] grid = [[0 for j in range(imageSize[1])] for i in range(imageSize[0])] grid[center[0]][center[1]] = 10 for i in range(imageSize[0]): for j in range(imageSize[1]): for k in range(len(data.est_rho)): d = perpDist((j - center[1])*xScale, (i - center[0])*yScale, data.est_rho[k], data.est_theta[k]) if abs(d) < distTol: grid[i][j] += 1 imshow(grid) show() keyboard()
def start(bot, update): query = get_query(bot, update) if check_username(bot, update) == False: return kb_markup = keyboard() bot.send_message(chat_id=query.message.chat.id, text="Добро пожаловать, @{}!".format( query.message.chat.username), reply_markup=kb_markup) log_client(bot, update)
def wrapped(*args, **kwargs): bot = kwargs.get('bot') if kwargs.get('bot') else args[0] update = kwargs.get('update') if kwargs.get('update') else args[1] if update.message.chat.type in ["group", "supergroup", "channel"]: kb_markup = keyboard() bot.sendMessage( text= "Не-не, в группах я отказываюсь работать, я стеснительный. Пиши мне только тет-а-тет 😉", chat_id=update.message.from_user.id, reply_markup=kb_markup) return return f(*args, **kwargs)
def get_trains(bot, update, *args, **kwargs): user = kwargs.get("user", None) activity = kwargs.get("activities", None) query = get_query(bot, update) db_name = "trains" if user: trains_list = get_things(db_name, user=user, activities=activity) else: trains_list = get_things(db_name, activities=activity) if trains_list: iter = 0 next = iter + step if user: if len(trains_list) <= next: thing_list(bot, update, db_name, iter, next, skip_pager=True, user=user, activities=activity) elif len(trains_list) > next: thing_list(bot, update, db_name, iter, next, user=user, activities=activity) else: if len(trains_list) <= next: thing_list(bot, update, db_name, iter, next, skip_pager=True, activities=activity) elif len(trains_list) > next: thing_list(bot, update, db_name, iter, next, activities=activity) else: bot.sendMessage( text="Пока тренировки не запланированы. Восстанавливаемся!", chat_id=query.message.chat.id, reply_markup=keyboard())
def __init__(self, margin, size, spacing, dt, options, hoverLimit=4, save_dir=''): self.save_dir = save_dir self.uid = os.getuid self.uname = os.getlogin() self.timemark = strftime("%a, %d %b %Y %H:%M:%S", localtime()) self.hoverlimit = hoverLimit # after hovering hoverlimit time over a key, key is selected self.lastHoverTime = time.time( ) # record the start of hovering on a key self.hoverDt = 0 # record how long the mouse is hovering on a key # mark which selection option is on(can be both on) self.clickOn = options[0] # 1 for click mode on self.hoverOn = options[1] # 1 for hover mode on # record the last key mouse was hovering self.lastHoverKey = (-1, -1) #set up keyboard appearance and size Setting self.backgroundColor = 'black' self.keyColor = 'white' self.hoverColor = 'cyan' self.textHeight = 0 self.inputText = 'INPUT:' self.kb = keyboard(size, spacing, self.keyColor, self.hoverColor, (margin[0], margin[1] + self.textHeight)) self.widthMargin = margin[0] self.heightMargin = margin[1] self.winWidth = self.kb.width + 2 * self.widthMargin self.winHeight = self.kb.height + 2 * self.heightMargin + self.textHeight # the time interval the whole app is running at self.dt = dt # data logging variables self.clickedKeys = [] # a list of clicked keys self.endIndex = [ ] # mark the end of a sequence of movement by index until a new key is selected self.mouseMovement = [] # a list of mouse position self.mouseMovementTime = [ ] # a list of corresponding time of mouse movement self.appStartTime = 0 # start time of the app(initialized in self.run()) # record if cap is turned on or not self.cap = True
def msgDia(): inst_keyboard = keyboard() msg = ['Coders', 'Jedi\'s', 'Programeiros'] hj = date.today().weekday() #podem mudar as frases. Não sou tão criativo. ^^ if hj == 0: hoje = ' Força que hoje é só o primeiro dia da semana!' elif hj == 2: hoje = ' Estamos no meio da semana. Tycot deseja-lhes muita sabedoria e paciência' elif hj == 4: hoje = ' Hoje é sexta! Não façam besteira ou vão perder o FDS!' #infelizmente, como está fora do handle, não há como pegar o ID do grupo. Se alguém souber, fique a vontade. bot.sendMessage(-1001068576090, parse_mode='HTML', text='<i>Bom dia {}!{}</i>'.format( msg[random.randint(0, len(msg) - 1)], hoje), reply_markup=inst_keyboard.keyboard_sugestao()) bot.sendVideo(-1001068576090, 'https://media.giphy.com/media/W4IY7zQdRh7Ow/giphy.gif')
with open('private_config.conf', 'r') as configFile: config = json.load(configFile) TOKEN, CHAT = config['TOKEN'], config['CHAT'] with open('config.conf', 'r') as configFile: config = json.load(configFile) LOOP_DELAY, Timelist = config['DELAY'], config['Timelist'] logging.basicConfig(level=logging.INFO) today = Today(config['Time']) Raspberry = Raspberry(config['Raspberry']) watcher = watcher() periodic = periodic() keyboard = keyboard(watcher, periodic, Timelist) bot = Bot(TOKEN) dp = Dispatcher(bot) loop = asyncio.get_event_loop() def repeat(wrapped): def wrapper(): loop.call_later(wrapped(), wrapper) return wrapper async def send_photo(chat): await bot.send_photo(chat, Raspberry.Capture())
from keyboard import keyboard from icp import Scan keyboard()
def main( argv ): """ Script execution entry point """ handle = open( 'keyboard.svg', 'wb' ) key_styles = { '.k_motion' : { 'fill' : '#78AC66', 'fill-opacity' : '0.5' }, '.k_command' : { 'fill' : '#66A3AC', 'fill-opacity' : '0.5' }, '.k_insert' : { 'fill' : '#E3972F', 'fill-opacity' : '0.5' }, '.k_operation' : { 'fill' : '#B968EB', 'fill-opacity' : '0.5' }, '.k_extra' : { 'fill' : '#D6D6D6', 'fill-opacity' : '0.5' }, '.k_test .key_top' : { 'fill' : '#FF0000' } } kb = keyboard.keyboard( xscale = 80, yscale = 80 ) for ( k, s ) in key_styles.items(): kb.style[ k ] = s for ( key_id, info ) in _info.items(): k = keyboard.create_key( key_id ) k.flags |= keyboard.key.SHIFT if ( 'default' in info ) and ( 'text' in info[ 'default' ] ): k.add_label( 30, 33, info[ 'default' ][ 'text' ] ) if ( 'shift' in info ) and ( 'text' in info[ 'shift' ] ): k.add_label( 30, 15, info[ 'shift' ][ 'text' ] ) #k.set_attributes( { 'class' : 'k_test' } ) kb.add_key( k ) # ZIH - not set on how styling each part of each key works # there will be lots of CSS rules this way ## -> will have to have a deeper method to set the class on each part # of the key (top and bottom) # ZIH - text elements for additional labels should have their own # class for easier selection in style sheet ## -> should also have a method to automatically position two additional # labels (top and bottom) without specifying coordinates # ZIH - the image is drawn as if all 23 unit columns are always required ## -> the keyboard module should detect the number of columns in the keys # list, and grow the image as it is adding key elements handle.write( str( kb ) ) handle.close() # Return success. return 0
def _init_(self): self.keyboard = keyboard.keyboard() self.gamecon = gamecon.gamecon()
from Whack_A_Dot import Whack_A_Dot from Cell_Spotter import Cell_Spotter from Alphabet_Cards import Alphabet_Cards from Braille_Tale import Braille_Tale import numpy from keyboard import keyboard import pygame import sounds from sys import exit pygame.mixer.pre_init(22050, -16, 2, 512) pygame.init() pygame.mixer.init() braille_keyboard = keyboard() braille_keyboard.test_coms() clock = pygame.time.Clock() SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 800 current_display_state = 0 white, black, yellow, blue = (255, 255, 255), (0, 0, 0), (255, 255, 0), (0, 0, 255) display_data = {'screen_width':SCREEN_WIDTH, 'screen_height':SCREEN_HEIGHT, 'current_display_state':current_display_state} display_names = ['white_black', 'black_white', 'blue_yellow'] display_states = {'black_white':{'background':black, 'text':white},
obs.date = ephem.now() refStars[nStar].compute(obs) Ra_t, Dec_t = float(refStars[nStar].ra), float(refStars[nStar].dec) tCoords.addStar(refStars[nStar], obs, Ra_t, Dec_t) nStar = (nStar + 1) % 3 time.sleep(60) print tCoords.T # Set up keyboard handling pygame.display.init() pygame.display.set_mode((300, 300)) KB = keyboard.keyboard(pygame) KB.setSpeeds(dt, spdMin, spd) # speed range for keyboard input # Main code if __name__ == '__main__': try: # Check for a PS3 controller connected pygame.init() if pygame.joystick.init( ): # Suspect, seems to return false even when joystick is present if pygame.joystick.Joystick(0): joysticks = [ pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count()) ] else:
def form_message(message, user, file='message_history.json'): data = json.load(codecs.open('json/' + file, 'r', 'utf-8-sig')) exams = json.load(codecs.open('json/decoding_exams.json', 'r', 'utf-8-sig')) dates = json.load(codecs.open('json/exams_dates.json', 'r', 'utf-8-sig')) capital_message = message.capitalize() if 'гвэ' in capital_message: i = capital_message.find('(гвэ)') capital_message = capital_message[:i] + '(ГВЭ)' if message == 'привет': return [ "Привет. Чтобы добавить экзамен, просто напиши название предмета (названия всех доступных предметов ты можешь посмотреть, отправив сообщение 'помощь')", keyboard.keyboard([]) ] if message == 'помощь': text = 'Список предметов, доступных для отслеживания:\n\n' for n in [ 'Допуск к экзаменам', 'Русский язык', 'Математика', 'Физика', 'Химия', 'Информатика', 'Биология', 'История', 'География', 'Иностранный язык', 'Обществознание', 'Литература', 'ГВЭ' ]: text += n + '\n' text += "\nЧтобы перестать следить за экзаменом, просто напиши 'перестать следить'" return [text, keyboard.keyboard([])] if message == 'перестать следить': data[user] = [0, '-'] files.json_save('json/message_history', data) text = 'Выбери предмет:\n\n' for n in [ 'Допуск к экзаменам', 'Русский язык', 'Математика', 'Физика', 'Химия', 'Информатика', 'Биология', 'История', 'География', 'Иностранный язык', 'Обществознание', 'Литература', 'ГВЭ' ]: text += n + '\n' return [text, keyboard.keyboard([])] if capital_message in exams.keys(): if user in data: if data[user][1] == '-': data[user] = [capital_message, '-'] else: data[user] = [capital_message, '+'] else: data[user] = [capital_message, '+'] files.json_save('json/message_history', data) text = 'Выбери дату экзамена:\n\n' m = dates[exams[capital_message]] for t in m: text += t + '\n' return [text, keyboard.keyboard(m)] if message == 'математика': m = ['Математика (базовая)', 'Математика (профильная)'] text = 'Выбери уровень:\n\n' for q in m: text += q + '\n' return [text, keyboard.keyboard(m)] if message == 'иностранный язык': m = ['Английский', 'Немецкий', 'Французский', 'Испанский', 'Китайский'] text = 'Выбери язык:\n\n' for q in m: text += q + '\n' return [text, keyboard.keyboard(m)] if message in [ 'английский', 'немецкий', 'французский', 'испанский', 'китайский' ]: m = [ capital_message + ' язык (устно)', capital_message + ' язык (письменно)' ] text = 'Выбери вид:\n\n' for q in m: text += q + '\n' return [text, keyboard.keyboard(m)] if message in [ 'английский язык', 'немецкий язык', 'французский язык', 'испанский язык', 'китайский язык' ]: m = [capital_message + ' (устно)', capital_message + ' (письменно)'] text = 'Выбери вид:\n\n' for q in m: text += q + '\n' return [text, keyboard.keyboard(m)] if message == 'гвэ': m = [ 'Русский язык (ГВЭ)', 'Математика (ГВЭ)', 'Информатика (ГВЭ)', 'Обществознание (ГВЭ)' ] text = 'Выбери экзамен:\n\n' for q in m: text += q + '\n' return [text, keyboard.keyboard(m)] if message == 'допуск к экзаменам': m = ['Итоговое сочинение', 'Итоговое изложение'] text = 'Выбери экзамен:\n\n' for q in m: text += q + '\n' return [text, keyboard.keyboard(m)] poisk = r'\d\d[.]\d\d[.]\d\d\d\d' result = re.findall(poisk, message) if result and message == result[0]: m = [] if user in data.keys(): if data[user][0] == 0: text = "Сначала выберите предмет (названия всех доступных предметов ты можешь посмотреть, написав 'помощь')" elif message in dates[exams[data[user][0]]]: if data[user][1] == '+': p = baza.change('json/students', '+', exams[data[user][0]], message, user) if p == 'Успешно': text = 'Экзамен успешно добавлен' else: text = 'Этот экзамен уже есть в списке твоих экзаменов. Пожалуйста, выбери другой экзамен' else: p = baza.change('json/students', '-', exams[data[user][0]], message, user) if p == 'Успешно': text = 'Экзамен успешно удалён' else: text = "Этого экзамена нет в списке твоих экзаменов. Если хочешь, чтобы я перестал следить за каким-то экзаменом, напиши мне 'перестать следить'" del data[user] files.json_save('json/message_history', data) else: text = 'В выбранную дату этот экзамен не проходит. Попробуй выбрать другую дату:\n\n' m = dates[exams[data[user][0]]] for t in m: text += t + '\n' else: text = "Сначала выберите предмет (названия всех доступных предметов ты можешь посмотреть, написав 'помощь')" return [text, keyboard.keyboard(m)] else: return ['Не понимаю', keyboard.keyboard([])]