Best Python code snippet using molotov_python
settings.py
Source:settings.py  
1from typing import MappingView2from discord.ext import commands3from importlib import reload4import discord5import inspect6import helpers7import re8class Settings(commands.Cog, description=""):9    def __init__(self, bot):10        self.osts = bot11        self.cog_name = "Settings"12        self.data = helpers.get_toml("data")13    # ==================================================14    # Unload Event15    # ==================================================16    def cog_unload(self):17        helpers.log(text="Unloaded", cog=self.cog_name)18    # ==================================================19    # Server settings20    # ==================================================21    @commands.command(aliases=["ss"], brief="Change server-specific settings!", help="""\22        __**Server Settings**__23        Change server-specific settings to whatever you like!24        __Viewing Server Settings__25        `[prefix]server_settings list`26        27        __Changing the Bot's Prefix__28        `[prefix]server_settings prefix os.`29        `[prefix]server_settings prefix !`30        __Toggling Invocation Deletion__31        `[prefix]server_settings delete_command`32        """)33    @commands.has_permissions(manage_guild=True)34    async def server_settings(self, ctx, _one="", _two=""):35        server_data = helpers.get_toml(f"servers/{ctx.guild.id}")36        if server_data.get("delete_invocation") == True:37            await helpers.try_delete(ctx)38    39        if _one not in ["prefix", "delete_command", "list"]:40            return await helpers.give_output(41                embed_title = f"the {re.sub(r'_', ' ', inspect.stack()[0][3])} command!",42                embed_content = re.sub(r"\[prefix\]", self.osts.command_prefix(self.osts, ctx.message), self.osts.get_command(inspect.stack()[0][3]).help),43                ctx = ctx44            )45    46        # ==================================================47        # If theyre listing the servers settings48        # ==================================================49        if _one == "list":50            embed = helpers.make_embed(51                title = helpers.success_title(ctx),52                content = "Here are this server's settings!",53                ctx = ctx54            )55            embed.add_field(56                name = "Prefix",57                value = server_data.get("prefix"),58                inline = True59            )60            embed.add_field(61                name = "Command Message Deletion",62                value = "Enabled" if server_data.get("delete_invocation") else "Disabled"63            )64            return await helpers.give_output(65                embed = embed,66                log_text = "Listed server settings",67				cog = self.cog_name,68                ctx = ctx69            )70        71        # ==================================================72        # If theyre changing the bots prefix73        # ==================================================74        if _one == "prefix":75            previous_prefix = server_data.get("prefix")76            if not previous_prefix:77                previous_prefix = "None"78            server_data["prefix"] = _two79            return await helpers.give_output(80                embed_title = helpers.success_title(ctx),81                embed_content = f"My prefix has been changed from \"{previous_prefix}\" to \"{_two}\"!",82                log_text = f"Changed server prefix to {_two}",83                ctx = ctx,84				cog = self.cog_name,85                data = server_data,86                data_file = f"servers/{ctx.guild.id}"87            )88        # ==================================================89        # If theyre toggling invocation deletion90        # ==================================================91        if _one == "delete_command":92            if server_data.get("delete_invocation"):93                server_data["delete_invocation"] = not server_data["delete_invocation"]94            else:95                server_data["delete_invocation"] = True96            return await helpers.give_output(97                embed_title = helpers.success_title(ctx),98                embed_content = f"Command deletion has been {'enabled' if server_data['delete_invocation'] else 'disabled'}!",99                log_text = f"Toggled invocation deletion",100                ctx = ctx,101				cog = self.cog_name,102                data = server_data,103                data_file = f"servers/{ctx.guild.id}"104            )105    # ==================================================106    # User settings107    # ==================================================108    @commands.command(aliases=["us"], brief="Change user-specific settings!", help="""\109        __**User Settings**__110        Change user-specific settings to whatever you like!111        __Viewing Your Settings__112        `[prefix]user_settings list`113       114        __Changing Your Color__115        `[prefix]user_settings color FFFF00`116        __Changing Your Prefix__117        `[prefix]user_settings prefix os.`118        `[prefix]user_settings prefix !`119        __Changing Your Success Title__120        This is the title that gets displayed when a command is a success.121        `[prefix]user_settings success Alright!`122        __Changing Your Error Title__123        This is the title that gets displayed when a command is a error.124        `[prefix]user_settings error Whoops!`125        """)126    async def user_settings(self, ctx, _one="", *, _two=""):127        server_data = helpers.get_toml(f"servers/{ctx.guild.id}")128        if server_data.get("delete_invocation") == True:129            await helpers.tryDelete(ctx)130    131        # ==================================================132        # If they didnt enter a correct category133        # Give them the help message134        # ==================================================135        if _one not in ["list", "color", "prefix", "success", "error"]:136            return await helpers.give_output(137                embed_title = f"the {re.sub(r'_', ' ', inspect.stack()[0][3])} command!",138                embed_content = re.sub(r"\[prefix\]", self.osts.command_prefix(self.osts, ctx.message), self.osts.get_command(inspect.stack()[0][3]).help),139                ctx = ctx140            )141        # ==================================================142        # Yoink user data143        # ==================================================144        user_data = helpers.get_toml(f"users/{ctx.author.id}")145    146        # ==================================================147        # If theyre viewing their settings148        # ==================================================149        if _one == "list":150            embed = helpers.make_embed(151                title = helpers.success_title(ctx),152                content = "Here are your user settings",153                ctx = ctx154            )155            embed.add_field(156                name = "Color",157                value = user_data.get("color"),158                inline = True159            )160            embed.add_field(161                name = "Prefix",162                value = user_data.get("prefix"),163                inline = True164            )165            embed.add_field(166                name = "Success Title",167                value = user_data.get("success title"),168                inline = True169            )170            embed.add_field(171                name = "Error Title",172                value = user_data.get("error title"),173                inline = True174            )175            return await helpers.give_output(176                embed = embed,177                log_text = f"Listed their user settings",178				cog = self.cog_name,179                ctx = ctx180            )181        182        # ==================================================183        # If theyre changing the color184        # ==================================================185        if _one == "color":186            try:187                _temp = int("0x" + _two, 0)188            except:189                return await helpers.give_output(190                    embed_title = helpers.error_title(ctx),191                    embed_content = "That wasn't a valid color!",192                    log_text = f"Tried to change their color to an invalid color",193                    cog = self.cog_name,194                    ctx = ctx195                )196            previous_color = None197            if user_data.get("color"):198                previous_color = user_data["color"]199            user_data["color"] = _two200            return await helpers.give_output(201                embed_title = helpers.success_title(ctx),202                embed_content = f"Your color has been changed {'to' if not previous_color else f'from {previous_color} to'} {_two}",203                log_text = f"Changed user color to {_two}",204                ctx = ctx,205				cog = self.cog_name,206                data = user_data,207                data_file = f"users/{ctx.author.id}"208            )209        # ==================================================210        # If theyre changing their prefix211        # ==================================================212        if _one == "prefix":213            previous_prefix = None214            if user_data.get("prefix"):215                previous_prefix = user_data["prefix"]216            user_data["prefix"] = _two217            if _two == "":218                user_data["prefix"] = "os."219            return await helpers.give_output(220                embed_title = helpers.success_title(ctx),221                embed_content = f"Your prefix has been changed {'to' if not previous_prefix else f'from {previous_prefix} to'} {user_data['prefix']}",222                log_text = f"Changed user prefix to {_two}",223                ctx = ctx,224				cog = self.cog_name,225                data = user_data,226                data_file = f"users/{ctx.author.id}"227            )228        if _one == "success":229            user_data["success title"] = _two230            if _two == "":231                user_data["success title"] = "Alright!"232            return await helpers.give_output(233                embed_title = helpers.success_title(ctx),234                embed_content = f"Your success message is now \"{_two}\"!",235                log_text = f"Changed their user success title to {_two}",236                ctx = ctx,237                cog = self.cog_name,238                data = user_data,239                data_file = f"users/{ctx.author.id}"240            )241        if _one == "error":242            user_data["error title"] = _two243            if _two == "":244                user_data["error title"] = "Whoops!"245            return await helpers.give_output(246                embed_title = helpers.success_title(ctx),247                embed_content = f"Your error message is now \"{_two}\"!",248                log_text = f"Changed their user error title to {_two}",249                ctx = ctx,250                cog = self.cog_name,251                data = user_data,252                data_file = f"users/{ctx.author.id}"253            )254def setup(bot):255    helpers.log(text="Loaded", cog="Settings")256    bot.add_cog(Settings(bot))...triangle.py
Source:triangle.py  
1# This Python file uses the following encoding: utf-823from abc import abstractmethod45from line_segment import LineSegment2D, LineSegment3D6from points import Point3D, Point2D789class BaseTriangle:10    # Baseclass for a triangle1112    def __init__(self, one, two, three):13        for p in [one, two, three]:14            if not isinstance(p, (Point2D, Point3D)):15                raise TypeError("A triangle must be created using Point3D points")16        if len({one.dimension, two.dimension, three.dimension}) != 1:17            raise ValueError("")18        self._one = one19        self._two = two20        self._three = three2122    @property23    def vertex_1(self):24        return self._one2526    @property27    def vertex_2(self):28        return self._two2930    @property31    def vertex_3(self):32        return self._three3334    @property35    @abstractmethod36    def boundary(self):37        pass383940class Triangle2D(BaseTriangle):41    def __init__(self, one, two, three):42        for p in [one, two, three]:43            if not isinstance(p, Point2D):44                raise TypeError("A Triangle2D must be created using Point2D points")45        super().__init__(one, two, three)4647    @property48    def boundary(self):49        return [LineSegment2D(self._one, self._two), LineSegment2D(self._two, self._three),50                LineSegment2D(self._three, self._one)]515253class Triangle3D(BaseTriangle):54    def __init__(self, one, two, three):55        for p in [one, two, three]:56            if not isinstance(p, Point3D):57                raise TypeError("A Triangle3D must be created using Point3D points")58        super().__init__(one, two, three)5960    @property61    def boundary(self):62        return [LineSegment3D(self._one, self._two), LineSegment3D(self._two, self._three),63                LineSegment3D(self._three, self._one)]6465    def translate(self, vector):66        result = Triangle3D(self._one + vector, self._two + vector, self._three + vector)67        return result6869    def scale(self, scale):70        result = Triangle3D(self._one * scale, self._two * scale, self._three * scale)71        return result7273    def project(self, projection):74        return Triangle2D(projection.project(self._one), projection.project(self._two),
...calculator.py
Source:calculator.py  
1import datetime2def print_result(numb1, numb2, result, op):3    print(str(numb1) + " " + op + " " + str(numb2) + " = " + str(result))4def finish_app():5    if operation[0] == "s":6        return True7    return False8def is_number1_float(_one):9    try:10        float(_one)11    except ValueError:12        return False13    return True14def is_number2_float(_two):15    try:16        float(_two)17    except ValueError:18        return False19    return True20def symb_valid(_symb):21    if _symb == "+":22        return True23    if _symb == "-":24        return True25    if _symb == "*":26        return True27    if _symb == "/":28        return True29    return False30def calculate(_one, _two, _symb):31    result = None32    if _symb == "+":33        result = _one + _two34    if _symb == "-":35        result = _one - _two36    if _symb == "*":37        result = _one * _two38    if _symb == "/":39        result = _one / _two40    return result41print("Witaj w moim kalkulatorze w jÄzyku Python!")42while True:43    print(" ")44    print("Wprowadź dziaÅanie (np. 5 + 7 lub 4 * 8, s aby zakoÅczyÄ)")45    operation = input()46    operation = operation.split()47    one = operation[0]48    if finish_app():49        print(" ")50        print("DziÄkujÄ za korzystanie z kalkulatora!")51        exit(0)52    two = operation[2]53    symb = str(operation[1])54    if not is_number1_float(one) or not is_number2_float(two):55        print("PodaÅeÅ niepoprawnÄ
 liczbÄ.")56        continue57    if not symb_valid(symb):58        print("PodaÅeÅ niepoprawny symbol.")59        continue60    one = float(one)61    two = float(two)62    result = "{} {} {} = {}".format(one, symb, two, calculate(one, two, symb))63    print(result)64    log = open("logs/calculator_log.txt", "a+")65    log.write("[{}] DziaÅanie: {}\n".format(datetime.datetime.now(), result))...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!!
