How do I fix this syntax error when using a function within another function? - python-3.x

I'm trying to figure out how to call the function within another function, but I am unable to solve this invalid syntax error on line "t_calc = calc_temp(d_curr,volt,tbase)." Can you not call a function within another function?
def calc_temp(current,voltage,tbase):
power_diss = current * voltage
thermal_resistance = THICK/(K*AREA)
temp = tbase + (power_diss * thermal_resistance)
return(temp)
def diode_i_terr(volt,tguess,tbase):
d_curr = I0(np.exp((Q*volt)/(IDE*KB*tguess))
t_calc = calc_temp(d_curr,volt,tbase)
t_err = t_calc - tguess
return(d_curr, t_err)
t_calc = calc_temp(d_curr,volt,tbase)
^
SyntaxError: invalid syntax

Related

Argument to dynamic structure reference must evaluate to a valid field name (helperBluetoothChannelClassification)

Hi im doing a bluetooth project using bluetooth toolbox in matlab, and encountered a problem. So I have been following one of the example from https://www.mathworks.com/help/bluetooth/ug/noncollaborative-bluetooth-le-coexistence-with-wlan-signal-interference.html this error occurred.
ble_wlan_interference
Argument to dynamic structure reference must evaluate to a valid field
name.
Error in helperBluetoothChannelClassification (line 102)
obj.(varargin{idx}) = varargin{idx+1};
Error in ble_wlan_interference (line 58)
classifierObj = helperBluetoothChannelClassification(centralNode,peripheralNode,PERThreshold=50);
At line 102 of helperBluetoothChannelClassification.m is as follows,
methods
% Constructor
function obj = helperBluetoothChannelClassification(varargin)
% Set name-value pairs
for idx = 1:2:nargin
obj.(varargin{idx}) = varargin{idx+1};
end
At line 58 of main code is as follows,
%enable channel classification
enableChannelClassification = true;
if enableChannelClassification
classifierObj = helperBluetoothChannelClassification(centralNode,peripheralNode,PERThreshold=50);
classifyFcn = #(varargin) classifierObj.classifyChannels;
userData = []; % User data needed to be passed to the callback function
callAt = 0; % Absolute simulation time, in seconds
periodicity = 125e-3; % In seconds
scheduleAction(networkSimulator,classifyFcn,userData,callAt,periodicity); % Schedule channel classification
end
I think the centralNode and peripheralNode parameter is not recognizable in helperBluetoothChannelClassification function, but don't know what is a problem.. Thanks :)

TypeError: process_session() missing 1 required positional argument: 'session'

I am facing this error I tried everything, I deployed this function as a google cloud function, but when I am running the triggering URL I am getting an error
Request cannot be handled
Logs are
TypeError: process_session() missing 1 required positional argument: 'session'
at call_user_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py:261)
at invoke_user_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py:268)
at run_http_function (/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py:402)
Function code
def process_session(self, session, utc_offset=0):
s = {}
try:
edfbyte, analysis = process_session(session, utc_offset)
report_json, quality = process_analysis(analysis, session.ref.id)
# save the EDF
path = 'Users/' + session.ref.get("uid") + '/session-' + session.ref.get("sessionId") + '.edf'
path_report = 'Users/' + session.ref.get("uid") + '/session-' + session.ref.get("sessionId") + '.json'
bucket = storage.bucket("......")
bucket.blob(path).upload_from_string(edfbyte, content_type='application/octet-stream')
bucket.blob(path_report).upload_from_string(report_json, content_type='application/json')
# update session
s = session.to_dict()
s[u'macid'] = analysis['header']['macid']
s[u'quality'] = quality
s[u'edfPath'] = path
s[u'reportPath'] = path_report
s[u'timestamp'] = dateutil.parser.parse(analysis['header']['startdate'])
self.db.collection(u'ProcessedSessions').document(session.ref.id).set(s)
try:
self.db.collection(u'UnprocessedSessions').document(session.ref.id).delete()
#session.ref.reference.delete()
except:
pass
return True, 0
except Exception as e:
traceback.print_exc()
s = session.to_dict()
if u'attempt' in s:
attempt = s['attempt']
else:
attempt = 0
self.db.collection(u'UnprocessedSessions').document(session.ref.id).set({u'attempt': attempt + 1}, merge=True)
return False, attempt + 1
You are trying to pass 3 parameters in a HTTP Trigger, Python only accepts 1 parameter wich is a Flask Request Object.
HTTP Functions
Your function is passed a single parameter, (request), which is a
Flask Request object. Return any value from your function that can be
handled by the Flask make_response method. The result will be the HTTP
response.
You can try this to invoke your function:
def functionx (request):
# the GCF always receive only 1 paramater an HTTP request object (flask request)
# you need to get the parameter from the request
# after that you can call your method
process_session(param1,param2,param3)
def process_session(self, session, utc_offset=0):
#dosomenthing
print ("some code here")
Or if you need to use more parameters for your entry point, you can use a Background function.
Background Functions
Background functions are passed arguments holding
data associated with the event that triggered the function's
execution. In the Python runtime, your function is passed the
arguments (data, context)
Is this all part of def process_session? I can't see indentation.
Is it inside a class-object?
Maybe try in line 4:
edfbyte, analysis = self.process_session(session, utc_offset)
The given error signals that you haven't referenced the class-object.

