Show First 10 Highest/Lower value in my Line Textbox - vb.net

I'd like to deepen this code, and show me the top 10 highest values, and the 10 lowest values. do you think it would be possible following the example given to me?
Dim myList = TxtNumberListCount.Lines.ToList
Dim removedEmptyLinesCount = myList.RemoveAll(Function(str) String.IsNullOrWhiteSpace(str))
Dim minValue = myList.Select(Function(line)
Dim res = 0
Integer.TryParse(line, res)
Return res
End Function).Min() ' or Max()
Dim lineIndex = myList.IndexOf(minValue) + removedEmptyLinesCount
TxtBoxMinValue1.Text = minValue
TxtBoxCountMinValue1.Text = lineIndex
Dim myList1 = TxtNumberListCount.Lines.ToList
Dim removedEmptyLinesCount1 = myList1.RemoveAll(Function(str) String.IsNullOrWhiteSpace(str))
Dim maxValue = myList1.Select(Function(line)
Dim res = 0
Integer.TryParse(line, res)
Return res
End Function).Max() ' or Max()
Dim lineIndex1 = myList1.IndexOf(maxValue) + removedEmptyLinesCount
TxtBoxMaxValue1.Text = maxValue
TxtBoxCountMaxValue1.Text = lineIndex1
TextBox6.Text = TxtNumberListScan.Lines(TxtBoxCountMinValue1.Text)
TextBox7.Text = TxtNumberListScan.Lines(TxtBoxCountMaxValue1.Text)

To get the most 10 highest values:
Dim Top10HighestValues = myList.Select(Function(line)
Dim res = 0
Integer.TryParse(line, res)
Return res
End Function).OrderByDescending(Function(x) x).Take(10)
And to get the most 10 lowest values you need to replace OrderByDescending with OrderBy:
Dim Top10LowestValues = myList.Select(Function(line)
Dim res = 0
Integer.TryParse(line, res)
Return res
End Function).OrderBy(Function(x) x).Take(10)
Save values and indexes into a Dictionary:
Dim dictionary As New Dictionary(Of String, Integer)
For Each i In Top10HighestValues
Dim idx = myList.IndexOf(i) + removedEmptyLinesCount
dictionary.Add(i, idx)
Next
For Each d In Dictionary
TextBox2.AppendText(d.Key & vbCrLf)
TextBox2.AppendText(d.Value & vbCrLf)
Next
Edit to get the indexes

Related

How to remove string except string startwith

I want to remove all string except string startwith EVOPB-
how can I make it happen ?
Private Sub StringResult()
Try
Dim web As New HtmlDocument()
web.Load(WebBrowser1.DocumentStream)
'' Extracting All Links
Dim redeem As HtmlNode = web.DocumentNode.SelectSingleNode("//div[#class='_58b7']")
If (redeem.InnerText.Contains("")) Then
Dim r As String = redeem.InnerText.ToString.Replace(vbNewLine, "")
TextBox1.Text = r
End If
Catch
Return
End Try
End Sub
Assuming what you are trying to match always starts with the same prefix and runs until the next space, something like this would work:
Public Shared Function ExtractStartsWith(ByVal Output As String, Optional StartsWith As String = "EVOPB") As List(Of String)
Dim pos As Integer = 0
Dim nextSpace As Integer
Dim results As New List(Of String)
Dim result As String
Do While pos >= 0 AndAlso pos < Output.Length
pos = Output.IndexOf(StartsWith, pos)
If pos >= 0 Then
nextSpace = Output.IndexOf(" ", pos)
If nextSpace > 0 Then
result = Output.Substring(pos, nextSpace - pos)
pos = nextSpace + 1
Else
result = Output.Substring(pos)
pos = Output.Length
End If
results.Add(result)
End If
Loop
Return results
End Function

VB.Net - Adwords API Get Domain Keywords, CPC And Search Volume

