Best Python code snippet using localstack_python
AD_adjoint.py
Source:AD_adjoint.py
1import math23TF_UNDEF = -14TF_CONST = 05TF_ASG = 16TF_ADD = 27TF_SUB = 38TF_MUL = 49TF_EXP = 510TF_LOG = 611TF_POW = 712TF_SIN = 813TF_COS = 914#---------------------------------------------------------------------------------------#15class tape_entry:16 """Contains all data for one operation. Self representation is value."""17 def __init__(self):18 self.oc = TF_UNDEF # operation code19 self.arg1 = TF_UNDEF # First operation argument20 self.arg2 = TF_UNDEF # Second operation argument (optional)21 self.value = 0 22 self.adjoint = 02324 def __repr__(self):25 return self.__str__()2627 def __str__(self):28 return str(self.value)2930#---------------------------------------------------------------------------------------#31# Initialize tape, list of tape entries32# Either a static tape size is given (delete all "tape.append(tape_entry())" from this file)33# or currently all the tape is dynamically getting bigger without user interaction.34global vac35vac = 036tape_size = 137tape = [tape_entry() for i in range(tape_size)]38#---------------------------------------------------------------------------------------#39class TFrev:40 """Tracer Float reverse (TFrev) is the used datatype for adjoint AD mode."""41 def __init__(self, value, is_input=False, from_operation=False):42 """Creation and initialization at once."""43 if is_input == True:44 #this ist the constructor (c++)45 global vac46 tape[vac].oc = TF_CONST47 tape[vac].value = value48 vac += 149 tape.append(tape_entry())50 # this is the operator= overloading (c++)51 self.adress = vac52 self.value = value53 tape[vac].oc = TF_ASG54 tape[vac].value = value55 tape[vac].arg1 = vac - 156 vac += 157 tape.append(tape_entry())58 #return TFrev(value, False, True)5960 if from_operation == True:61 vac += 1 # this is the increment of the operation 62 tape.append(tape_entry())63 self.value = value64 self.adress = vac65 tape[vac].oc = TF_ASG66 tape[vac].value = value67 tape[vac].arg1 = vac - 168 #return self6970 def __repr__(self):71 return self.__str__()7273 def __str__(self):74 return str(tape[self.adress].value)75#---------------------------------------------------------------------------------------#76 def __add__(self, other): 77 if isinstance(other, TFrev):78 global vac79 tape[vac].oc = TF_ADD80 tape[vac].arg1 = self.adress81 tape[vac].arg2 = other.adress82 tape[vac].value = self.value + other.value8384 # every operation is treated as an assignement85 tmp = TFrev(tape[vac].value, from_operation=True)86 vac += 1 # this is the increment of the asignemnet87 tape.append(tape_entry())88 return tmp89 else:90 tape[vac].oc = TF_CONST91 tape[vac].value = other92 vac += 193 tape.append(tape_entry())94 tape[vac].oc = TF_ADD95 tape[vac].arg1 = self.adress96 tape[vac].arg2 = vac - 197 tape[vac].value = self.value + other9899 # every operation is treated as an assignement100 tmp = TFrev(tape[vac].value, from_operation=True)101 vac += 1 # this is the increment of the asignemnet102 tape.append(tape_entry())103 return tmp104 105 def __radd__(self, other):106 return self.__add__(other)107108 def __sub__(self, other):109 return self.__add__(other * -1)110111 def __rsub__(self, other):112 return (self * -1).__add__(other)113114 def __mul__(self, other):115 if isinstance(other, TFrev):116 global vac117 tape[vac].oc = TF_MUL 118 tape[vac].arg1 = self.adress 119 tape[vac].arg2 = other.adress 120 tape[vac].value = self.value * other.value121122 # every operation is treated as an assignement123 tmp = TFrev(tape[vac].value, from_operation=True)124 vac += 1 # this is the increment of the asignemnet125 tape.append(tape_entry())126 return tmp127 else:128 tape[vac].oc = TF_CONST129 tape[vac].value = other130 vac += 1131 tape.append(tape_entry())132 tape[vac].oc = TF_MUL 133 tape[vac].arg1 = self.adress 134 tape[vac].arg2 = vac - 1 135 tape[vac].value = self.value * other136137 # every operation is treated as an assignement138 tmp = TFrev(tape[vac].value, from_operation=True)139 vac += 1 # this is the increment of the asignemnet140 tape.append(tape_entry())141 return tmp142143 def __rmul__(self, other):144 return self.__mul__(other)145146 def __truediv__(self, other):147 if isinstance(other, TFrev):148 assert tape[other.adress].value != 0, "Division by zero."149 else:150 assert other != 0, "Division by zero."151 return self.__mul__(other ** (-1))152153 def __rtruediv__(self, other):154 if isinstance(self, TFrev):155 assert tape[self.adress].value != 0, "Division by zero."156 else:157 assert self != 0, "Division by zero."158 return (self ** (-1)).__mul__(other)159160 def __neg__(self):161 return self.__mul__(-1)162163 def __pow__(self, power):164 if isinstance(power, TFrev):165 global vac166 tape[vac].oc = TF_POW 167 tape[vac].arg1 = self.adress 168 tape[vac].arg2 = power.adress 169 tape[vac].value = self.value ** power.value170171 # every operation is treated as an assignement172 tmp = TFrev(tape[vac].value, from_operation=True)173 vac += 1 # this is the increment of the asignemnet174 tape.append(tape_entry())175 return tmp176 elif not isinstance(power, TFrev):177 tape[vac].oc = TF_CONST178 tape[vac].value = power179 vac += 1180 tape.append(tape_entry())181 tape[vac].oc = TF_POW182 tape[vac].arg1 = self.adress 183 tape[vac].arg2 = vac - 1 184 tape[vac].value = self.value ** power185186 # every operation is treated as an assignement187 tmp = TFrev(tape[vac].value, from_operation=True)188 vac += 1 # this is the increment of the asignemnet189 tape.append(tape_entry())190 return tmp191 # other possibility is that 2(notTF) ** TF, that operation is curr not covered192 193 def exp(self):194 if isinstance(self, TFrev):195 global vac196 tape[vac].oc = TF_EXP 197 tape[vac].arg1 = self.adress 198 tape[vac].value = math.exp(self.value) 199200 # every operation is treated as an assignement201 tmp = TFrev(tape[vac].value, from_operation=True)202 vac += 1 # this is the increment of the asignemnet203 tape.append(tape_entry())204 return tmp205 elif not isinstance(self, TFrev):206 return math.exp(self)207208 def log(self):209 if isinstance(self, TFrev):210 assert self.value > 0, "log(x <= 0) is undefined." 211 global vac212 tape[vac].oc = TF_LOG 213 tape[vac].arg1 = self.adress 214 tape[vac].value = math.log(self.value) 215216 # every operation is treated as an assignement217 tmp = TFrev(tape[vac].value, from_operation=True)218 vac += 1 # this is the increment of the asignemnet219 tape.append(tape_entry())220 return tmp221 elif not isinstance(self, TFrev):222 assert self.value > 0, "log(x <= 0) is undefined." 223 return math.log(self)224225 def sin(self):226 if isinstance(self, TFrev):227 global vac228 tape[vac].oc = TF_SIN229 tape[vac].arg1 = self.adress 230 tape[vac].value = math.sin(self.value) 231232 # every operation is treated as an assignement233 tmp = TFrev(tape[vac].value, from_operation=True)234 vac += 1 # this is the increment of the asignemnet235 tape.append(tape_entry())236 return tmp237 elif not isinstance(self, TFrev):238 return math.sin(self)239240 def cos(self):241 #return TFrev.sin(self+math.pi/2)242 if isinstance(self, TFrev):243 global vac244 tape[vac].oc = TF_COS245 tape[vac].arg1 = self.adress 246 tape[vac].value = math.cos(self.value) 247248 # every operation is treated as an assignement249 tmp = TFrev(tape[vac].value, from_operation=True)250 vac += 1 # this is the increment of the asignemnet251 tape.append(tape_entry())252 return tmp253 elif not isinstance(self, TFrev):254 return math.cos(self)255256#---------------------------------------------------------------------------------------#257def interpret_tape():258 """Loop brackward through tape and evaluate derivatives."""259 global vac260 for i in range(vac,-1,-1): # reversed array261 if tape[i].oc == TF_ASG:262 tape[tape[i].arg1].adjoint += tape[i].adjoint263264 elif tape[i].oc == TF_ADD:265 tape[tape[i].arg1].adjoint += tape[i].adjoint266 tape[tape[i].arg2].adjoint += tape[i].adjoint267268 elif tape[i].oc == TF_SUB: # everything is currently piped to ADD269 tape[tape[i].arg1].adjoint += tape[i].adjoint270 tape[tape[i].arg2].adjoint -= tape[i].adjoint271272 elif tape[i].oc == TF_MUL:273 tape[tape[i].arg1].adjoint += tape[tape[i].arg2].value * tape[i].adjoint274 tape[tape[i].arg2].adjoint += tape[tape[i].arg1].value * tape[i].adjoint275 276 elif tape[i].oc == TF_POW: # fails if tape[tape[i].arg1].value is negative277 tape[tape[i].arg1].adjoint += tape[tape[i].arg2].value * tape[tape[i].arg1].value ** (tape[tape[i].arg2].value-1) * tape[i].adjoint278 tape[tape[i].arg2].adjoint += tape[tape[i].arg1].value ** tape[tape[i].arg2].value * math.log(tape[tape[i].arg1].value) * tape[i].adjoint279280 elif tape[i].oc == TF_EXP:281 tape[tape[i].arg1].adjoint += math.exp(tape[tape[i].arg1].value) * tape[i].adjoint282283 elif tape[i].oc == TF_LOG:284 tape[tape[i].arg1].adjoint += 1/tape[tape[i].arg1].value * tape[i].adjoint285286 elif tape[i].oc == TF_SIN:287 tape[tape[i].arg1].adjoint += math.cos(tape[tape[i].arg1].value) * tape[i].adjoint288289 elif tape[i].oc == TF_COS:290 tape[tape[i].arg1].adjoint += -math.sin(tape[tape[i].arg1].value) * tape[i].adjoint291292def reset_tape(): 293 """Resets complete tape to default values."""294 global vac295 vac = 0296 global tape_size297 global tape298 tape = [tape_entry() for i in range(tape_size)]299300def get_gradient(input, output=None):301 """Reads the derivatives of an input vector (of TFrev) from interpreted tape.302 Sets seed at output if given, otherwise last tape entry is taken.303 Output needs to be a scalar TFrev."""304 if output==None:305 tape[vac-1].adjoint = 1306 else:307 assert isinstance(output, TFrev), "Only scalar objective Func is allowed for reverse AD-sweep."308 tape[output.adress].adjoint = 1309 interpret_tape()310 gradient = [tape[input_val.adress].adjoint for input_val in input]311 return gradient312313def print_tape():314 """Prints tape in the current state."""315 print("tape:")316 global vac317 for i in range(vac):318 print(i, ": [ ", tape[i].oc, ", ", tape[i].arg1, ", ", tape[i].arg2, ", ", tape[i].value, ", ", tape[i].adjoint, " ]" )319#---------------------------------------------------------------------------------------#320if __name__ == '__main__':
...
tests.py
Source:tests.py
1from random import randrange2from django.test import TestCase3from django_advanced_wallet.models import Wallet4from django_advanced_wallet.errors import NegativeAmount, InsufficentBalance5from decimal import Decimal6from .models import Account, RelatedObject7class TestWalletRelation(TestCase):8 DEPOSIT_VALUES = list(sorted([randrange(100 * i, 200 * i) / 100 for i in range(1, 1000)]))9 def test_object_creation(self):10 obj = Account.objects.create()11 self.assertIsInstance(obj.wallet, Wallet)12 def test_deposit(self):13 obj = Account.objects.create()14 for value in self.DEPOSIT_VALUES:15 value = Wallet.normalize_amount(Decimal(value))16 self.assertEqual(obj.wallet.deposit(value).value, value)17 def test_deposit_with_related_object(self):18 obj = Account.objects.create()19 related_obj = RelatedObject.objects.create(name="test")20 for value in self.DEPOSIT_VALUES:21 value = Wallet.normalize_amount(Decimal(value))22 operation = obj.wallet.deposit(value, related_object=related_obj)23 self.assertEqual(operation.value, value)24 self.assertEqual(operation.content_object, related_obj)25 def test_negative_operation(self):26 obj = Account.objects.create()27 related_obj = RelatedObject.objects.create(name="test")28 with self.assertRaises(NegativeAmount):29 obj.wallet.withdraw(Decimal(-100))30 def test_insuffiecient_operation(self):31 obj = Account.objects.create()32 with self.assertRaises(InsufficentBalance):33 obj.wallet.withdraw(Decimal(100))34 def test_withdraw(self):35 obj = Account.objects.create()36 fund_200 = Wallet.normalize_amount(Decimal(200))37 fund_100 = Wallet.normalize_amount(Decimal(100))38 fund_0 = Wallet.normalize_amount(Decimal(0))39 obj.wallet.deposit(fund_200)40 self.assertEqual(obj.wallet.withdraw(fund_100).value, fund_100)41 self.assertEqual(obj.wallet.withdraw(fund_100).previous_value, fund_100)42 self.assertEqual(obj.wallet.balance, fund_0)43 with self.assertRaises(InsufficentBalance):44 obj.wallet.withdraw(fund_100)45 def test_withdraw_with_related_object(self):46 obj = Account.objects.create()47 related_obj = RelatedObject.objects.create(name="test")48 for value in self.DEPOSIT_VALUES:49 decimal_value = Wallet.normalize_amount(Decimal(value))50 obj.wallet.deposit(decimal_value)51 operation = obj.wallet.withdraw(decimal_value, related_object=related_obj)52 obj.refresh_from_db()53 self.assertEqual(operation.value, decimal_value)54 self.assertEqual(operation.content_object, related_obj)55 self.assertEqual(obj.wallet.previous_balance, operation.previous_value)56 def test_transfer(self):57 from_account = Account.objects.create()58 to_account = Account.objects.create()59 for value in self.DEPOSIT_VALUES:60 decimal_value = Wallet.normalize_amount(Decimal(value))61 zero_value = Wallet.normalize_amount(Decimal(0))62 from_account.wallet.deposit(decimal_value)63 from_account.refresh_from_db()64 self.assertEqual(from_account.wallet.balance, decimal_value)65 from_operation, to_operation = from_account.wallet.transfer(66 to_wallet=to_account.wallet,67 amount=decimal_value68 )69 self.assertEqual(from_operation.value, decimal_value)70 self.assertEqual(to_operation.value, decimal_value)71 self.assertEqual(from_operation.wallet.balance, zero_value)72 self.assertEqual(to_operation.wallet.balance, decimal_value)73 self.assertEqual(from_operation.operation_type, from_operation.OperationType.TRANSFER_ORIGIN)74 self.assertEqual(to_operation.operation_type, to_operation.OperationType.TRANSFER_DESTINATION)75 to_operation.wallet.withdraw(decimal_value)76 def test_operation_cancel(self):77 account = Account.objects.create()78 fund_0 = Wallet.normalize_amount(Decimal(0))79 fund_1000 = Wallet.normalize_amount(Decimal(1000))80 operation = account.wallet.deposit(81 fund_100082 )83 self.assertEqual(account.wallet.balance, fund_1000)84 cancel_operation = operation.cancel_operation()85 account.refresh_from_db()86 self.assertEqual(cancel_operation.operation_type, cancel_operation.OperationType.WITHDRAW)87 self.assertEqual(account.wallet.balance, fund_0)88 for value in self.DEPOSIT_VALUES:89 decimal_value = Wallet.normalize_amount(Decimal(value))90 operation = account.wallet.deposit(decimal_value)91 self.assertEqual(account.wallet.balance, decimal_value)92 operation.cancel_operation()93 account.refresh_from_db()94 self.assertEqual(account.wallet.balance, fund_0)95 def test_force_withdraw(self):96 account = Account.objects.create()97 fund_0 = Wallet.normalize_amount(Decimal(0))98 fund_1000 = Wallet.normalize_amount(Decimal(1000))99 account.wallet.deposit(100 fund_1000101 )102 self.assertEqual(account.wallet.balance, fund_1000)103 account.wallet.withdraw(fund_1000)104 self.assertEqual(account.wallet.balance, fund_0)105 with self.assertRaises(InsufficentBalance):106 account.wallet.withdraw(fund_1000)107 account.wallet.withdraw(fund_1000, force_withdraw=True)...
Converter_Expression.py
Source:Converter_Expression.py
1class Converter_Expression:2 def __init__(self, expression, from_operation, to_operation):3 """4 Konstruktor5 :param expression:6 :param from_operation:7 :param to_operation:8 """9 self.expression = expression10 self.from_operation = from_operation11 self.to_operation = to_operation12 def translate_expression(self):13 """14 Funkcja odpowiedzialna za przeksztaÅcanie wyrażenia.15 :return:16 """17 try:18 if self.from_operation != self.to_operation:19 if self.from_operation == "16":20 if self.to_operation == "10":21 self.expression = str(int(self.expression, int(self.from_operation)))22 elif self.to_operation == "8":23 self.expression = int(self.expression, int(self.from_operation))24 self.expression = oct(self.expression)25 elif self.to_operation == "2":26 self.expression = int(self.expression, int(self.from_operation))27 self.expression = bin(self.expression)28 elif self.from_operation == "10":29 self.expression = int(self.expression)30 if self.to_operation == "16":31 self.expression = hex(self.expression)32 elif self.to_operation == "8":33 self.expression = oct(self.expression)34 elif self.to_operation == "2":35 self.expression = bin(self.expression)36 self.expression = str(self.expression)37 elif self.from_operation == "8":38 if self.to_operation == "10":39 self.expression = str(int(self.expression, int(self.from_operation)))40 elif self.to_operation == "16":41 self.expression = int(self.expression, int(self.from_operation))42 self.expression = hex(self.expression)43 elif self.to_operation == "2":44 self.expression = int(self.expression, int(self.from_operation))45 self.expression = bin(self.expression)46 elif self.from_operation == "2":47 if self.to_operation == "10":48 self.expression = str(int(self.expression, int(self.from_operation)))49 elif self.to_operation == "16":50 self.expression = int(self.expression, int(self.from_operation))51 self.expression = hex(self.expression)52 elif self.to_operation == "8":53 self.expression = int(self.expression, int(self.from_operation))54 self.expression = oct(self.expression)55 if self.to_operation == "16":56 self.expression = self.expression.replace("0x", "", 1)57 elif self.to_operation == "8":58 self.expression = self.expression.replace("0o", "", 1)59 elif self.to_operation == "2":60 self.expression = self.expression.replace("0b", "", 1)61 self.expression = self.expression.upper()62 except:63 "ERROR"64 def update(self, expression, from_operation, to_operation):65 """66 Funkcja odpowiedzialna za aktualizacjÄ wyrażenia.67 :param expression:68 :param from_operation:69 :param to_operation:70 :return:71 """72 self.expression = expression73 self.from_operation = from_operation74 self.to_operation = to_operation75 def get_expression(self):76 """77 Funkcja zwracajÄ
ca przeksztaÅcone wyrażenie.78 :return:79 """...
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!!