Brownie error instead of exception when a transaction gets reverted on development - brownie

I am following a brownie tutorial which wrote the following test
def test_only_owner_can_withdraw():
fund_me = deploy()
bad_actor = accounts.add()
with pytest.raises(exceptions.VirtualMachineError):
fund_me.withdraw({"from": bad_actor})
and when I run it on development, it is supposed to pass after an exception from the withdraw transaction being reverted, but instead I get the following error:
> fund_me.withdraw({"from": bad_actor})
E TypeError: int() can't convert non-string with explicit base
and the stack from pdb where the error happens is as follows:
/home/gcodes/brownie_fundme/tests/test_fund_me.py(30)test_only_owner_can_withdraw()
-> fund_me.withdraw({"from": bad_actor})
/home/gcodes/.local/pipx/venvs/eth-brownie/lib/python3.10/site-packages/brownie/network/contract.py(1864)__call__()
-> return self.transact(*args)
/home/gcodes/.local/pipx/venvs/eth-brownie/lib/python3.10/site-packages/brownie/network/contract.py(1737)transact()
-> return tx["from"].transfer(
/home/gcodes/.local/pipx/venvs/eth-brownie/lib/python3.10/site-packages/brownie/network/account.py(682)transfer()
-> receipt._raise_if_reverted(exc)
/home/gcodes/.local/pipx/venvs/eth-brownie/lib/python3.10/site-packages/brownie/network/transaction.py(432)_raise_if_reverted()
-> self._expand_trace()
/home/gcodes/.local/pipx/venvs/eth-brownie/lib/python3.10/site-packages/brownie/network/transaction.py(817)_expand_trace()
-> self._get_trace()
> /home/gcodes/.local/pipx/venvs/eth-brownie/lib/python3.10/site-packages/brownie/network/transaction.py(678)_get_trace()
-> step["pc"] = int(step["pc"], 16)
and step is as follows
{'depth': 1, 'error': '', 'gas': 11978936, 'gasCost': 3, 'memory': [], 'op': 'PUSH1', 'pc': 0, 'stack': [], 'storage': None}
What is the issue here? Thank you
Edit: Upon further investigation, I noticed that the executed code in transactions.py is
fix_gas = isinstance(trace[0]["gas"], str)
if fix_stack or fix_gas:
for step in trace:
if fix_stack:
# for stack values, we need 32 bytes (64 chars) without the 0x prefix
step["stack"] = [HexBytes(s).hex()[2:].zfill(64) for s in step["stack"]]
if fix_gas:
# handle traces where numeric values are returned as hex (Nethermind)
step["gas"] = int(step["gas"], 16)
step["gasCost"] = int.from_bytes(HexBytes(step["gasCost"]), "big", signed=True)
step["pc"] = int(step["pc"], 16)
and before that trace[0] is
{'depth': 1, 'error': '', 'gas': '0xb6c8b8', 'gasCost': 3, 'memory': [], 'op': 'PUSH1', 'pc': 0, 'stack': [], 'storage': None}
so fix_gas is set to True, however pc is not in hex form so int(0, 16) throws an error. However, I don't think anything I do is causing this and I don't know how to fix this issue. What do I do?

Related

Create a dictionary in a loop

I have 2 lists that I want to convert them into a dict with key and values. I managed to do so but there are too many steps so I would like to know if there's a simpler way of achieving this. Basically I would like to create the dict directly in the loop without having the extra steps bellow. I just started working with python and I don't quite understand all the datatypes that it provides.
The jName form can be modified if needed.
jName=["Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder", "LElbow", "LWrist", "RHip",
"RKnee","RAnkle","LHip", "LKnee", "LAnkle", "REye", "LEye", "REar", "LEar"]
def get_joints(subset, candidate):
joints_per_skeleton = [[] for i in range(len(subset))]
# for each detected skeleton
for n in range(len(subset)):
# for each joint
for i in range(18):
cidx = subset[n][i]
if cidx != -1:
y = candidate[cidx.astype(int), 0]
x = candidate[cidx.astype(int), 1]
joints_per_skeleton[n].append((y, x))
else:
joints_per_skeleton[n].append(None)
return joints_per_skeleton
joints = get_joints(subset,candidate)
print joints
Here is the output of the joints list of list
[[None, (48.0, 52.0), (72.0, 50.0), None, None, (24.0, 55.0), (5.0, 105.0), None, (63.0, 159.0), (57.0, 221.0), (55.0, 281.0), (28.0, 154.0), (23.0, 219.0), (23.0, 285.0), None, (25.0, 17.0), (55.0, 18.0), (30.0, 21.0)]]
Here I defined a function to create the dictionary from the 2 lists
def create_dict(keys, values):
return dict(zip(keys, values))
my_dict = create_dict(jointsName, joints[0])
Here is the result:
{'LAnkle': (23.0, 285.0),
'LEar': (30.0, 21.0),
'LElbow': (5.0, 105.0),
'LEye': (25.0, 17.0),
'LHip': (28.0, 154.0),
'LKnee': (23.0, 219.0),
'LShoulder': (24.0, 55.0),
'LWrist': None,
'Neck': (48.0, 52.0),
'Nose': None,
'RAnkle': (55.0, 281.0),
'REar': (55.0, 18.0),
'RElbow': None,
'REye': None,
'RHip': (63.0, 159.0),
'RKnee': (57.0, 221.0),
'RShoulder': (72.0, 50.0),
'RWrist': None}
I think defaultdict could help you. I made my own example to show that you could predefine the keys and then go through a double for loop and have the values of the dict be lists of potentially different sizes. Please let me know if this answers your question:
from collections import defaultdict
import random
joint_names = ['hip','knee','wrist']
num_skeletons = 10
d = defaultdict(list)
for skeleton in range(num_skeletons):
for joint_name in joint_names:
r1 = random.randint(0,10)
r2 = random.randint(0,10)
if r1 > 4:
d[joint_name].append(r1*r2)
print d
Output:
defaultdict(<type 'list'>, {'hip': [0, 5, 30, 36, 56], 'knee': [35, 50, 10], 'wrist': [27, 5, 15, 64, 30]})
As a note I found it very difficult to read through your code since there were some variables that were defined before the snippet you posted.

caffe2 - loss not working and accuracy crashes

I am doing ramp up to caffe2 and I try a toy problem:
# Read the data from the database
def read_input(model, batch_size, db, db_type):
# load the data
data, binary, dist = model.TensorProtosDBInput(
[], ['data', 'binary'], batch_size=batch_size,
db=db, db_type=db_type)
# Get the absolute distance.
data = model.StopGradient(data, data)
binary = model.StopGradient(binary, binary)
return data, binary
def define_network(model, inp, b_classifier):
fc1 = brew.fc(model, inp, 'fc1', dim_in=2, dim_out=10)
fc1 = brew.relu(model, fc1, fc1)
fc2 = brew.fc(model, fc1, 'fc2', dim_in=10, dim_out=20)
fc2 = brew.relu(model, fc2, fc2)
fc3 = brew.fc(model, fc2, 'fc3', dim_in=20, dim_out=10)
fc3 = brew.relu(model, fc3, fc3)
nDimOut = 1+int(b_classifier)
predict = brew.fc(model, fc3, 'predict', dim_in=10, dim_out=nDimOut)
if b_classifier:
softmax = brew.softmax(model, predict, 'softmax')
return softmax
return predict
def add_classifier_loos_and_acc(model, softmax, gt):
crossEnt = model.LabelCrossEntropy([softmax, gt], 'crossEnt')
loss = model.AveragedLoss(crossEnt, "loss")
accuracy = brew.accuracy(model, [softmax, gt], "accuracy")
return loss, accuracy
def add_training_ops(model, loss):
model.AddGradientOperators([loss])
optimizer.build_rms_prop(model, base_learning_rate=0.001)
batchSize = 128
# Create a training network
train_model = model_helper.ModelHelper(name="binary_train")
data, binary = read_input(train_model, batch_size=batchSize, db='Data/' + folder + '/train.minidb', db_type='minidb')
softmax = define_network(train_model, data, True)
loss, _ = add_classifier_loos_and_acc(train_model, softmax, binary)
add_training_ops(train_model, loss)
# Train and check.
workspace.RunNetOnce(train_model.param_init_net)
# creating the network
workspace.CreateNet(train_model.net, overwrite=True)
# Train once
workspace.RunNet(train_model.net)
testRes = workspace.FetchBlob('softmax')
gt = workspace.FetchBlob('binary')
crossEnt = workspace.FetchBlob('crossEnt')
avgCrossEnt = np.mean(crossEnt)
loss = workspace.FetchBlob('loss')
When I run the code and get to the line of workspace.RunNet(train_model.net), my code crashes:
RuntimeError: [enforce fail at accuracy_op.cc:29] label.ndim() == 1. 2 vs 1 Error from operator:
input: "softmax" input: "binary" output: "accuracy" name: "" type: "Accuracy"
We've got an error while stopping in post-mortem: <type 'exceptions.KeyboardInterrupt'>
I tried to understand it about 2 days and I got nothing.
Does anyone has an idea what I am doing wrong ?
Thanks !
I found the problem.
The problem was that the binary was in the shape of (batchSize,1) and it should be at size of (batchSize,).
Adding FlattenToVec() solved the problem

Update a List of objects by comparing with another list

I do have two different lists of same object , one is with sample data , one is with real data. Few fields in the real data are messed up, I need to update the few fields of real data list , by getting those values from sample data .
Both lists are of same object, both have same unique key .
List<pojo> real = [(code:60,active:Y,account:check),(code:61,active:Y,account:check),(code:62,active:Y,account:check)];
List<pojo> sample = [(code:60,active:Y,account:saving),(code:61,active:Y,account:check),(code:62,active:Y,account:saving)]
I have around 60 objects in each list , In the above one I need to update real where code is 60 and 62 - account from check to saving.
I am using java 1.8 & groovy
thanks
Is this what you need?
class Pojo {
def code
def active
def account
String toString() {
account
}
}
List<Pojo> real = [new Pojo(code: 60, active: 'Y', account: 'check'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'check')]
List<Pojo> sample = [new Pojo(code: 60, active: 'Y', account: 'saving'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'saving')]
real.each { r ->
def acc = sample.find{it.code == r.code}?.account
if (acc != null) {
r.account = acc
}
}
println real // prints [saving, check, saving]
The above sample iterates with each over each pojo in real and searches the corresponding object (that with the same code) in the sample list. If the corresponding object is found, the value of account in the object of the real list is overwritten, otherwise it will be left as it is.
Here is the script that updates real data after comparing with sample data as requested by OP.
Note that the input is not valid, so made it valid by changing values inside list as map. i.e.,
changed from (code:60,active:'Y',account:'check')
to [code:60,active:'Y',account:'check']
def realData = [[code:60,active:'Y',account:'check'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'check']]
def sampleData = [[code:60,active:'Y',account:'saving'],[code:61,active:'Y',account:'check'],[code:62,active:'Y',account:'saving']]
realData.collect{rd -> sampleData.find{ it.code == rd.code && (it.account == rd.account ?: (rd.account = it.account))}}
println realData
Output:
[[code:60, active:Y, account:saving], [code:61, active:Y, account:check], [code:62, active:Y, account:saving]]
You can quickly try online Demo

I don't understand why I'm getting an index error, when trying to extract exif data

The code and error with sample data from an image:
image = Image.open(newest)
exif = image._getexif()
gps = {}
datebool = False
gpsbool = False
date = 'None'
time = 'None'
gpstext = 'None'
dmslat = 'None'
dmslon = 'None'
if exif is not None:
for tag, entry in exif.items(): #Import date and time from Exif
datebool = True
if TAGS.get(tag, tag) == 'DateTimeOriginal':
date = entry[0:10]
time = entry[11:19]
for tag, entry in exif.items(): #Check if the GPSInfo field exists
if TAGS.get(tag,tag) == 'GPSInfo':
gpsbool = True
for e in entry:
decoded = GPSTAGS.get(e,e)
print (decoded)
print(type(entry))
gps[decoded] = entry[e]
The results
4984
<type 'tuple'>
Traceback (most recent call last):File"C:\Users\~~~~~\Desktop\project_7-8-2015\8_bands\Program_camera.py", line 109, in <module>
gps[decoded] = entry[e]
IndexError: tuple index out of range
Since e is pulled from entry, how can indexing that particular e from entry generate an indexing error? Am I actually pulling the correct data for the gps?
for e in entry doesn't index the values in entry, it iterates over them. For example:
entry = (3, 5, 7)
for e in entry:
print(e)
will output:
3
5
7
So the line should probably look like:
gps[decoded] = e
though I'm not sure what the GPSTAGS line would become. If you really need the items in entry enumerated, then you should look into (to your great surprise, I'm sure) the enumerate() function.

