Creating an array of strings - arrays

I'm having a few problems with the following:
Dim design(6) As String
design(0) = "DES1"
design(1) = "DES1_slot"
design(2) = "DES2"
design(3) = "DES2_slot"
design(4) = "DES3"
design(5) = "DES3_slot"
I get the error "Expected end of statement"
Similarly:
Dim design(0 To 5) As String
design(0) = "DES1"
design(1) = "DES1_slot"
design(2) = "DES2"
design(3) = "DES2_slot"
design(4) = "DES3"
design(5) = "DES3_slot"
says "Expecting ')' "
I don't often use VBA, but from the quick googling I did at least one of these should work?

Thats perfectly valid VBA however you will get those exact errors in VBScript which is what I presume your using.
As VBScript is typeless change the first line to just:
Dim design(5)

Related

How to create a for loop when the variable is in a sentence?

I want to create a for loop when the variable is in a string format.
my code is:
for i in range(1,32):
DEP_RATE = pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = i:"{i}" group by YYYYMM',{i:str(i)},rconn)
the error is:
'dict' object has no attribute 'cursor'
I used this code:
for i in range(1,32):
DEP_RATE = pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = "i" group by YYYYMM',rconn, params={i:str(i)})
It hasn't error but doesn't work. the problem is:
("Truncated incorrect DOUBLE value: 'i'")
This appears to be a PANDAS question, yes? I believe it's an argument mismatch with the read_sql_query API. The function signature is:
pandas.read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None)
Which roughly says that the first two positional arguments are required, and everything else is defaulted or optional.
To make it more obvious, consider putting your core SQL string on a separate line:
sql = 'SELECT daynum, ... AND daynum = :i'
for i in range(1, 32):
DEP_RATE = pd.read_sql_query(sql, {i: str(i)}, rconn)
With this formulation, it's more obvious that your arguments do not match the API: your second argument is off. Perhaps you want (note the additional keyword argument params):
DEP_RATE = pd.read_sql_query(sql, rconn, params={i: str(i)})
I corrected the code. The correct answer is:
DEP_RATE = list(np.zeros((1,1)))*31
for i in range(1,32):
DEP_RATE[i-1] =np.array(pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = '+str(i)+' group by YYYYMM;',rconn, params={i:str(i)}))

Splitting String into Array Errors

Trying to write a script that will be run in WinPE, that essentially gets the IP address of the localhost and chooses an action based on the IP range.
In Windows, the script runs flawlessly. However, in WinPE, I'm getting the following error:
script.vbs(1,1) Microsoft VBScript runtime error: Subscript out of range
Google-fu is telling me that has something to do with my array being outside of the range. Here I thought I had a decent understanding, but apparently not.
Code that works as is on Windows:
Option Explicit
Dim sIP, sHostname,sPingBat
Dim aIP
Dim iOct1, iOct2, iOct3, iOct4, iReturn
Dim oWMIService, oCmd, oAdapter
Dim cAdapters
iReturn = 999
sHostname = "."
Set oWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sHostname & "\root\cimv2")
Set cAdapters = oWMIService.ExecQuery("Select IPAddress from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
Set oCmd = CreateObject("Wscript.Shell")
For Each oAdapter in cAdapters
If Not IsNull(oAdapter.IPAddress) Then
sIP = Trim(oAdapter.IPAddress(0))
Else
iReturn = 404
WScript.Quit iReturn
End If
Next
sIP = CStr(sIP)
aIP = Split(sIP, ".")
iOct1 = CInt(aIP(0))
iOct2 = CInt(aIP(1))
iOct3 = CInt(aIP(2))
iOct4 = CInt(aIP(3))
Now, if I change the declaration of the aIP array to either of the following:
aIP()
aIP(4)
and run
aIP = Split(sIP, ".")
I get
script.vbs(26, 1) Microsoft VBScript runtime error: Type mismatch
Changing the array assignment / split line to
aIP() = Split(sIP,".")
results in
script.vbs(26, 1) Microsoft VBScript runtime error: Subscript out of range
So I'm obviously doing something wrong.
It's also entirely possible that my original error message is completely unrelated to my array range, and WinPE just doesn't like my script (in which case, if anybody has any pointers, it'd be appreciated)
At the moment, I'm mounting my wim to get the install packages to make sure the WMI and Scripting packages are installed from the ADK.
There is nothing wrong with the code except the assumption being made about what Win32_NetworkAdapterConfiguration returns.
From MSDN - Win32_NetworkAdapterConfiguration class
Array of all of the IP addresses associated with the current network adapter. This property can contain either IPv6 addresses or IPv4 addresses. For more information, see IPv6 and IPv4 Support in WMI.
Because sIP could contain an IPv6 address the Split() will not work as expected. IPv6 addresses don't contain . as a separator so Split() will return a Array containing the original string as the first index only. Hence attempting to read anything other then aIP(0) will cause an
Microsoft VBScript runtime error:
Subscript out of range
error.
To avoid this use InStr() to check for the existence of . in the sIP variable first, you will also need to iterate through the oAdapter.IPAddress array to check each address to get the correct one, you can't assume IPAddress(0) will always be the right one.
Try this
Dim ips, ip
For Each oAdapter in cAdapters
ips = oAdapter.IPAddress
If IsArray(ips) Then
For Each ip In ips
If InStr(1, ip, ".") > 0 Then
sIP = Trim(ip)
Exit For
End If
Next
If Len(sIP) > 0 Then Exit For
Else
iReturn = 404
WScript.Quit iReturn
End If
Next
Untested on iPad sorry
I guess sIP variable contains some string which can not be splitted wity delimiter "."(ex: "somestringwithNoDOT")
So in the 1st case
aIP = Split(sIP,".") ' Split("somestringwithNoDOT",".")
statement returned only 1 string, which can not be coverted to Integer. So i returned Type mismatch error in below line
iOct1 = CInt(aIP(0)) ' returns Type mismatch error
In the 2nd case
aIP() = Split(sIP,".") ' Split("somestringwithNoDOT",".")
above statement will return 1 element, but aIP is array with NO elements. So this statement rturned "Subscript out of range" error
Resolution for this issue is to check whether correct value is passing to sIP

Convert.ChangeType() Returns incorrect value

I've got a class that parses a CNC file, but I'm having difficulties with trailing "words" on each line of the file.
My code parses all leading "words" until it reaches the final word. It's most noticeable when parsing "Z" values or other Double type values. I've debugged it enough to notice that it successfully parses the numerical value just as it does with "X" and "Y" values, but it doesn't seem to successfully convert it to double. Is there an issue with a character I'm missing or something?
Here's my code:
If IO.File.Exists("Some GCode File.eia") Then
Dim sr As New IO.StreamReader("Some GCode File.eia")
Dim i As Integer = 0
'Read text file
Do While Not sr.EndOfStream
'Get the words in the line
Dim words() As String = sr.ReadLine.Split(" ")
'iterate through each word
For i = 0 To words.Length - 1 Step 1
'iterate through each "registered" keyword. Handled earlier in program
For Each cmd As String In _registeredCmds.Keys
'if current word resembles keyword then process
If words(i) Like cmd & "*" Then
_commands.Add(i, _registeredCmds(cmd))
'Double check availability of a Type to convert to
If Not IsNothing(_commands(i).DataType) Then
'Verify enum ScopeType exists
If Not IsNothing(_commands(i).Scope) Then
'If ScopeType is modal then just set it to True. I'll fix later
If _commands(i).Scope = ScopeType.Modal Then
_commands(i).DataValue = True
Else
'Catch errors in conversion
Try
'Get the value of the gcode command by removing the "registered" keyword from the string
Dim strTemp As String = words(i).Remove(0, words(i).IndexOf(_commands(i).Key) + _commands(i).Key.Length)
'Save the parsed value into an Object type in another class
_commands(i).DataValue = Convert.ChangeType(strTemp, _commands(i).DataType)
Catch ex As Exception
'Log(vbTab & "Error:" & ex.Message)
End Try
End If
Else
'Log(vbTab & "Command scope is null")
End If
Else
'Log(vbTab & "Command datatype is null")
End If
Continue For
End If
Next
Next
i += 1
Loop
Else
Throw New ApplicationException("FilePath provided does not exist! FilePath Provided:'Some GCode File.eia'")
End If
Here's an example of the GCode:
N2930 X-.2187 Y-1.2378 Z-.0135
N2940 X-.2195 Y-1.2434 Z-.0121
N2950 X-.2187 Y-1.249 Z-.0108
N2960 X-.2164 Y-1.2542 Z-.0096
N2970 X-.2125 Y-1.2585 Z-.0086
N2980 X-.207 Y-1.2613 Z-.0079
N2990 X-.2 Y-1.2624 Z-.0076
N3000 X0.
N3010 X12.
N3020 X24.
N3030 X24.2
N3040 X24.2072 Y-1.2635 Z-.0075
N3050 X24.2127 Y-1.2665 Z-.0071
N3060 X24.2167 Y-1.2709 Z-.0064
N3070 X24.2191 Y-1.2763 Z-.0057
N3080 X24.2199 Y-1.2821 Z-.0048
N3090 X24.2191 Y-1.2879 Z-.004
N3100 X24.2167 Y-1.2933 Z-.0032
N3110 X24.2127 Y-1.2977 Z-.0026
N3120 X24.2072 Y-1.3007 Z-.0021
N3130 X24.2 Y-1.3018 Z-.002
N3140 X24.
N3150 X12.
N3160 X0.
N3170 X-.2
N3180 X-.2074 Y-1.3029 Z-.0019
N3190 X-.2131 Y-1.306 Z-.0018
N3200 X-.2172 Y-1.3106 Z-.0016
N3210 X-.2196 Y-1.3161 Z-.0013
N3220 X-.2204 Y-1.3222 Z-.001
N3230 X-.2196 Y-1.3282 Z-.0007
N3240 X-.2172 Y-1.3338 Z-.0004
N3250 X-.2131 Y-1.3384 Z-.0002
N3260 X-.2074 Y-1.3415 Z-.0001
N3270 X-.2 Y-1.3426 Z0.
N3280 X0.
N3290 X12.
N3300 X24.
N3310 X24.2
N3320 G0 Z.1
N3330 Z1.0
N3340 G91 G28 Z0.0
N3350 G90
With regard to the sample CNC code above, you'll notice that X and Y commands with a trailing Z command parse correctly.
EDIT
Per comment, here is a breakdown of _commands()
_commands = SortedList(Of Integer, Command)
Command is a class with the following properties:
Scope as Enum ScopeType
Name as String
Key as String
DataType as Type
DataValue as Object
EDIT: Solution!
Figured out what was wrong. The arrays that make up the construction of the classes were essentially being passed a reference to the "registered" array of objects from the Command class. Therefore every time I parsed the value out of the "word" each line, I was overwriting the DataValue in the Command object.
The solution was to declare a new 'Command' object with every parse and append it to the proper array.
Here's my short hand:
...
For I = 0 To words.Length - 1 Step 1
'iterate through each "registered" keyword. Handled earlier in program
For Each cmd as String in _registeredCmds.Keys
'if current word resembles keyword then process
If words(I) Like cmd & "*" Then
'NEW!!! Declare unassigned Command object
Dim com As Command
' ****** New elongated logic double checking existence of values.....
If _registeredCmds.Keys.Scope = ScopeType.Modal Then
'assign Command object to previously declared variable com
com = New Command()'There's technically passing arguments now to ensure items are transferred
Else
'Parse and pass DataValue from this word
com = New Command()'There's technically passing arguments now to ensure items are transferred
End If
'New sub to add Command object to local array
Add(com)
Continue For
End If
Next
Next
...

ValueError: could not convert string to float: E-3 [duplicate]

This question already has answers here:
Issue querying from Access database: "could not convert string to float: E+6"
(3 answers)
Closed 7 years ago.
I am trying to access some of the columns in a Microsoft Access database table which contains numbers of type double but I am getting the error mentioned in the title.The code used for querying the database is as below, the error is occurring in the line where cur.execute(....) command is executed. Basically I am trying filter out data captured in a particular time interval. If I exclude the columns CM3_Up, CG3_Up, CM3_Down, CG3_Down which contains double data type in the cur.execute(....) command I wont get the error. Same logic was used to access double data type from other tables and it worked fine, I am not sure what is going wrong.
Code:
start =datetime.datetime(2015,03,28,00,00)
a=start
b=start+datetime.timedelta(0,240)
r=7
while a < (start+datetime.timedelta(1)):
params = (a,b)
sql = "SELECT Date_Time, CM3_Up, CG3_Up, CM3_Down, CG3_Down FROM
Lysimeter_Facility_Data_5 WHERE Date_Time >= ? AND Date_Time <= ?"
for row in cur.execute(sql,params):
if row is None:
continue
r = r+1
ws.cell(row = r,column=12).value = row.get('CM3_Up')
ws.cell(row = r,column=13).value = row.get('CG3_Up')
ws.cell(row = r,column=14).value = row.get('CM3_Down')
ws.cell(row = r,column=15).value = row.get('CG3_Down')
a = a+five_min
b = b+five_min
wb.save('..\SE_SW_Lysimeters_Weather_Mass_Experiment-02_03_26_2015.xlsx')
Complete error report:
Traceback (most recent call last):
File "C:\DB_PY\access_mdb\db_to_xl.py", line 318, in <module>
for row in cur.execute(sql,params):
File "build\bdist.win32\egg\pypyodbc.py", line 1920, in next
row = self.fetchone()
File "build\bdist.win32\egg\pypyodbc.py", line 1871, in fetchone
value_list.append(buf_cvt_func(alloc_buffer.value))
ValueError: could not convert string to float: E-3
As to this discussion:
Python: trouble reading number format
the trouble could be that e should be d, like:
float(row.get('CM3_Up').replace('E', 'D'))
Sounds weird to me though, but I know only little of Python.
It sounds like you receive strings like '2.34E-3', so try with a conversion. Don't know Python, but in C# it could be like:
ws.cell(row = r,column=12).value = Convert.ToDouble(row.get('CM3_Up'))
ws.cell(row = r,column=13).value = Convert.ToDouble(row.get('CG3_Up'))
ws.cell(row = r,column=14).value = Convert.ToDouble(row.get('CM3_Down'))
ws.cell(row = r,column=15).value = Convert.ToDouble(row.get('CG3_Down'))

issue using wavread in matlab

I have the this:
name = ['Anca', 'Bogdan', 'Francois', 'Jerome', 'Simina'];
for i=1:size(name,1)
temp = name(i,:);
tempwav = wavread(temp);
end
And I get this error:
Error in Load_data (line 7)
tempwav = wavread(temp);
meaning this line: tempwav = wavread(temp);
The .wav files are there I just don't know what is the problem. Pls help
Your way of creating the variable name will result in the value AncaBogdanFrancoisJeromeSimina. Instead you should use a cell array (note the curly brackets)
name = {'Anca', 'Bogdan', 'Francois', 'Jerome', 'Simina'};
for i=1:length(name)
temp = name{i};
tempwav = wavread(temp);
end

Resources