Fixing "HEREError: Error occured on __get" - python

Im getting started using the herepy EVCharginStationsApi and have been running into some issues that I can't troubleshoot on my own. I have obtained an API Key and have tried this so far:
evAPI = EVChargingStationsApi(API_Key)
response = evAPI.get_stations_circular_search(latitude = 37.87166, longitude = -122.2727, radius = 10000)
At this point, I run into the aforementioned HEREError: Error occured on__get (I have included a screenshot of the full error message below)
Please let me know how I can get around this (seemingly trivial) error.
As per the request, here is the error message as text as well:
HEREError Traceback (most recent call last)
<ipython-input-72-e0860df7cdc5> in <module>
----> 1 response = evAPI.get_stations_circular_search(latitude = 37.87166, longitude =-122.2727, radius = 10000)
2 response
/Applications/anaconda3/lib/python3.7/site-packages/herepy/ev_charging_stations_api.py in get_stations_circular_search(self, latitude, longitude, radius, connectortypes)
100 }
101 response = self.__get(
--> 102 self._base_url + "stations.json", data, EVChargingStationsResponse
103 )
104 return response
/Applications/anaconda3/lib/python3.7/site-packages/herepy/ev_charging_stations_api.py in __get(self, base_url, data, response_cls)
41 return response_cls.new_from_jsondict(json_data)
42 else:
---> 43 raise error_from_ev_charging_service_error(json_data)
44
45 def __connector_types_str(self, connector_types: List[EVStationConnectorTypes]):
HEREError: Error occured on __get

Related

How can I select an SAP GuiGridView row via Python scripting