I am facing End of file reached error

I am newbie to python and was trying following code
class Arm(object):
def __init__(self, SNo, ActivityDate, RequesterTeam, RequesterSignumId, RequesterEmailId,Circle,Customer,Technology,WOType,ProblemTitle,ActivityTypeorEqType,SiteID,BSCFACID,EngineerName,EngineerSignum,DetailDescriptionOfActivityToBePerformed,TimelineforActivityCompletion,WOIDbyWFM ):
self.SNo= SNo
self.ActivityDate=ActivityDate
self.RequesterTeam=RequesterTeam
self.RequesterSignumId=RequesterSignumId
self.RequesterEmailId=RequesterEmailId
self.Circle=Circle
self.Customer=Customer
self.Technology=Technology
self.WOType=WOType
self.ProblemTitle=ProblemTitle
self.ActivityTypeorEqType=ActivityTypeorEqType
self.SiteID=SiteID
self.BSCFACID=BSCFACID
self.EngineerName=EngineerName
self.EngineerSignum=EngineerSignum
self.DetailDescriptionOfActivityToBePerformed=DetailDescriptionOfActivityToBePerformed
self.TimelineforActivityCompletion=TimelineforActivityCompletion
self.WOIDbyWFM=WOIDbyWFM
def __str__(self):
return("Arm object:\n"
"SNo = {0}\n"
"ActivityDate = {1}\n"
"RequesterTeam = {2}\n"
"RequesterSignumId = {3}\n"
"RequesterEmailId = {4}\n"
"Circle = {5}\n"
"Customer = {6}\n"
"Technology = {7}\n"
"WOType = {8}\n"
"ProblemTitle = {9}\n"
"ActivityTypeorEqType = {10}\n"
"SiteID = {11}\n"
"BSCFACID = {12}\n"
"EngineerName = {13}\n"
"EngineerSignum = {14}\n"
"DetailDescriptionOfActivityToBePerformed = {15}\n"
"TimelineforActivityCompletion= {16}\n"
"WOIDbyWFM = {17}\n"
.format(self.SNo,
self.ActivityDate,
self.RequesterTeam,
self.RequesterSignumId,
self.RequesterEmailId,
self.Circle,
self.Customer,
self.Technology,
self.WOType,
self.ProblemTitle,
self.ActivityTypeorEqType,
self.SiteID,
self.BSCFACID,
self.EngineerName,
self.EngineerSignum,
self.DetailDescriptionOfActivityToBePerformed,
self.TimelineforActivityCompletion,
self.WOIDbyWFM)
I am getting
File
"C:\Users\OpenSource\eclipse-workspace\PythonWorkSpace\DataHiding\src\Hiding.py", line 26 ^ SyntaxError:unexpected EOF while parsing error
while running the code. please suggest me where i am making errors.
You should have "WOIDbyWFM = {17}\n"..format(self.SNo, .......
You are missing a closing right parentheses at the end of your return statement.
Please use the PyCharm editor and it will show you all errors like eclipse does and then you can correctly indent your code to make it bug free.

Python-MySQL : removing single quotes around variable values in query while running db.execute(str, vars)

I am running this code
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from %(tablename)s where userid = %(userid)s"
result = db.run_query_vals(sql, payload)
res = result.fetchall()
return res
but get an error
SQLError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''statuser' where userid = '14'' at line 1
The arguments being passed are :
sql = "select * from %(tablename)s where userid = %(userid)s"
payload = {'tablename' : 'statuser', 'userid' : 14}
As far as I understand, the query being passed to MySQL is along the lines of
select * from 'statuser' where userid = '14'
which is where I get the error; the tablename isnt supposed to be enclosed in quotes. How do I have the name included without the quotes/make them backquotes?
(I don't want to hard-code the table name - this is a variable and is initialised according to different parameters during class creation). Any help here?
You can use the .format() from string in python:
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from {tablename} where userid = {userid}"
sql = sql.format(**payload)
# result = db.run_query_vals(sql, payload) # Method to run query
res = result.fetchall()
return res
I encountered the same problem in pymysql and have figured out a solution:
rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.
don't know whether it will help in your case, just sharing a possible way
similiar question: How to remove extra quotes in pymysql
Here's my code:
from pymysql.connections import Connection, converters
class MyConnect(Connection):
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str):
return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()

Why can't I directly assign to object properties using multiple return values from a method?

Based on this question I've coded the following which throws a compilation time error:
Here is the code:
43. Currency currency = new Currency()
44. (currency.rate_one, currency.time_one) = getDateAndRate()
My method with two return values:
def getDateAndRate(){
Date date = new Date()
double rate = getRate();
return [rate, date]
}
Error thrown
expecting '}', found ',' # line 44, column 26.
(currency.rate_one, currency.time_one) = getDateAndRate()
^
Try this instead
def (rate, time) = getDateAndRate()
currency.rate_one = rate
currency.time_one = time
There is a trick I learned only recently myself and that is to combine multiple assignment and with:
with (currency) {
(rate_one, time_one) = getDateAndTime()
}

Resources