Function 1:
Public Function DomainKeywords(ByVal url As String) As String
Dim output As String = ""
Dim user As AdWordsUser = New AdWordsUser
Using targetingIdeaService As TargetingIdeaService = CType(user.GetService(AdWordsService.v201710.TargetingIdeaService), TargetingIdeaService)
Dim selector As New TargetingIdeaSelector()
selector.requestType = RequestType.IDEAS
selector.ideaType = IdeaType.KEYWORD
selector.requestedAttributeTypes = New AttributeType() {AttributeType.KEYWORD_TEXT, AttributeType.SEARCH_VOLUME, AttributeType.AVERAGE_CPC, AttributeType.CATEGORY_PRODUCTS_AND_SERVICES}
Dim searchParameters As New List(Of SearchParameter)
Dim relatedToUrlSearchParameter As New RelatedToUrlSearchParameter
relatedToUrlSearchParameter.urls = New String() {url}
relatedToUrlSearchParameter.includeSubUrls = False
searchParameters.Add(relatedToUrlSearchParameter)
Dim languageParameter As New LanguageSearchParameter()
Dim hebrew As New Language()
hebrew.id = 1027
languageParameter.languages = New Language() {hebrew}
searchParameters.Add(languageParameter)
Dim locationParameter As New LocationSearchParameter()
Dim israel As New Location
israel.id = 2376
locationParameter.locations = New Location() {israel}
searchParameters.Add(locationParameter)
selector.searchParameters = searchParameters.ToArray()
selector.paging = New Paging
Dim page As New TargetingIdeaPage()
Dim offset As Integer = 0
Dim pageSize As Integer = 180
Try
Dim i As Integer = 0
Do
selector.paging.startIndex = offset
selector.paging.numberResults = pageSize
page = targetingIdeaService.get(selector)
Dim keywordCheck As List(Of String) = New List(Of String)
If Not page.entries Is Nothing AndAlso page.entries.Length > 0 Then
For Each targetingIdea As TargetingIdea In page.entries
For Each entry As Type_AttributeMapEntry In targetingIdea.data
Dim ideas As Dictionary(Of AttributeType, AdWords.v201710.Attribute) = MapEntryExtensions.ToDict(Of AttributeType, AdWords.v201710.Attribute)(targetingIdea.data)
Dim keyword As String = DirectCast(ideas(AttributeType.KEYWORD_TEXT), StringAttribute).value
Dim averageMonthlySearches As Long = DirectCast(ideas(AttributeType.SEARCH_VOLUME), LongAttribute).value
'''''''''''''''''''This Returns a Wrong Number
Dim cpc As Money = DirectCast(ideas(AttributeType.AVERAGE_CPC), MoneyAttribute).value
Dim microedit As String = Math.Round(cpc.microAmount / 1000000, 2).ToString + "$"
''''''''''''''''''
Dim isExist As Boolean = False
For Each keycheck In keywordCheck
If keyword = keycheck Then
isExist = True
End If
Next
If isExist = False Then
keywordCheck.Add(keyword)
If output = String.Empty Then
output = keyword + "###" + microedit + "###" + averageMonthlySearches.ToString
Else
output = output + Environment.NewLine + keyword + "###" + microedit + "###" + averageMonthlySearches.ToString
End If
End If
Next
i = i + 1
Next
End If
offset = offset + pageSize
Loop While (offset < page.totalNumEntries)
Catch e As Exception
If output = String.Empty Then
output = "ERROR"
If e.Message.Contains("Rate exceeded") Then
MsgBox("rate exceeded")
Else
MsgBox(e.Message.ToString)
End If
End If
End Try
End Using
Return output
End Function
This function gets a url as input and returns keywords that relevant to that url as output in the following format:
KeywordName1###CPC###SearchVolume
KeywordName2###CPC###SearchVolume
for some reason no matter what website I type in it returns 180 results,
Im aware that pageSize is set to 180,
In-fact if you lower pageSize to 179, you only get 179 results, the problem is that i cant get more then 180 results whatsoever..
Optional help: also why the CPC value returned in the first function is different from the CPC value returned from that function:
Function 2:
Public Function KeywordCPC(keyName As String, Optional Tries As Integer = 0) As String
Dim output As String = ""
Dim user As AdWordsUser = New AdWordsUser
Using trafficEstimatorService As TrafficEstimatorService = CType(user.GetService(AdWordsService.v201710.TrafficEstimatorService), TrafficEstimatorService)
Dim keyword3 As New Keyword
keyword3.text = keyName
keyword3.matchType = KeywordMatchType.EXACT
Dim keywords As Keyword() = New Keyword() {keyword3}
Dim keywordEstimateRequests As New List(Of KeywordEstimateRequest)
For Each keyword As Keyword In keywords
Dim keywordEstimateRequest As New KeywordEstimateRequest
keywordEstimateRequest.keyword = keyword
keywordEstimateRequests.Add(keywordEstimateRequest)
Next
Dim adGroupEstimateRequest As New AdGroupEstimateRequest
adGroupEstimateRequest.keywordEstimateRequests = keywordEstimateRequests.ToArray
adGroupEstimateRequest.maxCpc = New Money
adGroupEstimateRequest.maxCpc.microAmount = 1000000
Dim campaignEstimateRequest As New CampaignEstimateRequest
campaignEstimateRequest.adGroupEstimateRequests = New AdGroupEstimateRequest() {adGroupEstimateRequest}
Dim countryCriterion As New Location
countryCriterion.id = 2376
Dim languageCriterion As New Language
languageCriterion.id = 1027
campaignEstimateRequest.criteria = New Criterion() {countryCriterion, languageCriterion}
Try
Dim selector As New TrafficEstimatorSelector
selector.campaignEstimateRequests = New CampaignEstimateRequest() {campaignEstimateRequest}
selector.platformEstimateRequested = False
Dim result As TrafficEstimatorResult = trafficEstimatorService.get(selector)
If ((Not result Is Nothing) AndAlso (Not result.campaignEstimates Is Nothing) AndAlso (result.campaignEstimates.Length > 0)) Then
Dim campaignEstimate As CampaignEstimate = result.campaignEstimates(0)
If ((Not campaignEstimate.adGroupEstimates Is Nothing) AndAlso (campaignEstimate.adGroupEstimates.Length > 0)) Then
Dim adGroupEstimate As AdGroupEstimate = campaignEstimate.adGroupEstimates(0)
If (Not adGroupEstimate.keywordEstimates Is Nothing) Then
For i As Integer = 0 To adGroupEstimate.keywordEstimates.Length - 1
Dim keyword As Keyword = keywordEstimateRequests.Item(i).keyword
Dim keywordEstimate As KeywordEstimate = adGroupEstimate.keywordEstimates(i)
If keywordEstimateRequests.Item(i).isNegative Then
Continue For
End If
Dim meanAverageCpc As Long = 0L
Dim meanAveragePosition As Double = 0
Dim meanClicks As Single = 0
Dim meanTotalCost As Single = 0
If (Not (keywordEstimate.min Is Nothing) AndAlso Not (keywordEstimate.max Is Nothing)) Then
If (Not (keywordEstimate.min.averageCpc Is Nothing) AndAlso Not (keywordEstimate.max.averageCpc Is Nothing)) Then
meanAverageCpc = CLng((keywordEstimate.min.averageCpc.microAmount + keywordEstimate.max.averageCpc.microAmount) / 2)
End If
End If
output = Math.Round(meanAverageCpc / 1000000, 2).ToString + "$"
Next i
End If
End If
Else
output = "ZERO"
End If
Catch e As Exception
If output = String.Empty Then
output = "ERROR"
If e.Message.Contains("Rate exceeded") Then
output = KeywordCPC(keyName, Tries + 1)
End If
End If
End Try
End Using
Return output
End Function
how can I get EXCAT CPC in the first function?
because now only the second function return good CPC and the
first function return the wrong CPC(checked in israeli adwords frontend)
If you want to know how to use the functions (for beginners):
VB.Net - Trying To Increase the efficiency of adwords API requests