I am trying to use Python for SAP Scripting, specifically to select a row in a GuiGridView object. It works just fine in VB Script, but in Python I get an exception: -2147352562, 'Invalid number of parameters.', which doesn't make sense to me since I'm using the same number of parameters as for VB Script.
I am trying to get away from VB Script since it doesn't have proper error handling.
Here is the documentation (https://help.sap.com/doc/9215986e54174174854b0af6bb14305a/760.01/en-US/sap_gui_scripting_api_761.pdf ), but even with that I haven't been able to resolve this:
Page 128
SelectedRows (Read-write)
Public Property SelectedRows As String
The string is a comma separated list of row index numbers or index ranges, such as “1,2,4-8,10”.Setting this property to an invalid string or a string containing invalid row indices will raise an exception.
The following VB Script code selects the GuiGridRow as expected, but when I attempt to convert that to Python it won't work.
If Not IsObject(application) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
Set connection = application.Children(0)
End If
If Not IsObject(session) Then
Set session = connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject application, "on"
End If
Set GridView = session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell")
GridView.SelectedRows = 1
Here is my Python 3.9 attempt using Jupyter Notebook and the results:
+*In[1]:*+
import win32com.client
+*In[2]:*+
SapGuiAuto = win32com.client.GetObject('SAPGUI')
application = SapGuiAuto.GetScriptingEngine
connection = application.Children(0)
session = connection.Children(0)
type(session)
+*Out[2]:*+
----win32com.client.CDispatch----
+*In[3]:*+
grid_view = session.findById('wnd[0]/usr/cntlGRID1/shellcont/shell')
print(grid_view)
+*Out[3]:*+
<COMObject <unknown>>
+*In[4]:*+
# to show that grid_view is a valid GuiGridView object
grid_view.RowCount
+*Out[4]:*+
----2----
+*In[5]:*+
# reading the SelectedRows works
grid_view.SelectedRows
+*Out[5]:*+
----'1'----
+*In[6]:*+
# setting SelectedRows as number fails
# note: I had manually unselected the row in SAP before running the rest of the code
grid_view.SelectedRows = 1
+*Out[6]:*+
---------------------------------------------------------------------------
com_error Traceback (most recent call last)
~\AppData\Local\Temp\20/ipykernel_21344/1273355717.py in <module>
----> 1 grid_view.SelectedRows = 1
E:\Anaconda\Lib\site-packages\win32com\client\dynamic.py in __setattr__(self, attr, value)
541 entry = self._olerepr_.propMap[attr]
542 invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
--> 543 self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
544 return
545 # Check the specific "put" map.
com_error: (-2147352562, 'Invalid number of parameters.', None, None)
----
+*In[7]:*+
# setting SelectedRows as string fails
grid_view.SelectedRows = '1'
+*Out[7]:*+
---------------------------------------------------------------------------
com_error Traceback (most recent call last)
~\AppData\Local\Temp\20/ipykernel_21344/1222153478.py in <module>
----> 1 grid_view.SelectedRows = '1'
E:\Anaconda\Lib\site-packages\win32com\client\dynamic.py in __setattr__(self, attr, value)
541 entry = self._olerepr_.propMap[attr]
542 invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
--> 543 self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
544 return
545 # Check the specific "put" map.
com_error: (-2147352562, 'Invalid number of parameters.', None, None)
----
+*In[8]:*+
# setting SelectedRows as string with multiple rows fails
grid_view.SelectedRows = '0,1'
----
+*Out[8]:*+
---------------------------------------------------------------------------
com_error Traceback (most recent call last)
~\AppData\Local\Temp\20/ipykernel_21344/3316141255.py in <module>
----> 1 grid_view.SelectedRows = '0,1'
E:\Anaconda\Lib\site-packages\win32com\client\dynamic.py in __setattr__(self, attr, value)
541 entry = self._olerepr_.propMap[attr]
542 invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
--> 543 self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
544 return
545 # Check the specific "put" map.
com_error: (-2147352562, 'Invalid number of parameters.', None, None)
----
+*In[9]:*+
# setting SelectedRows as string with multiple rows in a method-type notation fails
grid_view.SelectedRows('0,1')
----
+*Out[9]:*+
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\20/ipykernel_21344/2186236324.py in <module>
----> 1 grid_view.SelectedRows('0,1')
TypeError: 'str' object is not callable
----
Ok, after digging around a lot more, patching to the latest version of win32com worked:
https://github.com/mhammond/pywin32/tree/main/com/win32com
Once I did that all of the following worked to select rows:
grid_view.SelectedRows = 1
grid_view.SelectedRows = '1'
grid_view.SelectedRows = '0,1'
grid_view.SelectedRows = '0-1'
The following did not work (type error), which makes sense since it would imply tuple packing/unpacking:
grid_view.SelectedRows = 0,1
This results in unexpected rows being selected since it is performing subtraction rather than indicating a range of rows:
grid_view.SelectedRows = 0-1

missing variable to complete cell execution

I hope someone can help me. I've been stuck with this error for a while. I have two .py files that I am importing in a jupyter notebook. When running the last cell (see code below) I get a Traceback error I can'f fix.
I think there is some error in my ch_data_prep.py file related to variable df_ch not correctly passed between files. Is this possible? Any suggestion on how to solve this problem?
Thanks!
ch_data_prep.py
def seg_data(self):
seg_startdate = input('Enter start date (yyyy-mm-dd): ')
seg_finishdate = input('Enter end date (yyyy-mm-dd): ')
df_ch_seg = df_ch[(df_ch['event_datetime'] > seg_startdate)
& (df_ch['event_datetime'] < seg_finishdate)
]
return df_ch_seg
df_ch_seg = seg_data(df_ch)
ch_db.py
def get_data():
# Some omitted code here to connect to database and get data...
df_ch = pd.DataFrame(result)
return df_ch
df_ch = get_data()
Jupyter Notebook data_analysis.ipynb
In[1]: import ch_db
df_ch = ch_db.get_data()
In[2]: import ch_data_prep
When I run cell 2, I get this error
--------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-fbe2d4fceba6> in <module>
----> 1 import ch_data_prep
~/clickstream/ch_data_prep.py in <module>
34 return df_ch_seg
35
---> 36 df_ch_seg = seg_data()
TypeError: seg_data() missing 1 required positional argument: 'df_ch'

Unable to export in parallel from Exasol using pyexasol

I'm attempting to fetch data from Exasol using PyExasol, in parallel. I'm following the example here - https://github.com/badoo/pyexasol/blob/master/examples/14_parallel_export.py
My code looks like this :
import multiprocessing
import pyexasol
import pyexasol.callback as cb
class ExportProc(multiprocessing.Process):
def __init__(self, node):
self.node = node
self.read_pipe, self.write_pipe = multiprocessing.Pipe(False)
super().__init__()
def start(self):
super().start()
self.write_pipe.close()
def get_proxy(self):
return self.read_pipe.recv()
def run(self):
self.read_pipe.close()
http = pyexasol.http_transport(self.node['host'], self.node['port'], pyexasol.HTTP_EXPORT)
self.write_pipe.send(http.get_proxy())
self.write_pipe.close()
pd1 = http.export_to_callback(cb.export_to_pandas, None)
print(f"{self.node['idx']}:{len(pd)}")
EXASOL_HOST = "<IP-ADDRESS>:8563"
EXASOL_USERID = "username"
EXASOL_PASSWORD = "password"
c = pyexasol.connect(dsn=EXASOL_HOST, user=EXASOL_USERID, password=EXASOL_PASSWORD, compression=True)
nodes = c.get_nodes(10)
pool = list()
proxy_list = list()
for n in nodes:
proc = ExportProc(n)
proc.start()
proxy_list.append(proc.get_proxy())
pool.append(proc)
c.export_parallel(proxy_list, "SELECT * FROM SOME_SCHEMA.SOME_TABLE", export_params={'with_column_names': True})
stmt = c.last_statement()
r = stmt.fetchall()
At the last statement, I'm getting the following error and unable to fetch any results.
---------------------------------------------------------------------------
ExaRuntimeError Traceback (most recent call last)
<command-911615> in <module>
----> 1 r = stmt.fetchall()
/local_disk0/pythonVirtualEnvDirs/virtualEnv-01515a25-967f-4b98-aa10-6ac03c978ce2/lib/python3.7/site-packages/pyexasol/statement.py in fetchall(self)
85
86 def fetchall(self):
---> 87 return [row for row in self]
88
89 def fetchcol(self):
/local_disk0/pythonVirtualEnvDirs/virtualEnv-01515a25-967f-4b98-aa10-6ac03c978ce2/lib/python3.7/site-packages/pyexasol/statement.py in <listcomp>(.0)
85
86 def fetchall(self):
---> 87 return [row for row in self]
88
89 def fetchcol(self):
/local_disk0/pythonVirtualEnvDirs/virtualEnv-01515a25-967f-4b98-aa10-6ac03c978ce2/lib/python3.7/site-packages/pyexasol/statement.py in __next__(self)
53 if self.pos_total >= self.num_rows_total:
54 if self.result_type != 'resultSet':
---> 55 raise ExaRuntimeError(self.connection, 'Attempt to fetch from statement without result set')
56
57 raise StopIteration
ExaRuntimeError:
(
message => Attempt to fetch from statement without result set
dsn => <IP-ADDRESS>:8563
user => username
schema =>
)
It seems that the type of the returned statement is not 'resultSet' but 'rowCount'. Any help on what I'm doing wrong or why the type of statement is ''rowCount' ?
PyEXASOL creator is here. Please not in case of parallel HTTP transport you have to process data chunks inside child processes. Your data set is available in pd1 DataFrame.
You should not be calling .fetchall() in the main process in case of parallel processing.
I suggest to check the complete examples, especially example 14 (parallel export).
Hope it helps!

Why do i get an Attribute Error when using Neurokit?

Why do i get an attribute error when i run this code in jupyter ? I am trying to figure out how to use Neurokit.
Ive tried to look through the modules one by one, but i seem to find the error.
import neurokit as nk
import pandas as pd
import numpy as np
import sklearn
df = pd.read_csv("https://raw.githubusercontent.com/neuropsychology/NeuroKit.py/master/examples/Bio/bio_100Hz.csv")
# Process the signals
bio = nk.bio_process(ecg=df["ECG"], rsp=df["RSP"], eda=df["EDA"], add=df["Photosensor"], sampling_rate=1000 )
Output Message:
AttributeError Traceback (most recent call last)
<ipython-input-2-ad0abf8de45e> in <module>
11
12 # Process the signals
---> 13 bio = nk.bio_process(ecg=df["ECG"], rsp=df["RSP"], eda=df["EDA"], add=df["Photosensor"], sampling_rate=1000 )
14 # Plot the processed dataframe, normalizing all variables for viewing purpose
15 nk.z_score(bio["df"]).plot()
~\Anaconda3\lib\site-packages\neurokit\bio\bio_meta.py in bio_process(ecg, rsp, eda, emg, add, sampling_rate, age, sex, position, ecg_filter_type, ecg_filter_band, ecg_filter_frequency, ecg_segmenter, ecg_quality_model, ecg_hrv_features, eda_alpha, eda_gamma, scr_method, scr_treshold, emg_names, emg_envelope_freqs, emg_envelope_lfreq, emg_activation_treshold, emg_activation_n_above, emg_activation_n_below)
123 # ECG & RSP
124 if ecg is not None:
--> 125 ecg = ecg_process(ecg=ecg, rsp=rsp, sampling_rate=sampling_rate, filter_type=ecg_filter_type, filter_band=ecg_filter_band, filter_frequency=ecg_filter_frequency, segmenter=ecg_segmenter, quality_model=ecg_quality_model, hrv_features=ecg_hrv_features, age=age, sex=sex, position=position)
126 processed_bio["ECG"] = ecg["ECG"]
127 if rsp is not None:
~\Anaconda3\lib\site-packages\neurokit\bio\bio_ecg.py in ecg_process(ecg, rsp, sampling_rate, filter_type, filter_band, filter_frequency, segmenter, quality_model, hrv_features, age, sex, position)
117 # ===============
118 if quality_model is not None:
--> 119 quality = ecg_signal_quality(cardiac_cycles=processed_ecg["ECG"]["Cardiac_Cycles"], sampling_rate=sampling_rate, rpeaks=processed_ecg["ECG"]["R_Peaks"], quality_model=quality_model)
120 processed_ecg["ECG"].update(quality)
121 processed_ecg["df"] = pd.concat([processed_ecg["df"], quality["ECG_Signal_Quality"]], axis=1)
~\Anaconda3\lib\site-packages\neurokit\bio\bio_ecg.py in ecg_signal_quality(cardiac_cycles, sampling_rate, rpeaks, quality_model)
355
356 if quality_model == "default":
--> 357 model = sklearn.externals.joblib.load(Path.materials() + 'heartbeat_classification.model')
358 else:
359 model = sklearn.externals.joblib.load(quality_model)
AttributeError: module 'sklearn' has no attribute 'externals'
You could downgrade you scikit-learn version if you don't need the most recent fixes using
pip install scikit-learn==0.20.1
There is an issue to fix this problem in future version:
https://github.com/neuropsychology/NeuroKit.py/issues/101
I'm executing the exact same code as you and run into the same problem.
I followed the link indicated by Louis MAYAUD and there they suggest to just add
from sklearn.externals import joblib
That solves everything and you don't need to downgrade scikit-learn version
Happy code! :)

