I have a Pipe | delimited file I'm sending out and in a string field the client is using Pipes as just a random character to separate points.
Example. This is what text they have in the field.
Encore AWD | Leather | Navigation | Sunroof | Back Up Camera | USB | Bluetooth
I need to replace the | with a - and this is the code I'm trying.
#set ($va.list_comment = $va.listing_comment.replace("|", "-"))
it is still outputting the | characters.
Anyone have any ideas what I could be doing wrong here?
You cannot assign a new value into an object. If you're using the latest version of Velocity, then such an assignment would work if there is a setList_comment method, or if $va is a Map. Otherwise, you would have to just create a new variable that would host the new value and use it:
#set ($fixedListing = $va.listing_comment.replace("|", "-"))
$fixedListing
Or if you don't need that value for anything else than just printing it once, skip the assignment completely and just print the outcome:
$va.listing_comment.replace("|", "-")
If that still doesn't work, make sure the value returned is indeed a java.lang.String and not something else:
$va.listing_comment.class
Related
I'm trying to sort servers by the 2nd index of the name.
The server names are taken from file paths where they are the BaseName of the file.
I know that Select-Object has the parameter -Index, but I don't think that will work.
I am assuming that the best approach is with a PowerShell RegEx like "(?:^a-z))". This returns an unsorted list and I'm still googling around for a pattern that will sort by the 2nd Index.
Example of the Intended Output
Group the servers by name CC or DD
Server
------
ABCCWS01
CDCCWS01
ABDDWS01
CDDDWS01
Current Output
Sorts alphabetically by -Property name
$servers = Get-Item -Path
C:\ABDDWS01.ServerData,
C:\ABCCWS01.ServerData,
C:\CDCCWS01.ServerData,
C:\CDDDWS01.ServerData | Group BaseName -AsHashtable
foreach($computer in $servers.GetEnumerator() | Sort-Object -Property name)
{ ...DoSomething... }
Server
------
ABCCWS01
ABDDWS01
CDCCWS01
CDDDWS01
Then I tried to implement a PowerShell RegEx. But I'm stuck on how to properly use this to sort by the 2nd index. This example has no affect and returns the list unsorted. I've tried subbing in different patterns at the end "(?:^a-z))". So far my attempts either return the list unsorted or just a segment of the list.
I've googled around and tried many different things. If someone else wants to help puzzle this out, it is much appreciated.
Sort-Object -Property #{Expression={[RegEx]::Match($_.basename, "(?:^a-z))")}}
Sort-Object works by "ranking" each input according to the resulting value of calculating one or more property expressions against each input item - in your existing example, based on the the value of the name property.
As you've already found, property expressions doesn't have to be the value of any existing property though - they can be made up of anything - just pass a script block in place of the property name:
... |Sort-Object -Property {$_.name[1]}
The reason it doesn't work in your example is that the expression [RegEx]::Match($_.basename, "(?:^a-z))") returns a [System.Text.RegularExpressions.Match] object - and those can't be meaningfully compared to one another.
If you change the expression to resolve to a string instead (the matched value for example), it'll work:
... |Sort-Object -Property #{Expression={[RegEx]::Match($_.basename, "(?:^a-z))").Value}}
# or
... |Sort-Object -Property {[RegEx]::Match($_.basename, "(?:^a-z))").Value}
I have a result set that looks like
{add=[44961373 (1645499799657512961), 44961374 (1645499799658561538), 44962094 (1645499799659610114), 44962095 (1645499799659610117), 44962096 (1645499799660658689), 44962097 (1645499799660658691), 44962098 (1645499799661707264), 44962099 (1645499799661707267), 44962100 (1645499799662755840), 44962101 (1645499799662755843), ... (592 adds)]}
If the add=[ array has more than 10 elements in it. Then it will put (x adds) at the end of the statement to show how many actual adds there were. IF it has less than 10, then it wont put the (x adds) statement. I am wanting timechart and also single value these outputs to a dashboard(separate modules).
I can get one or the other but I would like to use from logic to figure out which one to report.
index="index" host="host*" path=/update | eval count=mvcount(add) | stats count
will get the count of the array
index="index" host="host*" path=/update | stats sum(Adds)
will get the value of the (x adds). Adds is a 'extracted field'.
How do I get either or? If add array >10, use sum(Adds), in the same breath.
index="index" host="host*" path=/update | eval count=mvcount(add)
| eval first_ten="{add=[".mvjoin(mvindex(add,0,9), ",")." (" (count-10)." adds)}"
| eval msg=if(count<10,_raw,first_ten)
You can do something like this. Get the count of adds, create a new string with the first 10 elements only, with the count-10 adds message at the end. Then, depending on the actual count, either use the original (_raw), or the new message.
I am building a workbook in PowerBI and I have the need for doing a conditional appending of text to column A if it meets a certain criteria. Specifically, if column A does not end with ".html" then I want to append the text ".html" to the column.
A sample of the data would look like this:
URL | Visits
site.com/page1.html | 5
site.com/page2.html | 12
site.com/page3 | 15
site.com/page4.html | 8
where the desired output would look like this:
URL | Visits
site.com/page1.html | 5
site.com/page2.html | 12
site.com/page3.html | 15
site.com/page4.html | 8
I have tried using the code:
#"CurrentLine" = Table.TransformColumns(#"PreviousLine", {{"URL", each if Text.EndsWith([URL],".html") = false then _ & ".html" else "URL", type text}})
But that returns an error "cannot apply field access to the type Text".
I can achieve the desired output in a very roundabout way if I use an AddColumn to store the criteria value, and then another AddColumn to store the new appended value, but this seems like an extremely overkill way to approach doing a single transformation to a column. (I am specifically looking to avoid this as I have about 10 or so transformations and don't want to have so many columns to add and cleanup if there is a more succinct way of coding)
You don't want [URL] inside Text.EndWith. Try this:
= Table.TransformColumns(#"PreviousLine",
{{"URL", each if Text.EndsWith(_, ".html") then _ else _ & ".html", type text}}
)
I have a file in the format:
0000 | a1_1,a3_2 | b2_1, b3_2
0001 | a1_3 | b4_1
and I'm trying to create a dictionary which has
{ 'a1' : set(['b2', 'b3', 'b4']), 'a3': set(['b2', 'b3']) }
and this is how my code looks like:
def get_ids(row, col):
ids = set()
x = row.strip().split('|')
for a in x[col].split(','):
ids.add(a.split('_')[0])
return ids
def add_to_dictionary(funky_dictionary,key, values):
if key in funky_dictionary:
funky_dictionary[key].update(values)
else:
funky_dictionary[key] = values
def get_dict(input_file):
funky_dictionary = {}
with open(input_file,'r') as ip:
for row in ip:
a_ids = get_ids(row,1)
b_ids = get_ids(row,2)
for key in a_ids:
add_to_dictionary(funky_dictionary,key,b_ids)
return funky_dictionary
So my problem is this when I lookup values for certain key in the dictionary, it returns me with way more values than expected. E.g.
For the above example the expected value of a3 would be set(['b2', ' b3'])
However with the code, I'm getting set(['b2', ' b3', 'b4'])
I cant figure out whats wrong with the code. Any help?
The issue you have is that many of your dictionary's values are in fact references to the same set instances. In your example data, when the first line is processed, 'a1' and 'a3' both get mapped to the same set object (containing 'b2' and 'b3'). When you process the second line and call update on that set via the key 'a1', you'll see the added value through 'a3' too, since both values are references to the same set.
You need to change the code so that each value is a separate set object. I'd suggest getting rid of add_to_dictionary and just using the dictionary's own setdefault method, like this:
for key in a_ids:
funky_dictionary.setdefault(key, set()).update(b_ids)
This code always starts with a new empty set for a new key, and always updates it with new values (rather than adding a reference to the b_ids set to the dictionary directly).
So, I have this RegEx that captures a specific string I need (thanks to Shawn Mehan):
>?url:\'\/watch\/(video[\w-\/]*)
It works great, but now I need to mod my criteria. I need to capture ONLY the first URL after EACH instance of: videos:[{title:. Bolded all instances below and also bolded the first URL I'd want captured as an example.
How might I approach this? I have a VBScript that will dump each URL to a text file, so I just need help selecting the correct URLs from the blob below. Thinking something like, "if this string is found, do this, loop". Setting the regex global to false should only grab the first instance each round, right? A basic example would help.
I believe I have all of the pieces I need, but I'm not quite sure how to put them together. I'm expecting the code below to loop through and find the index of each instance of "videos:[{title:", then the regex to grab the first URL after (regexp global set to false) based on the pattern, then write the found URL to my text file, loop until all are found. Not working...
(larger portion of html_dump: http://pastebin.com/6i5gmeTB)
Set objWshShell = Wscript.CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set objRegExp = new RegExp
objRegExp.Global = False
objRegExp.Pattern = ">?url:\'\/watch\/(video[\w-\/]*)"
filename = fso.GetParentFolderName(WScript.ScriptFullName) & "\html_dump.txt" 'Text file contains html
set urldump = fso.opentextfile(filename,1,true)
do until urldump.AtEndOfStream
strLine = urldump.ReadLine()
strSearch = InStrRev(strLine, "videos:[{title:") 'Attempting to find the position of "videos:[{title:" to grab the first URL after.
If strSearch >0 then
Set myMatches = objRegExp.Execute(strLine) 'This matches the URL pattern.
For Each myMatch in myMatches
strCleanURL = myMatch.value
next
'===Writes clean urls to txt file...or, it would it if worked===
filename1 = fso.GetParentFolderName(WScript.ScriptFullName) & "\URLsClean.txt" 'Creates and writes to this file
set WriteURL = fso.opentextfile(filename1,2,true)
WriteURL.WriteLine strCleanURL
WriteURL.Close
else
End if
loop
urldump.close
var streams = [ {streamID:138, cards:[{cardId: 59643,cardTypeId: 48,clickCount: 84221,occurredOn: '2015-08-17T15:30:17.000-07:00',expiredOn: '',header: 'Latest News Headlines', subHeader: 'Here are some of the latest headlines from around the world.', link: '/watch/playlist/544/Latest-News-Headlines', earn: 3, playlistRevisionID: 3427, image: 'http%3A%2F%2Fpthumbnails.5min.com%2F10380591%2F519029502_3_o.jpg', imageParamPrefix: '?', size: 13, durationMin: 15, durationTime: '14:34',pos:0,trkId:'2gs55j6u0nz8', true,videos:[{title:'World\'s First Sky Pool Soon To Appear In South London',thumbnail:'http%3A%2F%2Fpthumbnails.5min.com%2F10380509%2F519025436_c_140_105.jpg',durationTime:'0:39',url:'/watch/video/716424/worlds-first-sky-pool-soon-to-appear-in-south-london',rating:'4.2857'},{title:'Treasure Hunters Find $4.5 Million in Spanish Coins',thumbnail:'http%3A%2F%2Fpthumbnails.5min.com%2F10380462%2F519023092_3.jpg',durationTime:'0:54',url:'/watch/video/715927/treasure-hunters-find-4-5-million-in-spanish-coins',rating:'4.25'},{title:'Former President Jimmy Carter Says Cancer Has Spread to Brain',thumbnail:'http%3A%2F%2Fpthumbnails.5min.com%2F10380499%2F519024920_c_140_105.jpg',durationTime:'1:59',url:'/watch/video/716363/former-president-jimmy-carter-says-cancer-has-spread-to-brain',rating:'2.8889'},{title:'Josh Duggar Had Multiple Accounts on AshleyMadison.Com',thumbnail:'http%3A%2F%2Fpthumbnails.5min.com%2F10380505%2F519025222_c_140_105.jpg',durationTime:'1:30',
Assuming that your input comes from a file and is in correct JSON format you could do something like this in PowerShell:
$jsonfile = 'C:\path\to\input.txt'
$json = Get-Content $jsonfile -Raw | ConvertFrom-Json
$json.streams.cards | ForEach-Object { $_.videos[0].url }
The above is assuming that streams is the topmost key in your JSON data.
Note that the code requires at least PowerShell v3.