How to convert a string to an array in FreeMarker - arrays

I have got stuck in one problem:
If the user give the value of a = abhay, himanshu, aman, piyush
they have not mentioned like this a = ["abhay","himanshu","aman","piyush"].
So how should I use this a as an array in this:
<#list a as x>
${x}
</#list>

You can use the string builtin ?split to split a string by a regular expression:
<#list "abhay, himanshu, aman, piyush"?split(", ?", "r") as x>
${x}
</#list>
See also:
https://freemarker.apache.org/docs/ref_builtins_string.html#ref_builtin_split

Related

Read String and convert it to array with ; as new item [duplicate]

I have a string that has email addresses separated by semi-colon:
$address = "foo#bar.com; boo#bar.com; zoo#bar.com"
How can I split this into an array of strings that would result as the following?
[string[]]$recipients = "foo#bar.com", "boo#bar.com", "zoo#bar.com"
As of PowerShell 2, simple:
$recipients = $addresses -split "; "
Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit to force case-sensitivity. See about_Split for more details.
[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)
Remove the spaces from the original string and split on semicolon
$address = "foo#bar.com; boo#bar.com; zoo#bar.com"
$addresses = $address.replace(' ','').split(';')
Or all in one line:
$addresses = "foo#bar.com; boo#bar.com; zoo#bar.com".replace(' ','').split(';')
$addresses becomes:
#('foo#bar.com','boo#bar.com','zoo#bar.com')

Unique combinations of different values in json using jq

I have a json file(input.json) which looks like this :
{"header1":"a","header2":1a, "header3":1a, "header4":"apple"},
{"header1":"b","header2":2a, "header3":2a, "header4":"orange"}
{"header1":"c","header2":1a, "header3":2a, "header4":"banana"},
{"header1":"d","header2":2a, "header3":1a, "header4":"apple"},
{"header1":"a","header2":2a, "header3":1a, "header4":"banana"},
{"header1":"b","header2":1a, "header3":2a, "header4":"orange"},
{"header1":"b","header2":1a, "header3":1a, "header4":"orange"},
{"header1":"d","header2":1a, "header3":1a, "header4":"apple"},
{"header1":"a","header2":2a, "header3":1a, "header4":"banana"} (repeat of line 5)
I want to filter out only the unique combinations of each of the values jq.
Results should look like:
{"header1":"a","header2":1a, "header3":1a, "header4":"apple"},
{"header1":"b","header2":2a, "header3":2a, "header4":"orange"}
{"header1":"c","header2":1a, "header3":2a, "header4":"banana"},
{"header1":"d","header2":2a, "header3":1a, "header4":"apple"},
{"header1":"a","header2":2a, "header3":1a, "header4":"banana"},
{"header1":"b","header2":1a, "header3":2a, "header4":"orange"},
{"header1":"b","header2":1a, "header3":1a, "header4":"orange"},
{"header1":"d","header2":1a, "header3":1a, "header4":"apple"}
I tried doing group by of header1 with the other headers but it didn't generate unique results.
I've used unique but that didnt generate the proper results.
How can I get this? Im new to jq and not finding many tutorials on it.
Thanks
The sample lines you give are not valid JSON. Since your preamble introduces them as JSON, the following will assume that you intended to present an array of JSON objects.
The question is unclear in several respects, but from the example, it looks as though unique might be what you're looking for, so consider:
Invocation: jq -c 'unique[]' input.json
Output:
{"header1":"a","header2":"1a","header3":"1a","header4":"apple"}
{"header1":"a","header2":"2a","header3":"1a","header4":"banana"}
{"header1":"b","header2":"1a","header3":"1a","header4":"orange"}
{"header1":"b","header2":"1a","header3":"2a","header4":"orange"}
{"header1":"b","header2":"2a","header3":"2a","header4":"orange"}
{"header1":"c","header2":"1a","header3":"2a","header4":"banana"}
{"header1":"d","header2":"1a","header3":"1a","header4":"apple"}
{"header1":"d","header2":"2a","header3":"1a","header4":"apple"}
If you need the output in some other format, you could do that using jq as well, but the requirements are not so clear, so let's leave that as an exercise :-)
Since as peak indicated your input isn't legal JSON I've taken the liberty of correcting it and converting to a list of individual objects:
{"header1":"a","header2":"1a", "header3":"1a", "header4":"apple"}
{"header1":"b","header2":"2a", "header3":"2a", "header4":"orange"}
{"header1":"c","header2":"1a", "header3":"2a", "header4":"banana"}
{"header1":"d","header2":"2a", "header3":"1a", "header4":"apple"}
{"header1":"a","header2":"2a", "header3":"1a", "header4":"banana"}
{"header1":"b","header2":"1a", "header3":"2a", "header4":"orange"}
{"header1":"b","header2":"1a", "header3":"1a", "header4":"orange"}
{"header1":"d","header2":"1a", "header3":"1a", "header4":"apple"}
{"header1":"a","header2":"2a", "header3":"1a", "header4":"banana"}
If this data is in data.json and you run
jq -M -s -f filter.jq data.json
with the following filter.jq
foreach .[] as $r (
{}
; ($r | map(.)) as $p | if getpath($p) then empty else setpath($p;1) end
; $r
)
it will generate the following output in the original order with no duplicates.
{"header1":"a","header2":"1a","header3":"1a","header4":"apple"}
{"header1":"b","header2":"2a","header3":"2a","header4":"orange"}
{"header1":"c","header2":"1a","header3":"2a","header4":"banana"}
{"header1":"d","header2":"2a","header3":"1a","header4":"apple"}
{"header1":"a","header2":"2a","header3":"1a","header4":"banana"}
{"header1":"b","header2":"1a","header3":"2a","header4":"orange"}
{"header1":"b","header2":"1a","header3":"1a","header4":"orange"}
{"header1":"d","header2":"1a","header3":"1a","header4":"apple"}
Note that the
($r | map(.))
is used to generate an array containing just the values from each row
which is assumed to always produce a unique key path. This is true for
the sample data but may not be true for more complex values.
A slower but more robust filter.jq is
foreach .[] as $r (
{}
; [$r | tojson] as $p | if getpath($p) then empty else setpath($p;1) end
; $r
)
which uses the json representation of the entire row as a unique key to determine if a row has been previously seen.