How to capture an error from the library python litex.Regon?

I want Handling Exceptions from litex Regon (polish library with information about company). I don't know how? When i try with
When i try with this code it's ok... so i don't know why?
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
But my code is doesn't work
## EXAMPLE
api = REGONAPI('https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc')
USER_KEY = 'my_key'
api.login(USER_KEY)
entities = api.search(nip='9222976976')
c = etree.tostring(entities[0], pretty_print=True)
c
## MY CODE
REGONAPI('https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc')
USER_KEY = 'my_key'
api.login(USER_KEY)
from litex.regon import REGONAPI
lista = []
for i in np.arange(280, 300):
try:
entities = api.search(nip=dane_do_przeszukwania['NIP'][i])
c = etree.tostring(entities[0], pretty_print=True)
lista.append(c)
except REGONAPIError:
None
I have a error
EGONAPIError Traceback (most recent call last)
<ipython-input-7-f2653b5824bc> in <module>
4 try:
----> 5 entities = api.search(nip=dane_do_przeszukwania['NIP'][i])
6 c = etree.tostring(entities[0], pretty_print=True)
~\Anaconda3\lib\site-packages\litex\regon\__init__.py in search(self, nip, regon, krs, nips, regons, krss, detailed)
210 if not result:
--> 211 raise REGONAPIError('Search failed.')
212
REGONAPIError: Search failed.
During handling of the above exception, another exception occurred:
NameError Traceback (most recent call last)
<ipython-input-7-f2653b5824bc> in <module>
6 c = etree.tostring(entities[0], pretty_print=True)
7 lista.append(c)
----> 8 except REGONAPIError:
9 None
10
NameError: name 'REGONAPIError' is not defined
if I do not find it number hand error and next row in iterate.
REGONAPIError is not defined because you probably didn't import it.
Try adding
from litex.regon import REGONAPIError
in your file, this should work.

Categories