Best Python code snippet using avocado_python
vtkMethodParser.py
Source:vtkMethodParser.py  
1"""2This python module provides functionality to parse the methods of a3VTK object.4Created by Prabhu Ramachandran.  Committed in Apr, 2002.5"""6import string, re, sys7import types8# set this to 1 if you want to see debugging messages - very useful if9# you have problems10DEBUG=011def debug (msg):12    if DEBUG:13	print msg14class VtkDirMethodParser:15    """ Parses the methods from dir(vtk_obj). """16    def initialize_methods (self, vtk_obj):17        debug ("VtkDirMethodParser:: initialize_methods ()")18	self.methods = dir (vtk_obj)[:]19	# stores the <blah>On methods20	self.toggle_meths = []21	# stores the Set<blah>To<blah> methods22	self.state_meths = []23	# stores the methods that have a Get<blah> and Set<blah>24	# only the <blah> is stored25	self.get_set_meths = []26	# pure get methods27	self.get_meths = []28	self.state_patn = re.compile ("To[A-Z0-9]")29    def parse_methods (self, vtk_obj):30	debug ("VtkDirMethodParser:: parse_methods()")31        self.initialize_methods (vtk_obj)	32	debug ("VtkDirMethodParser:: parse_methods() - initialized methods")33	34	for method in self.methods[:]:35	    # finding all the methods that set the state.36	    if string.find (method[:3], "Set") >= 0 and \37		 self.state_patn.search (method) is not None :38                try:39                    eval ("vtk_obj.Get%s"%method[3:])40                except AttributeError:41                    self.state_meths.append (method)42                    self.methods.remove (method)43            # finding all the On/Off toggle methods44	    elif string.find (method[-2:], "On") >= 0:45                try:46                    self.methods.index ("%sOff"%method[:-2])47                except ValueError:48                    pass49                else:50                    self.toggle_meths.append (method)51                    self.methods.remove (method)52                    self.methods.remove ("%sOff"%method[:-2])53	    # finding the Get/Set methods.54	    elif string.find (method[:3], "Get") == 0:55		set_m = "Set"+method[3:]56		try:57		    self.methods.index (set_m)58		except ValueError:59		    pass60		else:61		    self.get_set_meths.append (method[3:])62		    self.methods.remove (method)63		    self.methods.remove (set_m)64	self.clean_up_methods (vtk_obj)65    def clean_up_methods (self, vtk_obj):66	self.clean_get_set (vtk_obj)67	self.clean_state_methods (vtk_obj)68	self.clean_get_methods (vtk_obj)69    def clean_get_set (self, vtk_obj):70	debug ("VtkDirMethodParser:: clean_get_set()")71	# cleaning up the Get/Set methods by removing the toggle funcs.72	for method in self.toggle_meths:73	    try:74		self.get_set_meths.remove (method[:-2])75	    except ValueError:76		pass77	# cleaning them up by removing any methods that are responsible for78	# other vtkObjects79	for method in self.get_set_meths[:]:80	    try:81		eval ("vtk_obj.Get%s ().GetClassName ()"%method)82	    except (TypeError, AttributeError):83		pass84	    else:85		self.get_set_meths.remove (method)86                continue87	    try:88		val = eval ("vtk_obj.Get%s ()"%method)89	    except (TypeError, AttributeError):90		self.get_set_meths.remove (method)91	    else:92		if val is None:93		    self.get_set_meths.remove (method)94	95    def clean_state_methods (self, vtk_obj):96	debug ("VtkDirMethodParser:: clean_state_methods()")97	# Getting the remaining pure GetMethods98	for method in self.methods[:]:99	    if string.find (method[:3], "Get") == 0:100		self.get_meths.append (method)101		self.methods.remove (method)102	# Grouping similar state methods103	if len (self.state_meths) != 0:104	    tmp = self.state_meths[:]105	    self.state_meths = []106	    state_group = [tmp[0]]107	    end = self.state_patn.search (tmp[0]).start ()108	    # stores the method type common to all similar methods109	    m = tmp[0][3:end]110	    for i in range (1, len (tmp)):111		if string.find (tmp[i], m) >= 0:112		    state_group.append (tmp[i])113		else:114		    self.state_meths.append (state_group)115		    state_group = [tmp[i]]	116		    end = self.state_patn.search (tmp[i]).start ()117		    m = tmp[i][3:end]118		try: # remove the corresponding set method in get_set119		    val = self.get_set_meths.index (m)120		except ValueError:121		    pass122		else:123		    del self.get_set_meths[val]124		    #self.get_meths.append ("Get"+m)125                clamp_m = "Get" + m + "MinValue"126                try: # remove the GetNameMax/MinValue in get_meths127                    val = self.get_meths.index (clamp_m)128                except ValueError:129                    pass130                else:131                    del self.get_meths[val]132                    val = self.get_meths.index ("Get" + m + "MaxValue")133                    del self.get_meths[val]134	    if len (state_group) > 0:135		self.state_meths.append (state_group)136    def clean_get_methods (self, vtk_obj):137	debug ("VtkDirMethodParser:: clean_get_methods()")138	for method in self.get_meths[:]:139            debug (method)140            try:141		res = eval ("vtk_obj.%s ()"%method)142	    except (TypeError, AttributeError):143		self.get_meths.remove (method)144                continue145	    else:146		try:147		    eval ("vtk_obj.%s ().GetClassName ()"%method)148		except AttributeError:149		    pass150		else:151		    self.get_meths.remove (method)152                    continue153            if string.find (method[-8:], "MaxValue") > -1:154                self.get_meths.remove( method)155            elif string.find (method[-8:], "MinValue") > -1:156                self.get_meths.remove( method)157	self.get_meths.sort ()158    def toggle_methods (self):159	return self.toggle_meths160    def state_methods (self):161	return self.state_meths162    def get_set_methods (self):163	return self.get_set_meths164    def get_methods (self):165	return self.get_meths166class VtkPrintMethodParser:167    """ This class finds the methods for a given vtkObject.  It uses168    the output from vtkObject->Print() (or in Python str(vtkObject))169    and output from the VtkDirMethodParser to obtain the methods. """170    def parse_methods (self, vtk_obj):171	"Parse for the methods."172	debug ("VtkPrintMethodParser:: parse_methods()")173        if self._initialize_methods (vtk_obj):174            # if David Gobbi's improvements are in this version of VTK175            # then I need to go no further.176            return177	for method in self.methods[:]:178	    # removing methods that have nothing to the right of the ':'179	    if (method[1] == '') or \180	       (string.find (method[1], "none") > -1) :181		self.methods.remove (method)182	for method in self.methods:183	    # toggle methods are first identified184	    if (method[1] == "On") or (method[1] == "Off"):185		try:186		    val = eval ("vtk_obj.Get%s ()"%method[0])187		    if val == 1:188			eval ("vtk_obj.%sOn ()"%method[0])189		    elif val == 0:190			eval ("vtk_obj.%sOff ()"%method[0])191		except AttributeError:192		    pass193		else:194		    self.toggle_meths.append (method[0]+"On")		195	    else: # see it it is get_set or get or a state method196		found = 0197		# checking if it is a state func.198		# figure out the long names from the dir_state_meths199		for sms in self.dir_state_meths[:]:200		    if string.find (sms[0], method[0]) >= 0:201			self.state_meths.append (sms)202			self.dir_state_meths.remove (sms)203			found = 1204		if found:205		    self.get_meths.append ("Get"+method[0])206		    try:207			t = eval ("vtk_obj.Get%sAsString ()"%method[0])208		    except AttributeError:209			pass210		    else:211			self.get_meths.append ("Get"+method[0]+"AsString")212		else:213		    # the long name is inherited or it is not a state method214		    try:215			t = eval ("vtk_obj.Get%s ().GetClassName ()"%216				  method[0])217		    except AttributeError:218			pass219		    else:220			continue	221		    val = 0222		    try:223			val = eval ("vtk_obj.Get%s ()"%method[0])224		    except (TypeError, AttributeError):225			pass226		    else:227                        try:228                            f = eval ("vtk_obj.Set%s"%method[0])229                        except AttributeError:230                            self.get_meths.append ("Get"+method[0])231                        else:232                            try:233                                apply (f, val)234                            except TypeError:235                                try:236                                    apply (f, (val, ))237                                except TypeError:238                                    self.get_meths.append ("Get"+method[0])239                                else:240                                    self.get_set_meths.append (method[0])241                            else:242                                self.get_set_meths.append (method[0])243        self._clean_up_methods (vtk_obj)244    def _get_str_obj (self, vtk_obj):245	debug ("VtkPrintMethodParser:: _get_str_obj()")246	self.methods = str (vtk_obj)247	self.methods = string.split (self.methods, "\n")248	del self.methods[0]249    def _initialize_methods (self, vtk_obj):250	"Do the basic parsing and setting up"251	debug ("VtkPrintMethodParser:: _initialize_methods()")252	dir_p = VtkDirMethodParser ()253	dir_p.parse_methods (vtk_obj)254        # testing if this version of vtk has David Gobbi's cool255        # stuff. If it does then no need to do other things.256        try:257            junk = vtk_obj.__class__258        except AttributeError:259            pass260        else:261            self.toggle_meths = dir_p.toggle_methods ()262            self.state_meths = dir_p.state_methods ()263            self.get_set_meths = dir_p.get_set_methods ()264            self.get_meths = dir_p.get_methods ()265            return 1266	self.dir_toggle_meths = dir_p.toggle_methods ()267	self.dir_state_meths = dir_p.state_methods ()268	self.dir_get_set_meths = dir_p.get_set_methods ()269	self.dir_get_meths = dir_p.get_methods ()270	self._get_str_obj (vtk_obj)271	patn = re.compile ("  \S")272	for method in self.methods[:]:273	    if not patn.match (method):274		self.methods.remove (method)275	for method in self.methods[:]:276	    if string.find (method, ":") == -1:277		self.methods.remove (method)278	for i in range (0, len (self.methods)):279	    strng = self.methods[i]280	    strng = string.replace (strng, " ", "")281	    self.methods[i] = string.split (strng, ":")282	self.toggle_meths = []283	self.state_meths = []284	self.get_set_meths = []285	self.get_meths = []286        return 0287    def _clean_up_methods (self, vtk_obj):288	"Merge dir and str methods.  Finish up."289	debug ("VtkPrintMethodParser:: _clean_up_methods()")290	for meth_list in ((self.dir_toggle_meths, self.toggle_meths),\291			  (self.dir_get_set_meths, self.get_set_meths),\292			  (self.dir_get_meths, self.get_meths)):293	    for method in meth_list[0]:294		try:295		    meth_list[1].index (method)296		except ValueError:297		    meth_list[1].append (method)298	# Remove all get_set methods that are already in toggle_meths299	# This case can happen if the str produces no "On/Off" but300	# dir does and str produces a get_set instead.301	for method in self.toggle_meths:302	    try:303		self.get_set_meths.remove (method[:-2])304	    except ValueError:305		pass306	self.toggle_meths.sort ()307	self.state_meths.sort ()308	self.get_set_meths.sort ()309	self.get_meths.sort ()310    def toggle_methods (self):311	return self.toggle_meths312    def state_methods (self):313	return self.state_meths314    def get_set_methods (self):315	return self.get_set_meths316    def get_methods (self):...test_algebraic_connectivity.py
Source:test_algebraic_connectivity.py  
...81            assert_equal(nx.algebraic_connectivity(G), 0)82            assert_raises(nx.NetworkXError, nx.fiedler_vector, G,83                          method=method)84    @preserve_random_state85    def test_unrecognized_method(self):86        G = nx.path_graph(4)87        assert_raises(nx.NetworkXError, nx.algebraic_connectivity, G,88                      method='unknown')89        assert_raises(nx.NetworkXError, nx.fiedler_vector, G, method='unknown')90    @preserve_random_state91    def test_two_nodes(self):92        G = nx.Graph()93        G.add_edge(0, 1, weight=1)94        A = nx.laplacian_matrix(G)95        for method in self._methods:96            assert_almost_equal(nx.algebraic_connectivity(97                G, tol=1e-12, method=method), 2)98            x = nx.fiedler_vector(G, tol=1e-12, method=method)99            check_eigenvector(A, 2, x)100        G = nx.MultiGraph()101        G.add_edge(0, 0, spam=1e8)102        G.add_edge(0, 1, spam=1)103        G.add_edge(0, 1, spam=-2)104        A = -3 * nx.laplacian_matrix(G, weight='spam')105        for method in self._methods:106            assert_almost_equal(nx.algebraic_connectivity(107                G, weight='spam', tol=1e-12, method=method), 6)108            x = nx.fiedler_vector(G, weight='spam', tol=1e-12, method=method)109            check_eigenvector(A, 6, x)110    @preserve_random_state111    def test_path(self):112        G = nx.path_graph(8)113        A = nx.laplacian_matrix(G)114        sigma = 2 - sqrt(2 + sqrt(2))115        for method in self._methods:116            assert_almost_equal(nx.algebraic_connectivity(117                G, tol=1e-12, method=method), sigma)118            x = nx.fiedler_vector(G, tol=1e-12, method=method)119            check_eigenvector(A, sigma, x)120    @preserve_random_state121    def test_cycle(self):122        G = nx.cycle_graph(8)123        A = nx.laplacian_matrix(G)124        sigma = 2 - sqrt(2)125        for method in self._methods:126            assert_almost_equal(nx.algebraic_connectivity(127                G, tol=1e-12, method=method), sigma)128            x = nx.fiedler_vector(G, tol=1e-12, method=method)129            check_eigenvector(A, sigma, x)130    @preserve_random_state131    def test_buckminsterfullerene(self):132        G = nx.Graph(133            [(1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6),134             (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56),135             (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12),136             (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53),137             (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27),138             (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54),139             (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42),140             (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58),141             (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51),142             (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56),143             (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45),144             (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49),145             (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47),146             (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55),147             (47, 54), (48, 55)])148        for normalized in (False, True):149            if not normalized:150                A = nx.laplacian_matrix(G)151                sigma = 0.2434017461399311152            else:153                A = nx.normalized_laplacian_matrix(G)154                sigma = 0.08113391537997749155            for method in methods:156                try:157                    assert_almost_equal(nx.algebraic_connectivity(158                        G, normalized=normalized, tol=1e-12, method=method),159                        sigma)160                    x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12,161                                          method=method)162                    check_eigenvector(A, sigma, x)163                except nx.NetworkXError as e:164                    if e.args not in (('Cholesky solver unavailable.',),165                                      ('LU solver unavailable.',)):166                        raise167    _methods = ('tracemin', 'lanczos', 'lobpcg')168class TestSpectralOrdering(object):169    numpy = 1170    @classmethod171    def setupClass(cls):172        global numpy173        try:174            import numpy.linalg175            import scipy.sparse176        except ImportError:177            raise SkipTest('SciPy not available.')178    @preserve_random_state179    def test_nullgraph(self):180        for graph in (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph):181            G = graph()182            assert_raises(nx.NetworkXError, nx.spectral_ordering, G)183    @preserve_random_state184    def test_singleton(self):185        for graph in (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph):186            G = graph()187            G.add_node('x')188            assert_equal(nx.spectral_ordering(G), ['x'])189            G.add_edge('x', 'x', weight=33)190            G.add_edge('x', 'x', weight=33)191            assert_equal(nx.spectral_ordering(G), ['x'])192    @preserve_random_state193    def test_unrecognized_method(self):194        G = nx.path_graph(4)195        assert_raises(nx.NetworkXError, nx.spectral_ordering, G,196                      method='unknown')197    @preserve_random_state198    def test_three_nodes(self):199        G = nx.Graph()200        G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1)],201                                  weight='spam')202        for method in self._methods:203            order = nx.spectral_ordering(G, weight='spam', method=method)204            assert_equal(set(order), set(G))205            ok_(set([1, 3]) in (set(order[:-1]), set(order[1:])))206        G = nx.MultiDiGraph()207        G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1), (2, 3, 2)])...test_method.py
Source:test_method.py  
1import WebIDL2def WebIDLTest(parser, harness):3    parser.parse("""4        interface TestMethods {5          void basic();6          static void basicStatic();7          void basicWithSimpleArgs(boolean arg1, byte arg2, unsigned long arg3);8          boolean basicBoolean();9          static boolean basicStaticBoolean();10          boolean basicBooleanWithSimpleArgs(boolean arg1, byte arg2, unsigned long arg3);11          void optionalArg(optional byte? arg1, optional sequence<byte> arg2);12          void variadicArg(byte?... arg1);13          object getObject();14          void setObject(object arg1);15          void setAny(any arg1);16          float doFloats(float arg1);17        };18    """)19    results = parser.finish()20    harness.ok(True, "TestMethods interface parsed without error.")21    harness.check(len(results), 1, "Should be one production.")22    iface = results[0]23    harness.ok(isinstance(iface, WebIDL.IDLInterface),24               "Should be an IDLInterface")25    harness.check(iface.identifier.QName(), "::TestMethods", "Interface has the right QName")26    harness.check(iface.identifier.name, "TestMethods", "Interface has the right name")27    harness.check(len(iface.members), 12, "Expect 12 members")28    methods = iface.members29    def checkArgument(argument, QName, name, type, optional, variadic):30        harness.ok(isinstance(argument, WebIDL.IDLArgument),31                   "Should be an IDLArgument")32        harness.check(argument.identifier.QName(), QName, "Argument has the right QName")33        harness.check(argument.identifier.name, name, "Argument has the right name")34        harness.check(str(argument.type), type, "Argument has the right return type")35        harness.check(argument.optional, optional, "Argument has the right optional value")36        harness.check(argument.variadic, variadic, "Argument has the right variadic value")37    def checkMethod(method, QName, name, signatures,38                    static=False, getter=False, setter=False, creator=False,39                    deleter=False, legacycaller=False, stringifier=False):40        harness.ok(isinstance(method, WebIDL.IDLMethod),41                   "Should be an IDLMethod")42        harness.ok(method.isMethod(), "Method is a method")43        harness.ok(not method.isAttr(), "Method is not an attr")44        harness.ok(not method.isConst(), "Method is not a const")45        harness.check(method.identifier.QName(), QName, "Method has the right QName")46        harness.check(method.identifier.name, name, "Method has the right name")47        harness.check(method.isStatic(), static, "Method has the correct static value")48        harness.check(method.isGetter(), getter, "Method has the correct getter value")49        harness.check(method.isSetter(), setter, "Method has the correct setter value")50        harness.check(method.isCreator(), creator, "Method has the correct creator value")51        harness.check(method.isDeleter(), deleter, "Method has the correct deleter value")52        harness.check(method.isLegacycaller(), legacycaller, "Method has the correct legacycaller value")53        harness.check(method.isStringifier(), stringifier, "Method has the correct stringifier value")54        harness.check(len(method.signatures()), len(signatures), "Method has the correct number of signatures")55        sigpairs = zip(method.signatures(), signatures)56        for (gotSignature, expectedSignature) in sigpairs:57            (gotRetType, gotArgs) = gotSignature58            (expectedRetType, expectedArgs) = expectedSignature59            harness.check(str(gotRetType), expectedRetType,60                          "Method has the expected return type.")61            for i in range(0, len(gotArgs)):62                (QName, name, type, optional, variadic) = expectedArgs[i]63                checkArgument(gotArgs[i], QName, name, type, optional, variadic)64    checkMethod(methods[0], "::TestMethods::basic", "basic", [("Void", [])])65    checkMethod(methods[1], "::TestMethods::basicStatic", "basicStatic",66                [("Void", [])], static=True)67    checkMethod(methods[2], "::TestMethods::basicWithSimpleArgs",68                "basicWithSimpleArgs",69       [("Void",70        [("::TestMethods::basicWithSimpleArgs::arg1", "arg1", "Boolean", False, False),71         ("::TestMethods::basicWithSimpleArgs::arg2", "arg2", "Byte", False, False),72         ("::TestMethods::basicWithSimpleArgs::arg3", "arg3", "UnsignedLong", False, False)])])73    checkMethod(methods[3], "::TestMethods::basicBoolean", "basicBoolean", [("Boolean", [])])74    checkMethod(methods[4], "::TestMethods::basicStaticBoolean", "basicStaticBoolean", [("Boolean", [])], static=True)75    checkMethod(methods[5], "::TestMethods::basicBooleanWithSimpleArgs",76                "basicBooleanWithSimpleArgs",77       [("Boolean",78        [("::TestMethods::basicBooleanWithSimpleArgs::arg1", "arg1", "Boolean", False, False),79         ("::TestMethods::basicBooleanWithSimpleArgs::arg2", "arg2", "Byte", False, False),80         ("::TestMethods::basicBooleanWithSimpleArgs::arg3", "arg3", "UnsignedLong", False, False)])])81    checkMethod(methods[6], "::TestMethods::optionalArg",82                "optionalArg",83       [("Void",84        [("::TestMethods::optionalArg::arg1", "arg1", "ByteOrNull", True, False),85         ("::TestMethods::optionalArg::arg2", "arg2", "ByteSequence", True, False)])])86    checkMethod(methods[7], "::TestMethods::variadicArg",87                "variadicArg",88       [("Void",89        [("::TestMethods::variadicArg::arg1", "arg1", "ByteOrNull", True, True)])])90    checkMethod(methods[8], "::TestMethods::getObject",91                "getObject", [("Object", [])])92    checkMethod(methods[9], "::TestMethods::setObject",93                "setObject",94       [("Void",95        [("::TestMethods::setObject::arg1", "arg1", "Object", False, False)])])96    checkMethod(methods[10], "::TestMethods::setAny",97                "setAny",98       [("Void",99        [("::TestMethods::setAny::arg1", "arg1", "Any", False, False)])])100    checkMethod(methods[11], "::TestMethods::doFloats",101                "doFloats",102       [("Float",103        [("::TestMethods::doFloats::arg1", "arg1", "Float", False, False)])])104    parser = parser.reset()105    threw = False106    try:107        parser.parse("""108          interface A {109            void foo(optional float bar = 1);110          };111        """)112        results = parser.finish()113    except Exception, x:114        threw = True115    harness.ok(not threw, "Should allow integer to float type corecion")116    parser = parser.reset()117    threw = False118    try:119        parser.parse("""120          interface A {121            [GetterThrows] void foo();122          };123        """)124        results = parser.finish()125    except Exception, x:126        threw = True127    harness.ok(threw, "Should not allow [GetterThrows] on methods")128    parser = parser.reset()129    threw = False130    try:131        parser.parse("""132          interface A {133            [SetterThrows] void foo();134          };135        """)136        results = parser.finish()137    except Exception, x:138        threw = True139    harness.ok(threw, "Should not allow [SetterThrows] on methods")140    parser = parser.reset()141    threw = False142    try:143        parser.parse("""144          interface A {145            [Throw] void foo();146          };147        """)148        results = parser.finish()149    except Exception, x:150        threw = True151    harness.ok(threw, "Should spell [Throws] correctly on methods")152    parser = parser.reset()153    threw = False154    try:155        parser.parse("""156          interface A {157            void __noSuchMethod__();158          };159        """)160        results = parser.finish()161    except Exception, x:162        threw = True...methods.py
Source:methods.py  
...74        cls, arith_method, comp_method, bool_method, special=True75    )76    # inplace operators (I feel like these should get passed an `inplace=True`77    # or just be removed78    def _wrap_inplace_method(method):79        """80        return an inplace wrapper for this method81        """82        def f(self, other):83            result = method(self, other)84            if (85                self.ndim == 186                and result._indexed_same(self)87                and is_dtype_equal(result.dtype, self.dtype)88            ):89                # GH#36498 this inplace op can _actually_ be inplace.90                self._values[:] = result._values91                return self92            # Delete cacher93            self._reset_cacher()94            # this makes sure that we are aligned like the input95            # we are updating inplace so we want to ignore is_copy96            self._update_inplace(97                result.reindex_like(self, copy=False), verify_is_copy=False98            )99            return self100        name = method.__name__.strip("__")101        f.__name__ = f"__i{name}__"102        return f103    new_methods.update(104        dict(105            __iadd__=_wrap_inplace_method(new_methods["__add__"]),106            __isub__=_wrap_inplace_method(new_methods["__sub__"]),107            __imul__=_wrap_inplace_method(new_methods["__mul__"]),108            __itruediv__=_wrap_inplace_method(new_methods["__truediv__"]),109            __ifloordiv__=_wrap_inplace_method(new_methods["__floordiv__"]),110            __imod__=_wrap_inplace_method(new_methods["__mod__"]),111            __ipow__=_wrap_inplace_method(new_methods["__pow__"]),112        )113    )114    new_methods.update(115        dict(116            __iand__=_wrap_inplace_method(new_methods["__and__"]),117            __ior__=_wrap_inplace_method(new_methods["__or__"]),118            __ixor__=_wrap_inplace_method(new_methods["__xor__"]),119        )120    )121    _add_methods(cls, new_methods=new_methods)122def add_flex_arithmetic_methods(cls):123    """124    Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``)125    to the class.126    Parameters127    ----------128    cls : class129        flex methods will be defined and pinned to this class130    """131    flex_arith_method, flex_comp_method, _, _, _ = _get_method_wrappers(cls)132    new_methods = _create_methods(133        cls, flex_arith_method, flex_comp_method, bool_method=None, special=False134    )135    new_methods.update(136        dict(137            multiply=new_methods["mul"],138            subtract=new_methods["sub"],139            divide=new_methods["div"],140        )141    )142    # opt out of bool flex methods for now143    assert not any(kname in new_methods for kname in ("ror_", "rxor", "rand_"))144    _add_methods(cls, new_methods=new_methods)145def _create_methods(cls, arith_method, comp_method, bool_method, special):146    # creates actual methods based upon arithmetic, comp and bool method147    # constructors.148    have_divmod = issubclass(cls, ABCSeries)149    # divmod is available for Series150    new_methods = dict(151        add=arith_method(cls, operator.add, special),152        radd=arith_method(cls, radd, special),153        sub=arith_method(cls, operator.sub, special),154        mul=arith_method(cls, operator.mul, special),155        truediv=arith_method(cls, operator.truediv, special),156        floordiv=arith_method(cls, operator.floordiv, special),157        mod=arith_method(cls, operator.mod, special),158        pow=arith_method(cls, operator.pow, special),159        # not entirely sure why this is necessary, but previously was included160        # so it's here to maintain compatibility161        rmul=arith_method(cls, rmul, special),162        rsub=arith_method(cls, rsub, special),163        rtruediv=arith_method(cls, rtruediv, special),164        rfloordiv=arith_method(cls, rfloordiv, special),165        rpow=arith_method(cls, rpow, special),166        rmod=arith_method(cls, rmod, special),167    )168    new_methods["div"] = new_methods["truediv"]169    new_methods["rdiv"] = new_methods["rtruediv"]170    if have_divmod:171        # divmod doesn't have an op that is supported by numexpr172        new_methods["divmod"] = arith_method(cls, divmod, special)173        new_methods["rdivmod"] = arith_method(cls, rdivmod, special)174    new_methods.update(175        dict(176            eq=comp_method(cls, operator.eq, special),177            ne=comp_method(cls, operator.ne, special),178            lt=comp_method(cls, operator.lt, special),179            gt=comp_method(cls, operator.gt, special),180            le=comp_method(cls, operator.le, special),181            ge=comp_method(cls, operator.ge, special),182        )183    )184    if bool_method:185        new_methods.update(186            dict(187                and_=bool_method(cls, operator.and_, special),188                or_=bool_method(cls, operator.or_, special),189                xor=bool_method(cls, operator.xor, special),190                rand_=bool_method(cls, rand_, special),191                ror_=bool_method(cls, ror_, special),192                rxor=bool_method(cls, rxor, special),193            )194        )195    if special:196        dunderize = lambda x: f"__{x.strip('_')}__"197    else:198        dunderize = lambda x: x199    new_methods = {dunderize(k): v for k, v in new_methods.items()}200    return new_methods201def _add_methods(cls, new_methods):202    for name, method in new_methods.items():...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!!