How to inject characters into an array, and join that array into a string?

I have a url that's split by = parameters, what I want to do is inject characters into the array after every =:
For example:
http://multiplexstimulator.com/catalog/product.php?cat_id=82&pid=157&view=print
Should be split by the equals sign into an array that looks like this:
["http://multiplexstimulator.com/catalog/product.php?cat_id", "=", "82&pid", "=", "157&view", "=", "print"]
Then I want to add the letter "a" after the equals signs:
["http://multiplexstimulator.com/catalog/product.php?cat_id", "=", "a", "82&pid", "=", "a", "157&view", "=", "a", "print"]
After this is done I want to join that array to output:
"http://multiplexstimulator.com/catalog/product.php?cat_id=a82&pid=a157&view=aprint"
What I've tried:
module MultipleParameters
class TestAllParameters
def check_for_multiple_parameters(site, char)
site_arr = []
if site.count("=") != 1
site.split("=").each do |string_split|
site_arr.push(string_split)
end
end
inject_syntax(site_arr, char)
end
def inject_character(array, char)
array.each do |param|
param.inject(char)
end
puts array.join("")
end
end
end
However when I do this, I'm getting the error:
detection.rb:18:in `block in inject_syntax': undefined method `inject' for "http://multiplexstimulator.com/catalog/product.php?cat_id":String (NoMethodError)
Did you mean? inspect
from detection.rb:17:in `each'
from detection.rb:17:in `inject_syntax'
from detection.rb:13:in `check_for_multiple_parameters'
from detection.rb:33:in `<main>'
How can I do this successfully? Will I need to scan the string and split it when there's a "=" found instead of splitting the string by the equals sign?
You can just use the gsub method.
str = 'http://multiplexstimulator.com/catalog/product.php?cat_id=82&pid=157&view=print'
str.gsub('=','=a')
This yields
"http://multiplexstimulator.com/catalog/product.php?cat_id=a82&pid=a157&view=aprint"
Note that gsub does not modify the original string, if you want to modify it, use gsub!
Firstly you should separate params from url
url = 'http://multiplexstimulator.com/catalog/product.php?cat_id=82&pid=157&view=print'
array = url.split('/')
and now you should change all '=' to '=a' in last element in this array
array[-1] = array[-1].gsub('=', '=a')
now you can use join on this array :)
new_url = array.join('')

Extract Text from Array - perl

