Best Python code snippet using sure_python
graph_callable_test.py
Source:graph_callable_test.py  
...28class GraphCallableTest(test.TestCase):29  def testBasic(self):30    @graph_callable.graph_callable(31        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])32    def my_function(x):33      v = variable_scope.get_variable(34          "v", initializer=init_ops.zeros_initializer(), shape=())35      return v + x36    self.assertEqual(37        2, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())38    my_function.variables[0].assign(1.)39    self.assertEqual(40        3, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())41  def testFunctionWithoutReturnValue(self):42    @graph_callable.graph_callable(43        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])44    def my_function(x):45      v = variable_scope.get_variable(46          "v", initializer=init_ops.zeros_initializer(), shape=())47      v.assign(x)48    my_function(constant_op.constant(4, dtype=dtypes.float32))49    self.assertAllEqual(4, my_function.variables[0].read_value())50  def testFunctionWithoutReturnValueAndArgs(self):51    @graph_callable.graph_callable([])52    def my_function():53      v = variable_scope.get_variable(54          "v", initializer=init_ops.zeros_initializer(), shape=())55      v.assign(4)56    my_function()57    self.assertAllEqual(4, my_function.variables[0].read_value())58  def testVariableAPI(self):59    @graph_callable.graph_callable(60        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])61    def my_function(x):62      v = variable_scope.get_variable(63          "v", initializer=init_ops.zeros_initializer(), shape=())64      return v.read_value() + x65    self.assertEqual(66        2, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())67    my_function.variables[0].assign(1.)68    self.assertEqual(69        3, my_function(constant_op.constant(2, dtype=dtypes.float32)).numpy())70  def testTensorShape(self):71    @graph_callable.graph_callable(72        [graph_callable.ShapeAndDtype(shape=(1), dtype=dtypes.float32)])73    def my_function(x):74      _ = x.get_shape()75      v = variable_scope.get_variable(76          "v", initializer=init_ops.zeros_initializer(), shape=[x.shape[0]])77      self.assertEqual(v.shape[0], x.shape[0])78      return v + x79    self.assertEqual([2.],80                     my_function(81                         constant_op.constant([2.],82                                              dtype=dtypes.float32)).numpy())83  def testUpdatesAreOrdered(self):84    @graph_callable.graph_callable(85        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])86    def my_function(x):87      v = variable_scope.get_variable(88          "v", initializer=init_ops.zeros_initializer(), shape=())89      v.assign(x + 1)90      v.assign(v * x)91      return v.read_value()92    self.assertAllEqual(my_function(constant_op.constant(2.0)), 6.0)93  def testEmptyInitializer(self):94    @graph_callable.graph_callable(95        [graph_callable.ShapeAndDtype(shape=(1), dtype=dtypes.float32)])96    def my_function(x):97      v = variable_scope.get_variable("v", shape=[1])98      return x + 0 * v99    self.assertEqual([2.],100                     my_function(101                         constant_op.constant([2.],102                                              dtype=dtypes.float32)).numpy())103  def testMismatchingNumArgs(self):104    # pylint: disable=anomalous-backslash-in-string105    with self.assertRaisesRegexp(TypeError,106                                 "The number of arguments accepted by the "107                                 "decorated function `my_function` \(2\) must "108                                 "match the number of ShapeAndDtype objects "109                                 "passed to the graph_callable\(\) decorator "110                                 "\(1\)."):111      @graph_callable.graph_callable([112          graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)])113      def my_function(x, y):  # pylint: disable=unused-variable114        return x + y115    # pylint: enable=anomalous-backslash-in-string116  def testPureFunction(self):117    @graph_callable.graph_callable(118        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])119    def f(x):120      return math_ops.add(x, constant_op.constant(3))121    self.assertAllEqual(5, f(constant_op.constant(2)))122  def testNestedFunction(self):123    # TensorFlow function (which is what would be used in TensorFlow graph124    # construction).125    @function.Defun(dtypes.int32, dtypes.int32)126    def add(a, b):127      return math_ops.add(a, b)128    # A graph_callable that will invoke the TensorFlow function.129    @graph_callable.graph_callable(130        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])131    def add_one(x):132      return add(x, 1)133    self.assertAllEqual(3, add_one(constant_op.constant(2)))134  # TODO(ashankar): Make this work.135  # The problem is that the two graph_callables (for add_one and add_two)136  # are both trying to register the FunctionDef corresponding to "add".137  def DISABLED_testRepeatedUseOfSubFunction(self):138    @function.Defun(dtypes.int32, dtypes.int32)139    def add(a, b):140      return math_ops.add(a, b)141    @graph_callable.graph_callable(142        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])143    def add_one(x):144      return add(x, 1)145    @graph_callable.graph_callable(146        [graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.int32)])147    def add_two(x):148      return add(x, 2)149    two = constant_op.constant(2)150    self.assertAllEqual(3, add_one(two))151    self.assertAllEqual(4, add_two(two))152  def testNestedSequenceInputs(self):153    sd = graph_callable.ShapeAndDtype(shape=(), dtype=dtypes.float32)154    @graph_callable.graph_callable([[sd, tuple([sd, sd]), sd]])155    def my_op(inputs):156      a, b, c = inputs157      e, f = b158      v = variable_scope.get_variable(159          "my_v", initializer=init_ops.zeros_initializer(), shape=())160      return [a + a + v, tuple([e + e, f + f]), c + c], a + e + f + c + v161    inputs = [constant_op.constant(1.),162              [constant_op.constant(2.), constant_op.constant(3.)],163              constant_op.constant(4.)]164    ret = my_op(inputs)165    self.assertEqual(len(ret), 2.)166    self.assertAllEqual(ret[1], 10.)167    my_op.variables[0].assign(1.)168    ret = my_op(inputs)169    self.assertAllEqual(ret[1], 11.)170  def testVariableShapeIsTensorShape(self):171    @graph_callable.graph_callable([])172    def my_function():173      v = variable_scope.get_variable(174          "v", initializer=init_ops.zeros_initializer(), shape=())175      self.assertIsInstance(v.get_shape(), tensor_shape.TensorShape)176    my_function()177  def testIncorrectlyShapedInputs(self):178    @graph_callable.graph_callable(179        [graph_callable.ShapeAndDtype(shape=(3), dtype=dtypes.float32)])180    def my_function(x):181      v = variable_scope.get_variable(182          "v", initializer=init_ops.zeros_initializer(), shape=())183      return v + x184    with self.assertRaises(ValueError):185      my_function([1, 2])186    self.assertTrue(([1, 2, 3] == my_function(187        constant_op.constant([1, 2, 3], dtype=dtypes.float32)).numpy()).all())188  def testGradients(self):189    @graph_callable.graph_callable([])190    def my_function():191      v = variable_scope.get_variable(192          "v", initializer=init_ops.constant_initializer(3.), shape=())193      return v * v194    grad_fn = backprop.implicit_grad(my_function)195    grads_and_vars = list(zip(*grad_fn()))196    self.assertAllEqual(6., grads_and_vars[0][0])197if __name__ == "__main__":...main.py
Source:main.py  
...6pro = df2['product_line'].tolist()7Volume = df2['volume_in_kg'].tolist()8Gross = df2['gross_sales'].tolist()9margin = df2['gm'].tolist()10def my_function(dup):11    return list(dict.fromkeys(dup))12mylist = my_function(new1)13print('Unique Customer', mylist)14def my_fun(myfun):15    return list(dict.fromkeys(myfun))16mylis = my_fun(pro)17print('Unique product', mylis)18def my_function(Vol):19    return sum(Vol)20print('Sum of Volume', my_function(Volume))21def my_function(Vol):22    return np.mean(Vol)23print('Mean of Volume', my_function(Volume))24def my_function(Vol):25    return np.median(Vol)26print('Median of Volume', my_function(Volume))27def my_function(Vol):28    return np.min(Vol)29print('Min of Volume', my_function(Volume))30def my_function(Vol):31    return np.max(Vol)32print('Max of Volume', my_function(Volume))33def my_function(Vol):34    return np.std(Vol)35print('Std of Volume', my_function(Volume))36def my_function(Vol):37    return np.var(Vol)38print('Var of Volume', my_function(Volume))39def my_function(Gs):40    return sum(Gs)41print('Sum of Sales', my_function(Gross))42def my_function(Gs):43    return np.mean(Gs)44print('Mean of Sales', my_function(Gross))45def my_function(Gs):46    return np.median(Gs)47print('Median of Sales', my_function(Gross))48def my_function(Gs):49    return np.min(Gs)50print('Min of Sales', my_function(Gross))51def my_function(Gs):52    return np.max(Gs)53print('Max of Sales', my_function(Gross))54def my_function(Gs):55    return np.std(Gs)56print('Std of Sales', my_function(Gross))57def my_function(Gs):58    return np.var(Gs)59print('Var of Sales', my_function(Gross))60def my_function(Gm):61    return sum(Gm)62print('Sum of Margin', my_function(Gross))63def my_function(Gm):64    return np.mean(Gm)65print('Mean of Margin', my_function(margin))66def my_function(Gm):67    return np.median(Gm)68print('Median of Margin', my_function(margin))69def my_function(Gm):70    return np.min(Gm)71print('Min of Margin', my_function(margin))72def my_function(Gm):73    return np.max(Gm)74print('Max of Margin', my_function(margin))75def my_function(Gm):76    return np.std(Gm)77print('Std of Margin', my_function(margin))78def my_function(Gm):79    return np.var(Gm)80print('Var of Margin', my_function(margin))81Volume = df2["gross_sales"]82Sales = df2["volume_in_kg"]83x = []84y = []85def Scatter_plot(x, y):86    plt.scatter(x, y)87    plt.xlabel('Volume')88    plt.ylabel('Sales')89    plt.grid()90    plt.show()91if __name__ == '__main__':92    x = list(Volume)93    y = list(Sales)94    Scatter_plot(x, y)...function_ex.py
Source:function_ex.py  
1################# Creating a function ######################################2# def my_function():3#     print("Hello from a fuction")4# ############## Calling a Function #########################################5# def  my_function():6#     print("Hello from a function")7# my_function()8# ############### Arguments #################################################9    10# def my_function(fname):11#     print(fname + "Refsnes")12# my_function("Email")13# my_function("Tobias")14# my_function("Linus")15# ################# Parameters or Arguments? #################################16# def my_function(fname, lname):17#       print(fname + " " + lname)18# my_function("Emil", "Refsnes")19# ################## Arbitrary Arguments, *args ###############################20# def my_function(*kids):21#       print("The youngest child is " + kids[2])22# my_function("Emil", "Tobias", "Linus")23# #################### Keyword Argumets #########################################24# def my_function(child3, child2, child1):25#       print("The youngest child is " + child3)26# my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")27# ################### Arbitrary Keword Arguments,**Kwargs ########################28# def my_function(**kid):29#       print("His last name is " + kid["lname"])30# my_function(fname = "Tobias", lname = "Refsnes")31# ################## Default Parameter Value ######################################32# def my_function(country = "Norway"):33#       print("I am from " + country)34# my_function("Sweden")35# my_function("India")36# my_function()37# my_function("Brazil")38################## passing a list as an Argument #################################39# def my_function(food):40#     for x in food:41#         print(x)42# fruits = ["apple", "banana", "cherry"]43# my_function(fruits)44# ################# Return Values ##################################################45# def my_function(x):46#       return 5 * x47# print(my_function(3))48# print(my_function(5))49# print(my_function(9))50# ############## Recursion ###############################################51# def tri_recursion(k):52#     if(k > 0):53#         result = k + tri_recursion(k - 1)54#         print(result)55#     else:56#         result = 057#     return result58# print("\n\nRecursion Example Results")59# tri_recursion(6)...exceptions.py
Source:exceptions.py  
1# Provides numerous2# examples of different options for exception handling3def my_function(x, y):4    """5      A simple function to divide x by y6    """7    print('my_function in')8    solution = x / y9    print('my_function out')10    return solution11print('Starting')12print(my_function(6, 0))13try:14    print('Before my_function')15    result = my_function(6, 0)16    print(result)17    print('After my_function')18except:19    print('oops')20print('-' * 20)21try:22    print('Before my_function')23    result = my_function(6, 0)24    print(result)25    print('After my_function')26except ZeroDivisionError:27    print('oops')28print('-' * 20)29try:30    print('Before my_function')31    result = my_function(6, 0)32    print(result)33    print('After my_function')34except ZeroDivisionError as exp:35    print(exp)36    print('oops')37print('Done')38print('-' * 20)39try:40    print('Before my_function')41    result = my_function(6, 2)42    print(result)43    print('After my_function')44except ZeroDivisionError as exp:45    print(exp)46    print('oops')47else:48    print('All OK')49print('-' * 20)50try:51    print('At start')52    result = my_function(6, 2)53    print(result)54except ZeroDivisionError as e:55    print(e)56else:57    print('Everything worked OK')58finally:59    print('Always runs')60print('-' * 20)61try:62    result = my_function(6, 0)63    print(result)64except Exception as e:65    print(e)66print('-' * 20)67try:68    print('Before my_function')69    result = my_function(6, 0)70    print(result)71    print('After my_function')72except ZeroDivisionError as exp:73    print(exp)74    print('oops')75except ValueError as exp:76    print(exp)77    print('oh dear')78except:79    print('That is it')80print('-' * 20)81try:82    print('Before my_function')83    result = my_function(6, 0)84    print(result)85    print('After my_function')86finally:87    print('Always printed')88number = 089input_accepted = False90while not input_accepted:91    user_input = input('Please enter a number')92    if user_input.isnumeric():93        number = int(user_input)94        input_accepted = True95    else:96        try:97            number = float(user_input)...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!!