'str' object has no attribute 'remove'

I want to remove 362968 from below list-
list=[362976,362974,362971,362968,362969]
code-
list.remove(362968)
I am getting error: 'str' object has no attribute 'remove'
Actual code -
def matchmaker():
exportersfree = exporters[:]
engaged = {}
exprefers2 = copy.deepcopy(exprefers)
imprefers2 = copy.deepcopy(imprefers)
while exportersfree:
exporter = exportersfree.pop(0)
exporterslist = exprefers2[exporter]
importer = exporterslist.pop(0)
match = engaged.get(importer)
if not match:
# impo's free
engaged[importer] = exporter #both parties are added to the engaged list
importerslist = imprefers2[importer]
for z in range (importerslist.index(exporter)-1):
importerslist.index(exporter)
exprefers2[importerslist[z]].remove(importer)
del importerslist[0:(importerslist.index(exporter)-1)]
else
engaged[importer] = exporter
if exprefers2[match]:
# Ex has more importers to try
exportersfree.append(match)
return engaged
Without additional code to really debug, exprefers2is clearly a dict of strings; however, if you really want to delete it. You can cast the string to a list, or eval the value to convert it into a list, then use list.remove
import ast
list = [1, 2, 3, 4, 5, 6, 7]
list.remove(5)
print list
#[1, 2, 3, 4, 6, 7]
#Data Structure you most likely have
import_list = [1, 2]
exprefers2 = {1: "abc", 2: "xyz"}
print exprefers2[import_list[1]]
#xyz
#Or need to eval the string of a list
import_list = [1, 2]
exprefers2 = {1: u'[ "A","B","C" , " D"]', 2: u'[ "z","x","y" , " y"]'}
exprefers2[import_list[1]] = ast.literal_eval(exprefers2[import_list[1]])
exprefers2[import_list[1]].remove("y")
print exprefers2[import_list[1]]
#['z', 'x', ' y']
Try it in this way then, name your list "a".
a = [362976,362974,362971,362968,362969]
a.remove(362968)
print a
I think you need to check if the X has been changed.
x = [1, 40, 33, 20]
x.remove(33)
print (x)