I am trying to extract the Interface from an array created from an SNMP Query.
I want to create an array like THIS:
my #array = ( "Gig 11/8",
"Gig 10/1",
"Gig 10/4",
"Gig 10/2");
It currently looks like THIS:
my #array =
( "orem-g13ap-01 Gig 11/8 166 T AIR-LAP11 Gig 0",
"orem-g15ap-06 Gig 10/1 127 T AIR-LAP11 Gig 0",
"orem-g15ap-05 Gig 10/4 168 T AIR-LAP11 Gig 0",
"orem-g13ap-03 Gig 10/2 132 T AIR-LAP11 Gig 0");>
I am doing THIS:
foreach $ints (#array) {
#gig = substr("$ints", 17, 9);
print("Interface: #gig");
Sure it works, but the hostname [orem-g15ap-01] doesn't always stay the same length, it varies depending on the site. I need to extract the word "Gig" plus the next 6 characters. I have no idea what is the best way of doing this.
I am a novice at perl but trying. Thanks
# "I need to extract the word "Gig" plus the next 6 characters."
# This looks like a fixed-with file format, so consider using unpack.
foreach ( #lines ) {
my( $orem, $gig, $rest ) = unpack 'a17 a9 a*';
print "[$gig]\n";
}
If it's not fixed-with format, then you need to find out what the file spec is and then maybe use a regular expression, something like:
my( $orem, $gig, $rest ) = m/(\S+)\s+(.{9})(.*)/;
But this will not work in the general case without a proper file spec.
Stuff like that is what Perl is made for. Regular Expressions are the way to go. Read the perldoc perlre.
foreach $ints (#array) {
$ints =~ s/(Gig.{6})/$1/g;
}
So you want the second and third field.
my #array = map { /^\S+\s+(\S+\s\S+)/s } #source;
This one is like ikegami's, but I recommend that if you know how something you want looks, then by all means, specify that. Because this is done in a list context, any string that does not match the spec, returns an empty list--or is ignored.
my #results = map { m!(\bGig\s+\d+/d+)! } #array;

Output formatting in Python: replacing several %s with the same variable

I'm trying to maintain/update/rewrite/fix a bit of Python that looks a bit like this:
variable = """My name is %s and it has been %s since I was born.
My parents decided to call me %s because they thought %s was a nice name.
%s is the same as %s.""" % (name, name, name, name, name, name)
There are little snippets that look like this all over the script, and I was wondering whether there's a simpler (more Pythonic?) way to write this code. I've found one instance of this that replaces the same variable about 30 times, and it just feels ugly.
Is the only way around the (in my opinion) ugliness to split it up into lots of little bits?
variable = """My name is %s and it has been %s since I was born.""" % (name, name)
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name)
variable += """%s is the same as %s.""" % (name, name)
Use a dictionary instead.
var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }
Or format with explicit numbering.
var = '{0} {0} {0}'.format('look_at_meeee')
Well, or format with named parameters.
var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')
Python 3.6 has introduced a simpler way to format strings. You can get details about it in PEP 498
>>> name = "Sam"
>>> age = 30
>>> f"Hello, {name}. You are {age}."
'Hello, Sam. You are 30.'
It also support runtime evaluation
>>>f"{2 * 30}"
'60'
It supports dictionary operation too
>>> comedian = {'name': 'Tom', 'age': 30}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
The comedian is Tom, aged 30.
Use formatting strings:
>>> variable = """My name is {name} and it has been {name} since..."""
>>> n = "alex"
>>>
>>> variable.format(name=n)
'My name is alex and it has been alex since...'
The text within the {} can be a descriptor or an index value.
Another fancy trick is to use a dictionary to define multiple variables in combination with the ** operator.
>>> values = {"name": "alex", "color": "red"}
>>> """My name is {name} and my favorite color is {color}""".format(**values)
'My name is alex and my favorite color is red'
>>>
Use the new string.format:
name = 'Alex'
variable = """My name is {0} and it has been {0} since I was born.
My parents decided to call me {0} because they thought {0} was a nice name.
{0} is the same as {0}.""".format(name)
>>> "%(name)s %(name)s hello!" % dict(name='foo')
'foo foo hello!'
You could use named parameters. See examples here
variable = """My name is {0} and it has been {0} since I was born.
My parents decided to call me {0} because they thought {0} was a nice name.
{0} is the same as {0}.""".format(name)
have a look at Template Strings
If you are using Python 3, than you can also leverage, f-strings
myname = "Test"
sample_string = "Hi my name is {name}".format(name=myname)
to
sample_string = f"Hi my name is {myname}"

Resources