Using MailMessage with semi cologn seperation

If I manually put my address in for EmailMessage.To.Add(GetDelimitedField(x, strEmailRep, ";")) It sends me the message just fine. However If I use the code as is below which is using a list that looks like ;email1#mail.com;email2.mail.com
Then it gives an error that email address cannot be blank
Somewhere in GetDelimitedField is erasing addresses. I'm not sure where the problem is actually occurring. Here is all the code involved with this.
strmsg = "LOW STOCK ALERT: Component (" & rsMPCS("MTI_PART_NO") & ") has reached or fallen below it's minimum quantity(" & rsMPCS("MIN_QTY") & ")."
Dim EmailMessage As MailMessage = New MailMessage
EmailMessage.From = New MailAddress("noreply#mail.com")
For x = 1 To GetCommaCount(strEmailRep) + 1
EmailMessage.To.Add(GetDelimitedField(x, strEmailRep, ";"))
Next
EmailMessage.Subject = ("LOW STOCK ALERT!")
EmailMessage.Body = strmsg
EmailMessage.Priority = MailPriority.High
EmailMessage.IsBodyHtml = True
Dim smtp As New SmtpClient("smtp.mycompany.com")
smtp.UseDefaultCredentials = True
smtp.Send(EmailMessage)
Public Function GetCommaCount(ByVal sText As String)
Dim X As Integer
Dim Count As Integer
Dim Look As String
For X = 1 To Len(sText)
Look = Microsoft.VisualBasic.Left(sText, X)
If InStr(X, Look, ";", 1) > 0 Then
Count = Count + 1
End If
Next
GetCommaCount = Count
End Function
Public Function GetDelimitedField(ByRef FieldNum As Short, ByRef DelimitedString As String, ByRef Delimiter As String) As String
Dim NewPos As Short
Dim FieldCounter As Short
Dim FieldData As String
Dim RightLength As Short
Dim NextDelimiter As Short
If (DelimitedString = "") Or (Delimiter = "") Or (FieldNum = 0) Then
GetDelimitedField = ""
Exit Function
End If
NewPos = 1
FieldCounter = 1
While (FieldCounter < FieldNum) And (NewPos <> 0)
NewPos = InStr(NewPos, DelimitedString, Delimiter, CompareMethod.Text)
If NewPos <> 0 Then
FieldCounter = FieldCounter + 1
NewPos = NewPos + 1
End If
End While
RightLength = Len(DelimitedString) - NewPos + 1
FieldData = Microsoft.VisualBasic.Right(DelimitedString, RightLength)
NextDelimiter = InStr(1, FieldData, Delimiter, CompareMethod.Text)
If NextDelimiter <> 0 Then
FieldData = Microsoft.VisualBasic.Left(FieldData, NextDelimiter - 1)
End If
GetDelimitedField = FieldData
End Function
You can split the list easier using string.Split:
Dim strEmails = "a#test.com;b#test.com;c#test.com;"
Dim lstEmails = strEmails.Split(";").ToList()
'In case the last one had a semicolon:
If (lstEmails(lstEmails.Count - 1).Trim() = String.Empty) Then
lstEmails.RemoveAt(lstEmails.Count - 1)
End If
If (lstEmails.Count > 0) Then
lstEmails.AddRange(lstEmails)
End If

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help

