I want to know why #XVAL shows the index (from 0 to 3 since there is 4 items in there) instead of ex:"< .50%" and so on. This will help me to change the desired output, which is "< .50%".
I've tried #AXISLABEL too and it doesn't work.
Here is a snippet of the code:
Private Sub LoadGraphicChart()
Try
C1Chart2.ChartGroups(0).ChartData.SeriesList.Clear()
' Data
Dim items As String() = New String() {"< 0.50%", "0.50% - 1.00%", "1.00% - 2.00%", "> 2.00%"}
Dim unitHData As Double() = New Double() {7 / 100, 0, 0, 1 / 100}
'first try, populating the series
Dim unitH As C1.Win.C1Chart.ChartDataSeriesCollection = C1Chart2.ChartGroups(0).ChartData.SeriesList
'unitH.Clear()
Dim series As ChartDataSeries = unitH.AddNewSeries
series.Label = "Unit Holder"
series.LineStyle.Color = Color.MediumPurple
series.X.CopyDataIn(items)
series.Y.CopyDataIn(unitHData)
'tooltip
C1Chart2.ToolTip.Enabled = True
For Each ds As ChartDataSeries In unitH
ds.TooltipText = "Series = {#TEXT}" + ControlChars.Cr + ControlChars.Lf + "X = {#XVAL}" + ControlChars.Cr + ControlChars.Lf + "Y = {#YVAL:0.00%}"
Next ds
End Try
End Sub
This is what the tooltip currently looks like:
Changing from using tooltiptext to CoordToDataIndex solved my problems.
Here is how I use it:
Private Sub C1Chart2_MouseClick(sender As Object, e As MouseEventArgs) Handles C1Chart2.MouseClick
Dim SeriesOutput As Integer
Dim PointOutput As Integer
Dim DistanceOutput As Integer
Dim items As String() = New String() {InputLabel10.Text, InputLabel9.Text, InputLabel8.Text, InputLabel7.Text}
Dim unitHData As String() = New String() {FormatPercent((CDbl(lblPersen00.Text) / 100)), FormatPercent((CDbl(lblPersen05.Text) / 100)), FormatPercent((CDbl(lblPersen10.Text) / 100)), FormatPercent((CDbl(lblPersen20.Text) / 100))}
C1Chart2.ChartGroups.Group0.CoordToDataIndex(e.X, e.Y, CoordinateFocusEnum.XandYCoord, SeriesOutput, PointOutput, DistanceOutput)
Debug.WriteLine("Series Index : " & SeriesOutput.ToString())
Debug.WriteLine("Point Index : " & PointOutput.ToString())
Debug.WriteLine("Distance from Point: " & DistanceOutput.ToString())
'MessageBox.Show(PointOutput)
If PointOutput.ToString <> "" Then
MessageBox.Show("X : " & items(PointOutput) & ControlChars.Cr & ControlChars.Lf & "Y : " & unitHData(PointOutput))
End If
End Sub
Result(First Data):
Result(Last Data):
Please see the code below:
Private Shared ReadOnly log As ILog = LogManager.GetLogger(GetType(ScheduledTasks))
Private Shared TestString As String = ""
Public Shared Sub writeConsole(ByVal i As Integer)
System.Threading.Thread.Sleep(1000)
TestString = TestString & i
End Sub
Public Shared Sub ParallelTest()
Dim int1 As Integer = 1, int2 As Integer = 2, int3 As Integer = 3, int4 As Integer = 4, int5 As Integer = 5, int6 As Integer = 6, int7 As Integer = 7, int8 As Integer = 8, int9 As Integer = 9, int10 As Integer = 10
Dim list As List(Of Integer) = New List(Of Integer)
list.Add(int1)
list.Add(int2)
list.Add(int3)
list.Add(int4)
list.Add(int5)
list.Add(int6)
list.Add(int7)
list.Add(int8)
list.Add(int9)
list.Add(int10)
Dim ParallelOptions As ParallelOptions = New ParallelOptions
ParallelOptions.MaxDegreeOfParallelism = 1 ' Environment.ProcessorCount * 10
Parallel.ForEach(Of Integer)(list.AsEnumerable(),
Sub(test As Integer)
writeConsole(test)
End Sub)
MsgBox("got here")
When the code reaches the message box, TestString contains the following value: 16237594810. I would expect it to be: 12345678910. It seems to indicate that multiple threads are being used even though MaxDegreeOfParallelism is set to: 1. Why is this?
I am little bit confused in this program.
I am new to Visual Basic but intermediate to C.
Actually I want to get sub-string of string without using library function of Visual Basic.
Here is the C source code I also given my VB code too.
1.The Program will get two inputs from user i.e A & B
2. Than Find the substring from B.
3. Finally Print the result.
int i,j=0,k=0,substr=0;
for(i=0;i<strlen(a);i++)
{
if(a[i]==b[j])
{
j++;
if(b[j]==0)
{
printf("second string is substring of first one");
substr=1;
break;
}
}
}
for(i=0;i<strlen(b);i++)
{
if(b[i]==a[k])
{
k++;
if(a[k]==0)
{
printf(" first string is substring of second string");
substr=1;
break ;
}
}
}
if(substr==0)
{
printf("no substring present");
}
While my code is
Dim a As String
Dim b As String
a = InputBox("Enter First String", a)
b = InputBox("Enter 2nd String", b)
Dim i As Integer
Dim j As Integer = 0
Dim k As Integer = 0
Dim substr As Integer = 0
For i = 0 To a.Length - 1
If a(i) = b(j) Then
j += 1
If b(j) = 0 Then
MsgBox("second string is substring of first one")
substr = 1
Exit For
End If
End If
Next i
For i = 0 To b.Length - 1
If b(i) = a(k) Then
k += 1
If a(k) = 0 Then
MsgBox(" first string is substring of second string")
substr = 1
Exit For
End If
End If
Next i
If substr = 0 Then
MsgBox("no substring present")
End If
End Sub
While compiling it gives following debugging errors.
Line Col
Error 1 Operator '=' is not defined for types 'Char' and 'Integer'. 17 24
Error 2 Operator '=' is not defined for types 'Char' and 'Integer'. 27 24
Part of your confusion is that .Net strings are much more than just character buffers. I'm going to assume that you can at least use strings. If you can't, use need to declare character arrays instead. That out of the way, this should get you there as a 1:1 translation:
Private Shared Function search(ByVal a As String, ByVal b As String) As Integer
Dim i As Integer = 0
Dim j As Integer = 0
Dim firstOcc As Integer
While i < a.Length
While a.Chars(i)<>b.Chars(0) AndAlso i < a.Length
i += 1
End While
If i >= a.Length Then Return -1 'search can not continue
firstOcc = i
While a.Chars(i)=b.Chars(j) AndAlso i < a.Length AndAlso j < b.Length
i += 1
j += 1
End While
If j = b.Length Then Return firstOcc
If i = a.Length Then Return -1
i = firstOcc + 1
j = 0
End While
Return 0
End Function
Shared Sub Main() As Integer
Dim a As String
Dim b As String
Dim loc As Integer
Console.Write("Enter the main string :")
a = Console.ReadLine()
Console.Write("Enter the search string :")
b = Console.ReadLine()
loc = search(a, b)
If loc = -1 Then
Console.WriteLine("Not found")
Else
Console.WriteLine("Found at location {0:D}",loc+1)
End If
Console.ReadKey(True)
End Sub
But please don't ever actually use that. All you really need is this:
Private Shared Function search(ByVal haystack as String, ByVal needle As String) As Integer
Return haystack.IndexOf(needle)
End Function
VB has a built-in function called InStr, it's part of the language. It returns an integer specifying the start position of the first occurrence of one string within another.
http://msdn.microsoft.com/en-us/library/8460tsh1(v=VS.80).aspx
Pete
Try this one, this will return a List(Of Integer) containing the index to all occurrence's of the find text within the source text, after the specified search starting position.
Option Strict On
Public Class Form1
''' <summary>
''' Returns an array of indexes where the find text occurred in the source text.
''' </summary>
''' <param name="Source">The text you are searching.</param>
''' <param name="Find">The text you are searching for.</param>
''' <param name="StartIndex"></param>
''' <returns>Returns an array of indexes where the find text occurred in the source text.</returns>
''' <remarks></remarks>
Function FindInString(Source As String, Find As String, StartIndex As Integer) As List(Of Integer)
If StartIndex > Source.Length - Find.Length Then Return New List(Of Integer)
If StartIndex < 0 Then Return New List(Of Integer)
If Find.Length > Source.Length Then Return New List(Of Integer)
Dim Results As New List(Of Integer)
For I = StartIndex To (Source.Length) - Find.Length
Dim TestString As String = String.Empty
For II = I To I + Find.Length - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then Results.Add(I)
Next
Return Results
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim Search As String = "Hello world, this world is an interesting world"
Dim Find As String = "world"
Dim Indexes As List(Of Integer) = New List(Of Integer)
Try
Indexes = FindInString(Search, Find, 0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
RichTextBox1.Text = "Search:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Search & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Find:" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & Find & vbCrLf & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "-----------" & vbCrLf
RichTextBox1.Text = RichTextBox1.Text & "Result Indexes:" & vbCrLf & vbCrLf
For Each i As Integer In Indexes
RichTextBox1.Text = RichTextBox1.Text & i.ToString & vbCr
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Here is another way, where there is no use of .Net functions.
Function FindInString(Source As String, Find As String, StartIndex As Integer) As Integer()
If StartIndex > Len(Source) - Len(Find) Then Return {}
If StartIndex < 0 Then Return {}
If Len(Find) > Len(Source) Then Return {}
Dim Results As Integer() = {}, ResultCount As Integer = -1
For I = StartIndex To Len(Source) - Len(Find)
Dim TestString As String = ""
For II = I To I + Len(Find) - 1
TestString = TestString & Source(II)
Next
If TestString = Find Then
ResultCount += 1
ReDim Preserve Results(ResultCount)
Results(ResultCount) = I
End If
Next
Return Results
End Function
How to remove the last element from an array in VB.NET. I need to split the street and housenumber.
STREET
Split the address on spaces
Remove last element (missing in the code)
Join array
NUMBER
Split the address on spaces
get last element
My code:
'split address
Dim addressArray() As String = args.Content.Split(" ")
'remove last element and return the joined array
Return String.Join(" ", addressArray.Remove(addressArray.Length() - 1))
Dim foo() As String = "This is a test".Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
Array.Resize(foo, foo.Length - 1)
Dim s As String = String.Join(" ", foo)
or use lists
Dim foo As New List(Of String)
foo.AddRange("This is a test".Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
foo.RemoveAt(foo.Count - 1)
Dim s As String = String.Join(" ", foo)
As far as using LINQ and performance, judge for yourself
Public Class Form1
'to LINQ or not to LINQ
'judge for yourself
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As System.Object, _
e As System.EventArgs) Handles Button1.Click
Dim ipsumA() As String = New String() {"Lorem", "ipsum", "dolor", "sit", _
"amet", "consectetur", "adipisicing", _
"elit", "sed", "do", "eiusmod", _
"tempor", "incididunt", "ut", "labore", _
"et", "dolore", "magna", "aliqua", "Ut", _
"enim", "ad", "minim", "veniam", "quis", _
"nostrud", "exercitation", "ullamco", _
"laboris", "nisi", "ut", "aliquip", "ex", _
"ea", "commodo", "consequat", "Duis", "aute", _
"irure", "dolor", "in", "reprehenderit", "in", _
"voluptate", "velit", "esse", "cillum", "dolore", _
"eu", "fugiat", "nulla", "pariatur", "Excepteur", _
"sint", "occaecat", "cupidatat", "non", "proident", _
"sunt", "in", "culpa", "qui", "officia", "deserunt", _
"mollit", "anim", "id", "est", "laborum"}
Const tries As Integer = 100000
Debug.WriteLine("")
stpw.Reset()
stpw.Start()
For x As Integer = 1 To tries
Dim s As String = arrayTake(ipsumA)
Next
stpw.Stop()
Debug.WriteLine(stpw.ElapsedTicks.ToString)
stpw.Reset()
stpw.Start()
For x As Integer = 1 To tries
Dim s As String = arrayRsz(ipsumA)
Next
stpw.Stop()
Debug.WriteLine(stpw.ElapsedTicks.ToString)
End Sub
Private Function arrayRsz(test As String()) As String
Array.Resize(test, test.Length - 1)
Return String.Join(" ", test)
End Function
Private Function arrayTake(test As String()) As String
Return String.Join(" ", test.Take(test.Length - 1))
End Function
End Class
You can't remove items from an array. The size of an array is decided when you create it, and can't be changed.
You can create a result that contains the items from the array except the last one:
Return String.Join(" ", addressArray.Take(addressArray.Length() - 1))
Edit:
If you are concerned about performance, you should not do any Split or Join at all, but simply get the parts of the string using simple string operations:
Dim pos As Integer = args.Content.LastIndexOf(" "C)
Dim street As String = args.Content.Substring(0, pos)
Dim number As String = args.Content.Substring(pos + 1)
This is at least ten times faster than any other method presented here.
Edit 2:
Here is the performance test code (C#):
Dim time As Performance = New Performance(1000000, 6)
Dim address As String = "aölskdjf öawe öofij 42"
Console.WriteLine(time.Take("SplitTakeJoin", Sub()
Dim parts As String() = address.Split(" "c)
Dim street As String = String.Join(" ", parts.Take(parts.Length - 1))
End Sub))
Console.WriteLine(time.Take("SplitResizeJoin", Sub()
Dim parts As String() = address.Split(" "c)
Array.Resize(parts, parts.Length - 1)
Dim street As String = String.Join(" ", parts)
End Sub))
Console.WriteLine(time.Take("Substring", Sub()
Dim street As String = address.Substring(0, address.LastIndexOf(" "c))
End Sub))
Output:
SplitTakeJoin 0,000511 ms.
SplitResizeJoin 0,000323 ms.
Substring 0,000031 ms.
using this performance test class:
Public Class Performance
Private _iterations As Integer
Private _displayDigits As Integer
Private _emptyTime As TimeSpan
Public Sub New(ByVal iterations As Integer, ByVal displayDigits As Integer)
_iterations = iterations
_displayDigits = displayDigits
_emptyTime = TimeSpan.Zero
_emptyTime = Take(Sub()
End Sub)
End Sub
Private Function Take(ByVal action As Action) As TimeSpan
Dim w As Stopwatch = Stopwatch.StartNew()
For i As Integer = 0 To _iterations - 1 Step 10
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Next
w.Stop()
Return w.Elapsed - _emptyTime
End Function
Public Function Take(ByVal title As String, ByVal action As Action) As String
Dim Time As TimeSpan = Take(action)
Return title + " " + (Time.TotalMilliseconds / Convert.ToDouble(_iterations)).ToString("N" + _displayDigits.ToString()) + " ms."
End Function
End Class
You could also try using Redim Preserve. These statements are carry overs from the Visual Basic 6.0 days and are not considered the .NET way of doing things, but it is another option. There may be performance issues though according to this article.
Redim Preserve addressArray(addressArray.Length - 1)
Actually to delete the last item of array you would have to:
Redim Preserve addressArray(addressArray.Length - 2)
since they are zero based and the length is one based.
This will return all but the last "word/number" in a String as an array of Strings.
Return args.content.Split(" ").Take((args.content.Split(" ").Count - 1)).ToArray()
How can I get the resulting generated list of links sorted out alphabetically according to "sTitle"? My sort function on line 272 is not giving me the results I need. Please help.
<script language="VB" runat="server">
Function sectionTitle(ByRef f As String)
'Open a file for reading
'Dim FILENAME As String = Server.MapPath("index.asp")
Dim FILENAME As String = f
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(FILENAME)
'Now, read the entire file into a string
Dim contents As String = objStreamReader.ReadToEnd()
'search string for <title>some words</title>
Dim resultText As Match = Regex.Match(contents, "(<title>(?<t>.*?)</title>)")
'put result into new string
Dim HtmlTitle As String = resultText.Groups("t").Value
Return HtmlTitle
' If HtmlTitle <> "" Then
'Response.Write(HtmlTitle)
' Else
'Response.Write("<ul><li>b: " & contents & "</a></li></ul>")
' End If
End Function
Public Class linkItem
Public myName As String
Public myValue As String
Public Sub New(ByVal myName As String, ByVal myValue As String)
Me.myName = myName
Me.myValue = myValue
End Sub 'New
End Class 'linkItem
Sub DirSearch(ByVal sDir As String)
Dim d As String
Dim f As String
Dim mylist As New List(Of linkItem)
Try
For Each d In Directory.GetDirectories(sDir)
'Response.Write("test c")
For Each f In Directory.GetFiles("" & d & "", "index.asp")
'Response.Write("test a")
Dim sTitle As String = sectionTitle(f)
'remove wilbur wright college - from sTitle string
sTitle = Regex.Replace(sTitle, "My College - ", "")
'print section title - must come before search n replace string
f = Regex.Replace(f, "C:\\inetpub\\wwwroot\\mypath\\", "")
'add to list
mylist.Add(New linkItem(f, sTitle))
'print links as list
'Response.Write("<ul><li><a href='" & f & "'>" & sTitle & "</a></li></ul>")
Next
DirSearch(d)
Next
Catch excpt As System.Exception
'Response.Write("test b")
Response.Write(excpt.Message)
End Try
mylist.Sort(Function(p1, p2) p1.myValue.CompareTo(p2.myValue))
mylist.ForEach(AddressOf ProcessLink)
End Sub
Sub ProcessLink(ByVal P As linkItem)
If (True) Then
Response.Write("<ul><li><a href='" & P.myName & "'>" & P.myValue & "</a></li></ul>")
End If
End Sub
</script>
<%
'Dim sDir As New DirectoryInfo(Server.MapPath(""))
Call DirSearch((Server.MapPath("")))
%>
Check out the IComparable interface to help with this.
Basically, you need to teach your program what to use as a comparison point of reference for your class.
IComparable will allow you to make use of the CompareTo() method.
Here's the sample code if you're interested:
Public Class Temperature
Implements IComparable
Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
Implements IComparable.CompareTo
If TypeOf obj Is Temperature Then
Dim temp As Temperature = CType(obj, Temperature)
Return m_value.CompareTo(temp.m_value)
End If
Throw New ArgumentException("object is not a Temperature")
End Function
' The value holder
Protected m_value As Integer
Public Property Value() As Integer
Get
Return m_value
End Get
Set(ByVal Value As Integer)
m_value = Value
End Set
End Property
Public Property Celsius() As Integer
Get
Return (m_value - 32) / 2
End Get
Set(ByVal Value As Integer)
m_value = Value * 2 + 32
End Set
End Property
End Class