Best Python code snippet using pandera_python
paginator.py
Source:paginator.py
1from itertools import islice2from typing import Iterable, Any, Iterator, Callable, Coroutine3from aiogram import types, Dispatcher4from aiogram.dispatcher import FSMContext5from aiogram.dispatcher.filters import Text6from aiogram.dispatcher.filters.state import State7from aiogram.types import CallbackQuery8class Paginator:9 def __init__(10 self,11 data: types.InlineKeyboardMarkup |12 Iterable[types.InlineKeyboardButton] |13 Iterable[Iterable[types.InlineKeyboardButton]],14 state: State = None,15 callback_startswith: str = 'page_',16 size: int = 8,17 page_separator: str = '/',18 dp: Dispatcher | None = None,19 ):20 """21 Example: paginator = Paginator(data=kb, size=5)22 :param data: An iterable object that stores an InlineKeyboardButton.23 :param callback_startswith: What should callback_data begin with in handler pagination. Default = 'page_'.24 :param size: Number of lines per page. Default = 8.25 :param state: Current state.26 :param page_separator: Separator for page numbers. Default = '/'.27 """28 self.dp = dp29 self.page_separator = page_separator30 self._state = state31 self._size = size32 self._startswith = callback_startswith33 if isinstance(data, types.InlineKeyboardMarkup):34 self._list_kb = list(35 self._chunk(36 it=data.inline_keyboard,37 size=self._size38 )39 )40 elif isinstance(data, Iterable):41 self._list_kb = list(42 self._chunk(43 it=data,44 size=self._size45 )46 )47 """48 Class for pagination's in aiogram inline keyboards49 """50 def __call__(51 self,52 current_page=0,53 *args,54 **kwargs55 ) -> types.InlineKeyboardMarkup:56 """57 Example:58 await message.answer(59 text='Some menu',60 reply_markup=paginator()61 )62 :return: InlineKeyboardMarkup63 """64 _list_current_page = self._list_kb[current_page]65 paginations = self._get_paginator(66 counts=len(self._list_kb),67 page=current_page,68 page_separator=self.page_separator,69 startswith=self._startswith70 )71 keyboard = types.InlineKeyboardMarkup(72 row_width=5,73 inline_keyboard=_list_current_page74 )75 keyboard.add(*paginations)76 if self.dp:77 self.paginator_handler()78 return keyboard79 @staticmethod80 def _get_page(call: types.CallbackQuery) -> int:81 """82 :param call: CallbackQuery in paginator handler.83 :return: Current page.84 """85 return int(call.data[-1])86 @staticmethod87 def _chunk(it, size) -> Iterator[tuple[Any, ...]]:88 """89 :param it: Source iterable object.90 :param size: Chunk size.91 :return: Iterator chunks pages.92 """93 it = iter(it)94 return iter(lambda: tuple(islice(it, size)), ())95 @staticmethod96 def _get_paginator(97 counts: int,98 page: int,99 page_separator: str = '/',100 startswith: str = 'page_'101 ) -> list[types.InlineKeyboardButton]:102 """103 :param counts: Counts total buttons.104 :param page: Current page.105 :param page_separator: Separator for page numbers. Default = '/'.106 :return: Page control line buttons.107 """108 counts -= 1109 paginations = []110 if page > 0:111 paginations.append(112 types.InlineKeyboardButton(113 text='â®ï¸ï¸',114 callback_data=f'{startswith}0'115 )116 )117 paginations.append(118 types.InlineKeyboardButton(119 text='â¬
ï¸',120 callback_data=f'{startswith}{page - 1}'121 ),122 )123 paginations.append(124 types.InlineKeyboardButton(125 text=f'{page + 1}{page_separator}{counts + 1}',126 callback_data='pass'127 ),128 )129 if counts > page:130 paginations.append(131 types.InlineKeyboardButton(132 text='â¡ï¸',133 callback_data=f'{startswith}{page + 1}'134 )135 )136 paginations.append(137 types.InlineKeyboardButton(138 text='âï¸',139 callback_data=f'{startswith}{counts}'140 )141 )142 return paginations143 def paginator_handler(self) -> tuple[144 tuple[Callable[[CallbackQuery], Coroutine[Any, Any, None]], Text],145 dict[str, State | str]146 ]:147 """148 Example:149 args, kwargs = paginator.paginator_handler()150 151 dp.register_callback_query_handler(*args, **kwargs)152 :return: Data for register handler pagination.153 """154 async def _page(call: types.CallbackQuery, state: FSMContext):155 page = self._get_page(call)156 await call.message.edit_reply_markup(157 reply_markup=self.__call__(158 current_page=page159 )160 )161 await state.update_data({f'last_page_{self._startswith}': page})162 if not self.dp:163 return \164 (_page, Text(startswith=self._startswith)), \165 {'state': self._state if self._state else '*'}166 else:167 self.dp.register_callback_query_handler(168 _page,169 Text(startswith=self._startswith),170 **{'state': self._state if self._state else '*'}171 )172 # def paginator_handler(self):173 # def decorator(func):174 # def _wrapper(context: dict, *args, **kwargs):175 # func(176 # context={177 # 'startswith': self._startswith,178 # 'state': self._state,179 # 'data': self._list_kb,180 # 'size': self._size181 # },182 # *args,183 # **kwargs184 # )185 #186 # return _wrapper187 #188 # return decorator189class CheckBoxPaginator(Paginator):190 def __init__(self, data: types.InlineKeyboardMarkup |191 Iterable[types.InlineKeyboardButton] |192 Iterable[Iterable[types.InlineKeyboardButton]],193 state: State = None,194 callback_startswith: str = 'page_',195 size: int = 8,196 page_separator: str = '/',197 callback_startswith_button: str = 'select_',198 confirm_text: str = 'ÐодÑвеÑдиÑÑ',199 dp: Dispatcher | None = None):200 """201 Example: paginator = Paginator(data=kb, size=5)202 :param data: An iterable object that stores an InlineKeyboardButton.203 :param callback_startswith: What should callback_data begin with in handler pagination. Default = 'page_'.204 :param size: Number of lines per page. Default = 8.205 :param state: Current state.206 :param page_separator: Separator for page numbers. Default = '/'.207 :param callback_startswith_button: Callback start with buttons.208 :param confirm_text: Text on button confirm.209 """210 super().__init__(data, state, callback_startswith, size, page_separator, dp)211 self.dp = dp212 self.page_separator = page_separator213 self._state = state214 self._size = size215 self._startswith = callback_startswith216 self._startswith_button = callback_startswith_button217 self._confirm_text = confirm_text218 if isinstance(data, types.InlineKeyboardMarkup):219 self._list_kb = list(220 self._chunk(221 it=data.inline_keyboard,222 size=self._size223 )224 )225 elif isinstance(data, Iterable):226 self._list_kb = list(227 self._chunk(228 it=data,229 size=self._size230 )231 )232 def __call__(233 self,234 current_page=0,235 selected: list[list[types.KeyboardButton]] = None,236 *args,237 **kwargs238 ) -> types.InlineKeyboardMarkup:239 """240 Example:241 await message.answer(242 text='Some menu',243 reply_markup=paginator()244 )245 :return: InlineKeyboardMarkup246 """247 _list_current_page = self._list_kb[current_page]248 for lst in _list_current_page:249 for button in lst:250 button: types.InlineKeyboardButton251 if selected:252 if button.callback_data in selected:253 if not button.text.endswith('â
'):254 button.text += ' â
'255 else:256 if button.text.endswith(' â
'):257 button.text = button.text[:-2]258 else:259 if button.text.endswith(' â
'):260 button.text = button.text[:-2]261 paginations = self._get_paginator(262 counts=len(self._list_kb),263 page=current_page,264 page_separator=self.page_separator,265 startswith=self._startswith266 )267 keyboard = types.InlineKeyboardMarkup(268 row_width=5,269 inline_keyboard=_list_current_page270 )271 confirm_button = types.InlineKeyboardButton(272 text=self._confirm_text,273 callback_data=f'{self._confirm_text}confirm'274 )275 keyboard.add(*paginations)276 keyboard.add(confirm_button)277 if self.dp:278 self.paginator_handler()279 self.select_handler()280 return keyboard281 def paginator_handler(self) -> tuple[282 tuple[Callable[[CallbackQuery], Coroutine[Any, Any, None]], Text],283 dict[str, State | str]284 ]:285 """286 Example:287 args, kwargs = paginator.paginator_handler()288 dp.register_callback_query_handler(*args, **kwargs)289 :return: Data for register handler pagination.290 """291 async def _page(call: types.CallbackQuery, state: FSMContext):292 page = self._get_page(call)293 data = await state.get_data()294 selected = data.get(f'{self._startswith}selected', None)295 if selected:296 kb = self.__call__(current_page=page, selected=selected)297 else:298 kb = self.__call__(current_page=page)299 await state.update_data({f'{self._startswith}selected': []})300 await call.message.edit_reply_markup(301 reply_markup=kb302 )303 await state.update_data({f'last_page_{self._startswith}': page})304 if not self.dp:305 return \306 (_page, Text(startswith=self._startswith)), \307 {'state': self._state if self._state else '*'}308 else:309 self.dp.register_callback_query_handler(310 _page,311 Text(startswith=self._startswith),312 **{'state': self._state if self._state else '*'}313 )314 def select_handler(self):315 async def _select(call: types.CallbackQuery, state: FSMContext):316 data = await state.get_data()317 page = data.get(f'last_page_{self._startswith}', 0)318 selected = data.get(f'{self._startswith}selected', [])319 if selected:320 selected: list321 if call.data in selected:322 selected.remove(call.data)323 await state.update_data({f'{self._startswith}selected': selected})324 else:325 selected.append(call.data)326 await state.update_data({f'{self._startswith}selected': selected})327 await state.update_data({f'{self._startswith}selected': selected})328 data = await state.get_data()329 selected = data.get(f'{self._startswith}selected', None)330 await call.message.edit_reply_markup(331 reply_markup=self.__call__(332 current_page=page,333 selected=selected334 )335 )336 else:337 await state.update_data({f'{self._startswith}selected': [call.data, ]})338 await call.message.edit_reply_markup(339 reply_markup=self.__call__(340 current_page=page,341 selected=[call.data, ]342 )343 )344 await state.update_data({f'last_page_{self._startswith}': page})345 if not self.dp:346 return \347 (_select, Text(startswith=self._startswith_button)), \348 {'state': self._state if self._state else '*'}349 else:350 self.dp.register_callback_query_handler(351 _select,352 Text(startswith=self._startswith_button),353 **{'state': self._state if self._state else '*'}...
solution2.py
Source:solution2.py
...11 :rtype: bool12 """13 def _match(c_s, c_p):14 return c_s == c_p or c_p == '?'15 def _startswith(s, p):16 if len(s) < len(p):17 return False18 for i in xrange(len(p)):19 if not _match(s[i], p[i]):20 return False21 return True22 def _endswith(s, p, start):23 if len(s) - start < len(p):24 return False25 for i in xrange(len(p)):26 if not _match(s[-i-1], p[-i-1]):27 return False28 return True29 def _find(s, p, start):30 """31 idea32 """33 m = len(s)34 n = len(p)35 if m - start < n:36 return -137 # build table38 t = [0] * (n+1)39 i = 140 j = 041 while i < n:42 if _match(p[j], p[i]) or _match(p[i], p[j]):43 i += 144 j += 145 t[i] = j46 elif j == 0:47 i += 148 else:49 j = t[j]50 # match51 i = start52 j = 053 while i < m and j < n:54 if _match(s[i], p[j]):55 i += 156 j += 157 elif j == 0:58 i += 159 else:60 j = t[j]61 return i - n if j == n else -162 def match1(s, p):63 pos = p.find('*')64 if pos < 0:65 return len(s) == len(p) and _startswith(s, p)66 return _startswith(s, p[:pos]) and \67 _endswith(s, p[pos+1:], pos)68 ps = p.split('*')69 if len(ps) <= 2:70 return match1(s, p)71 if not _startswith(s, ps[0]):72 return False73 q = len(ps[0])74 n = len(ps)75 for i in xrange(1, n-1):76 q = _find(s, ps[i], q)77 if q < 0:78 return False79 q += len(ps[i])...
__init__.py
Source:__init__.py
...21 if not path:22 path = os.getcwd()23 self.path = path24 self.out = get(path)25 def _startswith(self, string):26 """return a list of files startswith string"""27 lines = []28 for line in self.out.splitlines():29 if line.find(string) == 0:30 lines.append(" ".join(line.split(" ")[2:]))31 return lines32 @property33 def A(self):34 """return a list of added files"""35 return self._startswith(" A")36 @property37 def D(self):38 """return a list of deleted files"""39 return self._startswith(" D")40 @property41 def M(self):42 """return a list of modified files"""43 return self._startswith(" M")44 @property45 def R(self):46 """return a list of renamed files"""47 return self._startswith(" R")48 @property49 def untracked(self):50 """return a list of untracked files"""...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!