Best Python code snippet using hypothesis
test_from_dtype.py
Source: test_from_dtype.py
...86 # See https://github.com/numpy/numpy/issues/1536387 pass88@pytest.mark.xfail(strict=False, reason="mitigation for issue above")89def test_unicode_string_dtypes_need_not_be_utf8():90 def cannot_encode(string):91 try:92 string.encode("utf-8")93 return False94 except UnicodeEncodeError:95 return True96 find_any(nps.from_dtype(np.dtype("U")), cannot_encode)97@given(st.data())98def test_byte_string_dtypes_generate_unicode_strings(data):99 dt = data.draw(nps.byte_string_dtypes())100 result = data.draw(nps.from_dtype(dt))101 assert isinstance(result, bytes)102@pytest.mark.parametrize("dtype", ["U", "S", "a"])103def test_unsized_strings_length_gt_one(dtype):104 # See https://github.com/HypothesisWorks/hypothesis/issues/2229...
app.py
Source: app.py
1import logging2from io import BytesIO3from aiogram import Bot, Dispatcher, executor, types4from aiogram.utils.exceptions import MessageError, MessageTextIsEmpty5import morse6from config import Config7CANNOT_ENCODE = r"""ÐзвиниÑе, не полÑÑилоÑÑ Ð·Ð°ÐºÐ¾Ð´Ð¸ÑоваÑÑ ÑÑо ÑообÑение.8ÐзбÑка ÐоÑзе ÑоÑÑÐ¾Ð¸Ñ ÑолÑко из бÑкв (английÑкиÑ
и ÑÑÑÑкиÑ
), ÑиÑÑ Ð¸ ÑледÑÑÑиÑ
знаков пÑепинаниÑ:9`. , : ; ( ) ' " - \ _ ? ! + @`10СкоÑее вÑего, Ð²Ñ Ñ
оÑиÑе закодиÑоваÑÑ ÑообÑение, ÑоÑÑоÑÑее ÑолÑко из Ñимволов, коÑоÑÑÑ
Ð½ÐµÑ Ð² азбÑке ÐоÑзе11"""12MSG_TOO_LONG = "ÐзвиниÑе, ÑÑо ÑообÑение полÑÑилоÑÑ ÑлиÑком длиннÑм"13config = Config()14logging.basicConfig(15 format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',16 level=config.loglevel,17)18logger = logging.getLogger(__name__)19bot = Bot(token=config.token)20dispatcher = Dispatcher(bot)21def format_error(message: str) -> str:22 return f"𤷠{message}"23@dispatcher.errors_handler()24async def global_error_handler(update, exception):25 logger.exception(f"Update: {update}\n{exception}")26@dispatcher.message_handler()27async def echo(message: types.Message):28 message_translated = morse.text_to_morse(message.text)29 if not message_translated.strip():30 await message.answer(format_error(CANNOT_ENCODE), parse_mode='markdown')31 elif len(message_translated) > 1024:32 # TODO Split long messages into smaller ones33 await message.answer(format_error(MSG_TOO_LONG))34 else:35 bot_info = await bot.get_me()36 await types.ChatActions.record_audio()37 sound = morse.morse_to_sound(message_translated)38 await types.ChatActions.upload_audio()39 await message.answer_audio(40 audio=BytesIO(sound),41 caption=message_translated.replace("-", "â").replace(".", "·"),42 performer=bot_info["username"],43 # TODO filename=f"{performer} - {title}.mp3",44 title=message.text,45 )46async def on_startup(dp):47 await bot.set_webhook(config.webhook_url + config.webhook_path)48async def on_shutdown(dp):49 pass50def main():51 if config.use_webhook:52 logger.debug("Using webhook")53 executor.start_webhook(54 dispatcher=dispatcher,55 webhook_path=config.webhook_path,56 skip_updates=True,57 on_startup=on_startup, on_shutdown=on_shutdown,58 host=config.host, port=config.port59 )60 else:61 logger.debug("Using polling")62 executor.start_polling(dispatcher, skip_updates=True)63if __name__ == "__main__":...
tweet_kentt.py
Source: tweet_kentt.py
1import json2import tweepy3import socket4import sys5def initialize():6 with open("/home/kentt/pems/twitter/config.json") as config_data:7 config = json.load(config_data)8 auth = tweepy.OAuthHandler(config['consumer_key'], config['consumer_secret'])9 auth.set_access_token(config['access_token'], config['access_token_secret'])10 api = tweepy.API(auth)11 stream = TwitterStreamListener()12 twitter_stream = tweepy.Stream(auth = api.auth, listener=stream)13 twitter_stream.filter(track=['python'], async=True)14class TwitterStreamListener(tweepy.StreamListener):15 def on_data(self, data):16 17 data_dict=json.loads(data)18 19 try:20 text = str(data_dict["lang"])+' : '+str(data_dict["text"].decode('utf_8'))21 except:22 text = "Cannot_encode"23 print text24 #except KeyboardInterrupt:25 # print('Aborting on Ctrl-c, goodbye!')26 # pass27 #def on_error(self, status_code):28 # try:29 # if status_code == 420:30 # return False31 # except KeyboardInterrupt:32 # print('Aborting on Ctrl-c, goodbye!')33 # pass34 35if __name__ == "__main__":36 initialize()...
Check out the latest blogs from LambdaTest on this topic:
Before we discuss the Joomla testing, let us understand the fundamentals of Joomla and how this content management system allows you to create and maintain web-based applications or websites without having to write and implement complex coding requirements.
In today’s world, an organization’s most valuable resource is its customers. However, acquiring new customers in an increasingly competitive marketplace can be challenging while maintaining a strong bond with existing clients. Implementing a customer relationship management (CRM) system will allow your organization to keep track of important customer information. This will enable you to market your services and products to these customers better.
How do we acquire knowledge? This is one of the seemingly basic but critical questions you and your team members must ask and consider. We are experts; therefore, we understand why we study and what we should learn. However, many of us do not give enough thought to how we learn.
Testing is a critical step in any web application development process. However, it can be an overwhelming task if you don’t have the right tools and expertise. A large percentage of websites still launch with errors that frustrate users and negatively affect the overall success of the site. When a website faces failure after launch, it costs time and money to fix.
Mobile application development is on the rise like never before, and it proportionally invites the need to perform thorough testing with the right mobile testing strategies. The strategies majorly involve the usage of various mobile automation testing tools. Mobile testing tools help businesses automate their application testing and cut down the extra cost, time, and chances of human error.
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!!