I'm getting error in this line:
line 21: dindrv = InputDriver(dut, 'din_value', dut.CLK)
self is already defined in:
class InputDriver(BusDriver):
signals = ['rdy', 'en', 'data']
def __init__(self,dut,name,clk):
BusDriver.__init__(self,dut,name,clk) --->line 35
self.bus.en.value = 0
self.clk = clk
The error is:
Traceback (most recent call last):
File "/home/trisha77/interfaces-trisha2915/tests/ifc_test.py", line
21, in ifc_test
dindrv = InputDriver(dut, 'din_value', dut.CLK)
File "/home/trisha77/interfaces-trisha2915/tests/ifc_test.py", line
35, in __init__
BusDriver.__init__(self,dut,name,clk)
File
"/home/trisha77/.local/lib/python3.10/site-packages/cocotb_busdrivers/__init__.py",
line 236, in__init__
self.entity, name, self._signals,
optional_signals=self._optional_signals,
AttributeError: 'InputDriver' object has no attribute '_signals'
I tried giving dindrv = InputDriver(self, dut, 'din_value', dut.CLK)
But in this case, it is showing the error as:
NameError: name 'self' is not defined
The whole code:
import cocotb
from cocotb.triggers import Timer, RisingEdge, ReadOnly,NextTimeStep
from cocotb_bus.drivers import BusDriver
def sb_fn(actual_value):
global expected_value
assert actual_value == expected_value.pop(0), "Scoreboard Matching Failed"
#cocotb.test() async def ifc_test(dut):
global exp_dout
din_value = (4, 6, 7, 5)
exp_dout = (22)
dut.RST_N.value = 1
await Timer(1,'ns')
dut.RST_N.value = 0
await RisingEdge(dut.CLK)
await RisingEdge(dut.CLK)
dut.RST_N.value = 1
self.dindrv = InputDriver(self, dut, 'din_value', dut.CLK)
OutputDriver(dut, 'dout_value', dut.CLK, sb_fn)
for i in range(4):
dindrv.append(din[i])
while len(exp_dout)>0:
await Timer(2,'ns')
class InputDriver(BusDriver):
signals = ['din_rdy', 'din_en', 'din_value']
def __init__(self,dut,name,clk):
BusDriver.__init__(self,dut,name,clk)
self.bus.en.value = 0
self.clk = clk async def driver_send(self,value,sync=True):
if self.bus.rdy.value != 1:
await RisingEdge(self.bus.rdy)
self.bus.en.value = 1
self.bus.data.value = value
await ReadOnly()
await RisingEdge(self.clk)
self.bus.en.value = 1
await NextTimeStep()
class OutputDriver(BusDriver):
signals = ['rdy', 'en', 'data']
def __init__(self,dut,name,clk):
BusDriver.__init__(self,dut,dut.v,clk, sb_callback)
self.bus.en.value = 0
self.clk = clk
self.callback = sb_callback
self.append(0)
async def driver_send(self,value,sync=True):
while True:
if self.bus.rdy.value != 1:
await RisingEdge(self.bus.rdy)
self.bus.en.value = 1
await ReadOnly()
self.callback(self.bus.data.value)
await RisingEdge(self.clk)
self.bus.en.value = 0
await NextTimeStep()
Related
I am trying to build a command in python for Maya following a course on youtube and it's showing this error "# Error: RuntimeError: file line 2: AttributeError: file C:/Users/saeed/OneDrive/Documents/maya/2020/Plugins/vertexParticle.py line 23: 'module' object has no attribute 'MStatus' # "
I checked Maya API documents and we should have "MStatus" class but I have no idea why it's not accepted, I tried to use "MStatusCode" and it's showing same error.
from maya import OpenMaya
from maya import OpenMayaMPx
from maya import OpenMayaFX
import sys
commandName = "vertexParticle"
kHelpFlag = "-h"
kHelpLongFlag = "-help"
kSparseFlag = "-s"
kSparseLongFlag = "-sparse"
helpMessage = "This command will attach a particle for each vertex"
class pluginCommand(OpenMayaMPx.MPxCommand):
sparse = None
def __init__(self):
OpenMayaMPx.MPxCommand.__init__(self)
def argumentParser(self, argList):
syntax = self.syntax()
parserArguments = OpenMaya.MArgDatabase(syntax, argList)
if parserArguments.isFlagSet(kSparseFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kSparseLongFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseLongFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpLongFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
def isUndoable(self):
return True
def undoIt(self):
print "undo"
mFnDagNode = OpenMaya.MFnDagNode(self.mObjParticle)
mDagMod = OpenMaya.MDagModifier()
mDagMod.deleteNode(mFnDagNode.parent(0))
mDagMod.doIt()
return OpenMaya.MStatus.kSuccess
def redoIt(self):
mSel = OpenMaya.MSelectionList()
mDagPath = OpenMaya.MDagPath()
mFnMesh = OpenMaya.MFnMesh()
OpenMaya.MGlobal.getActiveSelectionList(mSel)
if mSel.length() >= 1:
try:
mSel.getDagPath(0, mDagPath)
mFnMesh.setObject(mDagPath)
except:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
else:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
mPointArray = OpenMaya.MPointArray()
mFnMesh.getPoints(mPointArray, OpenMaya.MSpace.kWorld)
mFnParticle = OpenMayaFX.MFnParticleSystem()
self.mObjParticle = mFnParticle.create()
mFnParticle = OpenMayaFX.MFnParticleSystem(self.mObjParticle)
counter == 0
for i in xrange(mPointArray.length()):
if i%self.sparse == 0:
mFnParticle.emit(mPointArray[i])
counter += 1
print "total points :" + str(counter)
mFnParticle.saveInitialState()
return OpenMaya.MStatus.kSuccess
def doIt(self, argList):
self.argumentParser(argList)
if self.sparse != None:
self.redoIt()
return OpenMaya.MStatus.kSuccess
def cmdCreator():
return OpenMayaMPx.asMPxPtr(pluginCommand())
def syntaxCreator():
syntax = OpenMaya.MSyntax()
syntax.addFlag(kHelpFlag, kHelpLongFlag)
syntax.addFlag(kSparseFlag, kSparseLongFlag, OpenMaya.MSyntax.kDouble)
return syntax
def initializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(mObject)
try:
mPlugin.registerCommand(commandName, cmdCreator, syntaxCreator)
except:
sys.stderr.write("Failed to register" + commandName)
def uninitializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(pluginCommand())
try:
mPlugin.deregisterCommand(commandName)
except:
sys.stderr.write("Failed to deregister" + commandName)
Because MStatus.MStatusCode is an enum, you can return its integer value in Python. The only issue is that because in C++ this is an enum, there is no guarantee that the values won't change/shift between releases. This enum has remained consistent since 2019, so there isn't much risk of this happening for MStatus.MStatusCode.
https://help.autodesk.com/view/MAYAUL/2019/ENU/?guid=__cpp_ref_class_m_status_html
https://help.autodesk.com/view/MAYAUL/2023/ENU/?guid=Maya_SDK_cpp_ref_class_m_status_html
Somewhere in the top of your file simply add the constants you intend to use:
MStatus_kSuccess = 0
MStatus_kFailure = 1
MStatus_kUnknownParameter = 5
Then return the constant instead in your functions:
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return MStatus_kSuccess
Unhandled exception in internal background task 'called_once_a_day'.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/discord/ext/tasks/init.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "fx-news.py", line 40, in called_once_a_day
datetime = simpledate.SimpleDate(item['date']).convert(country='GB', tz='Europe/London')
TypeError: an integer is required (got type str)
That's the error I'm receiving.
Here are my lines of code
#tasks.loop(hours=24)
async def called_once_a_day():
message_channel = bot.get_channel(channel)
print(f"Got channel {message_channel}")
my_json = json.loads(get_news())
embed = discord.Embed(title="Forex News today!", description="", color=0x8877dd)
separator = "═════════════════════════════════════"
for item in my_json:
# Date
# London
datetime = simpledate.SimpleDate(item['date']).convert(country='GB', tz='Europe/London')
weekday = calendar.day_name[datetime.weekday]
tz = str(datetime.time)[0:5] + ' (Europe/London)'
date_ldn = f"{weekday} - {datetime.day} {calendar.month_abbr[datetime.month]}, {datetime.year} {tz}"
# NewYork
datetime = simpledate.SimpleDate(item['date']).convert(country='US', tz='America/New_York')
weekday = calendar.day_name[datetime.weekday]
tz = str(datetime.time)[0:5] + ' (America/New_York)'
date_nyc = f"{weekday} - {datetime.day} {calendar.month_abbr[datetime.month]}, {datetime.year} {tz}"
# Australia
datetime = simpledate.SimpleDate(item['date']).convert(country='AU', tz='Australia/Sydney')
weekday = calendar.day_name[datetime.weekday]
tz = str(datetime.time)[0:5] + ' (Australia/Sydney)'
date_aus = f"{weekday} - {datetime.day} {calendar.month_abbr[datetime.month]}, {datetime.year} {tz}"
I got an issue with this driver:
LM75_CHIP_ADDR = 0x48
LM75_I2C_SPEED = 100000
LM75_REGS = {
'TEMP' : 0x00,
'CONF' : 0x01,
'THYST' : 0x02,
'TOS' : 0x03,
'PRODID' : 0x07 # TI LM75A chips only?
}
LM75_REPORT_TIME = .8
# Temperature can be sampled at any time but the read aborts
# the current conversion. Conversion time is 300ms so make
# sure not to read too often.
LM75_MIN_REPORT_TIME = .5
class MLM75:
def __init__(self, config):
self.printer = config.get_printer()
self.name = config.get_name().split()[-1]
self.reactor = self.printer.get_reactor()
self.i2c_sen = bus.MCU_I2C_from_config(config, LM75_CHIP_ADDR,
LM75_I2C_SPEED)
self.mcu = self.i2c_sen.get_mcu()
self.report_time = config.getfloat('lm75_report_time',LM75_REPORT_TIME, minval=LM75_MIN_REPORT_TIME)
self.temp = self.min_temp = self.max_temp = 0.0
self.sample_timer = self.reactor.register_timer(self._sample_mlm75)
self.printer.add_object("mlm75 " + self.name, self)
self.printer.register_event_handler("klippy:connect",
self.handle_connect)
############# MUX HANDLER ############
self.gcode = self.printer.lookup_object('gcode')
self.mux = self.printer.load_object(config, "PCA9545A %s" % (self.name,))
self.mux.init_route = config.getint( "mux_ch", 0, minval=0, maxval=3 )
self.mux.address = config.getint( "mux_i2c_address", 112 )
self.mux.change_i2c_addr( self.mux.address )
# _mux_iic_addr = self.mux.get_info()[0]
# _mux_out_chan = self.mux.get_info()[1]
# self.gcode.respond_info('sensor: '+self.name+ '\n' +
# ' addr:'+str(_mux_iic_addr)+
# ' chan:'+str(_mux_out_chan))
self.mux_channel = 0
############# MUX HANDLER ############
def handle_connect(self):
self._init_mlm75()
self.reactor.update_timer(self.sample_timer, self.reactor.NOW)
def setup_minmax(self, min_temp, max_temp):
self.min_temp = min_temp
self.max_temp = max_temp
def setup_callback(self, cb):
self._callback = cb
def get_report_time_delta(self):
return self.report_time
def degrees_from_sample(self, x):
# The temp sample is encoded in the top 9 bits of a 16-bit
# value. Resolution is 0.5 degrees C.
return x[0] + (x[1] >> 7) * 0.5
def _init_mlm75(self):
# Check and report the chip ID but ignore errors since many
# chips don't have it
try:
prodid = self.read_register('PRODID', 1)[0]
logging.info("mlm75: Chip ID %#x" % prodid)
except:
pass
def _sample_mlm75(self, eventtime):
# self.gcode.respond_info( str(self.i) )
self.mux_channel += 1
self.mux_channel %= 4
self.mux.route( self.mux_channel ) # <<<<
# self.gcode.respond_info('mx c:'+str(self.mux.get_info()[1])) # <<<<
try:
sample = self.read_register('TEMP', 2)
self.temp = self.degrees_from_sample(sample)
except Exception:
logging.exception("mlm75: Error reading data")
self.temp = 0.0
return self.reactor.NEVER
if self.temp < self.min_temp or self.temp > self.max_temp:
self.printer.invoke_shutdown(
"MLM75 temperature %0.1f outside range of %0.1f:%.01f"
% (self.temp, self.min_temp, self.max_temp))
measured_time = self.reactor.monotonic()
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
return measured_time + self.report_time
def read_register(self, reg_name, read_len):
# read a single register
regs = [LM75_REGS[reg_name]]
params = self.i2c_sen.i2c_read(regs, read_len)
return bytearray(params['response'])
def write_register(self, reg_name, data):
if type(data) is not list:
data = [data]
reg = LM75_REGS[reg_name]
data.insert(0, reg)
self.i2c_sen.i2c_write(data)
def get_status(self, eventtime):
return {
'temperature': round(self.temp, 2),
}
def load_config(config):
# Register sensor
pheaters = config.get_printer().load_object(config, "heaters")
pheaters.add_sensor_factory("MLM75", MLM75)
This code is supposed to read, write and change the address of a MUX. For some reason I can't read part of the sensors.
That's the log:
mcu 'mcu': Starting serial connect
Loaded MCU 'mcu' 100 commands (v0.10.0-388-gd9daeb08-dirty-20220429_121230-raspberrypi / gcc: (GCC) 5.4.0 binutils: (GNU Binutils) 2.26.20160125)
MCU 'mcu' config: BUS_PINS_spi=PB3,PB2,PB1 PWM_MAX=255 CLOCK_FREQ=16000000 BUS_PINS_twi=PD0,PD1 MCU=atmega32u4 ADC_MAX=1023 STATS_SUMSQ_BASE=256
mcu 'mcu': got {u'count': 229, '#receive_time': 3173.116210849, u'sum': 315145, u'sumsq': 3550500, '#name': u'stats', '#sent_time': 3173.115847275}
Configured MCU 'mcu' (165 moves)
lm75: Chip ID 0x1e
Starting heater checks for plateHeater1
lm75: Chip ID 0x22
Starting heater checks for plateHeater2
Starting heater checks for blockHeater1
Starting heater checks for blockHeater2
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
I am trying to figure this thing out for 2 weeks now and my hair is starting to fall. Can someone tell me what I do wrong?
Thanks for the help
I do not know much about asynchrony, I tried to turn for loops into async for, but now only
the first element of the generator is working, the rest are ignored. What is wrong with
this code?
async def get_requests(self, data, request_type):
for x in data:
r = [
'subscribe_on_model',
{
'collection': None,
'id': None,
'recursive': ''
}
]
r[1]['collection'] = request_type
r[1]['id'] = x
yield r
async def get_results(self):
async with BaseWebsocket(self.uri) as ws:
await ws.receive()
sport_keys = list(self.sports.keys())
sport_values = list(self.sports.values())
bundle_requests = self.get_requests(sport_values, 'LineSport')
async for bundle_request in bundle_requests:
results = []
sport_name = sport_keys[sport_values.index(bundle_request[1]['id'])]
b_request = [bundle_request]
await ws.send(b_request)
b_response = await ws.receive()
bundle_ids = b_response[0][1].get('lineCountryIds')
if bundle_ids:
championship_requests = self.get_requests(bundle_ids, 'LineCountry')
async for championship_request in championship_requests:
c_request = [championship_request]
await ws.send(c_request)
c_response = await ws.receive()
championship_ids = c_response[0][1].get('lineChampionshipIds')
if championship_ids:
event_requests = self.get_requests(championship_ids, 'LineChampionship')
I am trying my darnest to pull a variable from a text file to do some math in an trading bot algorithim.
This is my code. I have shortened it to get to the issue:
from botlog import BotLog
from botindicators import BotIndicators
from bottrade import BotTrade
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
self.trades = [] #20 trades at 0.021 = .042
self.currentPrice = "" #after a day, add the BTC to 0.042 and adjust simultaneous trades
self.currentClose = "" #53 coins for 2500 simul trades per coin pair
self.numSimulTrades = 100 #looks like dash ends at 2500 trades eth ends at about 1000 trades total for all four would be about 208 coins
self.indicators = BotIndicators()
mid=0
with open('test.txt', 'r') as myfile:
mid=myfile.read().replace('\n', '')
self.output.log(mid)
mid=int(mid)
def tick(self,candlestick):
self.currentPrice = float(candlestick.priceAverage)
self.prices.append(self.currentPrice)
#self.currentClose = float(candlestick['close'])
#self.closes.append(self.currentClose)
self.output.log("Price: "+str(candlestick.priceAverage)+"\tMoving Average: "+str(self.indicators.movingAverage(self.prices,5)))
self.evaluatePositions()
self.updateOpenTrades()
self.showPositions()
def evaluatePositions(self):
openTrades = []
for trade in self.trades:
if (trade.status == "OPEN"):
openTrades.append(trade)
if (len(openTrades) < self.numSimulTrades):
if ((self.currentPrice) < self.indicators.movingAverage(self.prices,15)):
self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001))
for trade in openTrades:
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
trade.close(self.currentPrice)
def updateOpenTrades(self):
for trade in self.trades:
if (trade.status == "OPEN"):
trade.tick(self.currentPrice)
def showPositions(self):
for trade in self.trades:
trade.showTrade()
With "self.mid" I get the error: 'Bot1' object has no attribute 'mid'
a if I remove the "self" I get: NameError: global name 'mid' is not defined
What am I doing wrong? I'm losing my mind!
Traceback was requested: This is the No Attribute:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
self.currentPrice= float(self.currentPrice+self.mid)
AttributeError: 'BotStrategy' object has no attribute 'mid'
And this is "mid" not defined:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
NameError: global name 'mid' is not defined
bottrade.py code:
from botlog import BotLog
import botstrategy
def main(argv):
currentMovingAverage = 0;
tradePlaced = False
typeOfTrade = False
dataDate = ""
orderNumber = ""
dataPoints = []
localMax = []
currentResistance = 0.018
mid = int(mid)
class BotTrade(object):
def __init__(self,currentPrice,stopLoss=0):
self.output = BotLog()
prices = []
self.status = "OPEN"
self.entryPrice = currentPrice
self.exitPrice = ""
self.output.log("Trade opened")
if (stopLoss):
self.stopLoss = currentPrice - stopLoss
def close(self,currentPrice):
self.mid = int(mid)
if currentPrice > (self.entryPrice + self.mid): #DASH likes about 0.000937, XRP about 0.000001, ETH likes 0.000855 XMR likes 0.000396
#use ETH to start with, with less than 4 trades. you get about 1.7 BTC in a week - 4 trades # 0.021=0.084 BTC. Daily is 0.24
self.status = "CLOSED"
self.exitPrice = currentPrice
self.output.log("Trade closed")
def tick(self, currentPrice):
if (self.stopLoss):
if (currentPrice < self.stopLoss):
self.close(currentPrice)
def showTrade(self):
tradeStatus = "Entry Price: "+str(self.entryPrice)+" Status: "+str(self.status)+" Exit Price: "+str(self.exitPrice)
if (self.status == "CLOSED"):
tradeStatus = tradeStatus + " Profit:! "
if (self.exitPrice > self.entryPrice):
tradeStatus = tradeStatus + " \033[92m"
else:
tradeStatus = tradeStatus + " \033[91m"
tradeStatus = tradeStatus+str(abs((self.exitPrice) - (self.entryPrice)))+" \033[0m"
self.output.log(tradeStatus)
Traceback from bottrade.py
user#user1:~/Desktop/bot/part3$ python backtest.py
Price: 1131.71486314 Moving Average: None
Price: 1103.73203402 Moving Average: 1117.72344858
Trade opened
Entry Price: 1103.73203402 Status: OPEN Exit Price:
Price: 1108.36463027 Moving Average: 1114.60384248
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 29, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
trade.close(self.currentPrice)
File "/home/user/Desktop/bot/part3/bottrade.py", line 30, in close
self.mid = int(mid)
NameError: global name 'mid' is not defined
Full display now. Any help would be appreciated.
The run-time system is correct. In the mid case, there is no variable mid defined in evaluatePositions. Similarly, there is no object attribute mid for instances of BotStrategy. Look at the difference in your initialization:
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
...
mid=int(mid)
mid is a local variable of init, not an attribute. Perhaps you need
self.mid = int(mid)
and the use self.mid when you reference that value.
Does that work for you?