Name Proper Casing

Can you help me in having a proper casing,
I have this code...
Private Function NameCsing(ByVal sValue As String) As String
Dim toConvert As String() = sValue.Split(" ")
Dim lst As New List(Of String)
For i As Integer = 0 To toConvert.Length - 1
Dim converted As String = ""
If toConvert(i).Contains("~") Then
Dim toName As String() = toConvert(i).Split("~")
Dim sName As String = ""
For n As Integer = 0 To toName.Length - 1
Dim sconvert As String = ""
If n = 0 Then
sName = StrConv(toName(n), VbStrConv.ProperCase)
Else
sName += StrConv(toName(n), VbStrConv.ProperCase)
End If
Next
converted = sName
Else
converted = toConvert(i)
End If
lst.Add(converted)
Next
Dim ret As String = ""
For i As Integer = 0 To lst.Count - 1
If i = 0 Then
ret = lst(0)
Else
ret += " " + lst(i)
End If
Next
Return ret
End Function
My codes will just output like this "McDonalds" is you input "mc~donalds"
now my problem is eh I input "evalue", my output must be "eValue"
The only way to know how to treat a special string is to code it yourself from a list of rules:
Private Function NameCsing(ByVal sValue As String) As String
If sValue.Trim.ToLower = "evalue" Then Return "eValue"
'Then process any other special cases
End Function