Variable inside a variable in Jenkinsfile - variables

What is the correct Jenkinsfile syntax in order to use a variable value when executing command with another variable?
For example:
def lastItemIndex = "${json.items.size()-1}"
def path = "${json.items[${lastItemIndex}].assets.downloadUrl}"
echo "${path}"
First variable is lastItemIndex and second one is json.
The second row is not running properly when I tried different options.

The syntax in your second row is mostly fine. Your problem is that you are storing the return of lastItemIndex as a String and then attempting to use it as an Integer in your second row of code.
You can fix your first row with:
lastItemIndex = json.items.size() - 1
and then it will be an Integer type and def path = "${json.items[lastItemIndex].assets.downloadUrl}" will succeed.
Alternatively, you could just have the second line of code with:
def path = "${json.items[-1].assets.downloadUrl}"
to access the last element of the array.
Note that in general if you need to convert a String to an Integer within a Jenkins Pipeline via Groovy you can utilize the to_Integer method.

Thanks to Matt, eventually that what works for me:
def lastItemIndex = json.items.size()-1
def path = json.items[lastItemIndex].assets.downloadUrl

Related

Using call read within a js function

I have a slight problem I want to solve. I have the following lines of code which create 2 users which works. However the issue is that, it creates both users with the same Id from the the first line of code:
def myId = call read('classpath:karate/helpers/guid.js')
def users = function(){ karate.call('classpath:v1/api_CreateUser.feature')}
def usersResult = karate.repeat(2, users )
So I want to be able to create multiple users with different Ids. I tried the following:
* def users =
"""
function(){
var myId = null;
if(myId == null)
{
myId = call read('classpath:karate/helpers/guid.js')
}
karate.call('classpath:v1/api_CreateUser.feature');
}
"""
def usersResult = karate.repeat(2, users )
So the idea is to reset the 'myId' variable everytime to null, check if null which will be true, then call the js function which generates the id and assign the result to 'myId' variable.
Then the variable will be used on the karate.call('classpath:v1/api_CreateUser.feature') line.
Unfortunately I'm getting javascript evaluation failed error.
Anyone could help?
Thanks
Be clear about the slight difference when you are in Karate and when you are in JS. For example:
myId = call read('classpath:karate/helpers/guid.js')
This won't work. What you are looking for is:
myId = karate.call('classpath:karate/helpers/guid.js');
I recommend you read and understand the section on Karate Expressions it will save you a lot of trouble later.
When you use a JS function (that works) you should never need to worry about what you are. Just invoke it wherever, and it will "dispense" a new value. For example if you have:
* def time = function(){ return java.lang.System.currentTimeMillis() + '' }
* def first = time()
* def second = time()
Here first and second will always be different. I think now you have all you need. You are trying to access a JS variable defined in Karate from within a function, this depends on when either was initialized and I don't recommend it if you don't know what you are doing. But if you want to access the latest value of a Karate variable, the right way is to use karate.get(varNameAsString).

How to pass variable to groovy code in Intellij IDEA live templates groovy script?

I have a groovyScript in my Intellij IDEA live template, like this :
groovyScript("D:/test.groovy","", v1)
on my D:/test.groovy i have a code like this:
if ( v1 == 'abc') {
'abc'
}
Now I want to pass v1 variable into test.groovy ,can any one help me how can I do this?
For exemplification purposes I made a live template which is printing a comment with the current class and current method.
This is how my live template is defined:
And here is how I edited the variableResolvedWithGroovyScript variable:
The Expression for the given variable has the follwing value:
groovyScript("return \"// Current Class:\" + _1 + \". Current Method:\"+ _2 ", className(),methodName())
As you can see, in this case the _1(which acts like a variable in the groovy script) takes the value of the first parameter which is the class name, and the _2 takes the value of the
second parameter which is the method name. If another parameter is needed the _3 will be used in the groovy script to reference the given parameter.
The arguments to groovyScript macro are bound to script variables named _1, _2 etc. This is also described at groovyScript help at Edit Template Variables Dialog / Live Template Variables.
I found a solution.
I was needing to calculate a CRC32 of the qualified class name using live models
I used it like this:
groovyScript("
def crc = new java.util.zip.CRC32().with { update _1.bytes; value };
return Long.toHexString(crc);
", qualifiedClassName())
then the result is
Based on the documentation, your variables are available as _1, _2, etc. Please note that variables are passed without dollar signs (so only v1 instead of $v1$)
So your test script should look like
if ( _2 == 'abc') {
'abc'
}

scilab : index in variable name loop

i would like to read some images with scilab and i use the function imread like this
im01=imread('kodim01t.jpg');
im02=imread('kodim02t.jpg');
im03=imread('kodim03t.jpg');
im04=imread('kodim04t.jpg');
im05=imread('kodim05t.jpg');
im06=imread('kodim06t.jpg');
im07=imread('kodim07t.jpg');
im08=imread('kodim08t.jpg');
im09=imread('kodim09t.jpg');
im10=imread('kodim10t.jpg');
i would like to know if there is a way to do something like below in order to optimize the
for i = 1:5
im&i=imread('kodim0&i.jpg');
end
thanks in advance
I see two possible solutions using execstr or using some kind of list/matrix
Execstr
First create a string of the command to execute with msprintf and then execute this with execstr. Note that in the msprintf conversion the right amount of leading zeros are inserted by %0d format specifier descbribed here.
for i = 1:5
cmd=msprintf('im%d=imread(\'kodim%02d.jpg\');', i, i);
execstr(cmd);
end
List/Matrix
This is probably the more intuitive option using a indexable container such as list.
// This list could be generated using msprintf from example above
file_names_list = list("kodim01t.jpg", "kodim02t.jpg" ,"kodim03t.jpg");
// Create empty list to contain images
opened_images = list();
for i=1:length(file_names_list)
// Open image and insert it at end of list
opened_images($+1) = imread(file_names_list[i]);
end

Pass the value of a variable to a function in Python3

I have created a function that opens a file and reads the first line of it into a variable named 'farmer_id'. I would now like to use this 'farmer_id' variable in a second function in my script, and I'm not sure of the best way to do this. Global variables are allowed, so any solution is welcome.
I have read everything I can find on Stackoverflow on this topic, but I cannot find anything which works for my specific problem.
def get_id_from_file():
file = open('C:/Users/my.name/Documents/test.txt', 'r')
farmer_id = file.readline()
You can do like this
def any_func(former_id):
pass
def get_id_from_file():
file = open(r'C:/Users/my.name/Documents/test.txt', 'r')
farmer_id = file.readline()
return farmer_id
farmerid = get_id_from_file()
any_func(farmerid)

SSIS filename - file count

I'm currently creating a flat file export for one of our clients, i've managed to get the file in the format they want, i'm trying to get the easiest way of creating a dynamic file name. I've got the date in as a variable and the path ect but they want a count in the file name. For example
File name 1 : TDY_11-02-2013_{1}_T1.txt. The {} being the count. So next weeks file would be TDY_17-02-2013_{2}_T1.txt
I cant see an easy way of doing this!! any idea's??
EDIT:
on my first answer, I thought you meant count of values returned on a query. My bad!
two ways to achieve this, you could loop into the destination folder, select the last file by date, get its value and increase 1, which sound like a lot of trouble. Why not a simple log table on the DB with last execution date and ID and then you compose your file name base on the last row of this table?
where exactly is your problem?
you can make a dynamic file name using expressions:
the count, you can use a "row count" component inside your data flow to assign the result to a variable and use the variable on your expression:
Use Script task and get the number inside the curly braces of the file name and store it in a variable.
Create a variable(FileNo of type int) which stores the number for the file
Pseudo code
string name = string.Empty;
string loction = #"D:\";
/* Get the path from the connection manager like the code below
instead of hard coding like D: above
string flatFileConn =
(string(Dts.Connections["Yourfile"].AcquireConnection(null) as String);
*/
string pattern = string.Empty;
int number = 0;
string pattern = #"{([0-9])}"; // Not sure about the correct regular expression to retrieve the number inside braces
foreach (string s in Directory.GetFiles(loction,"*.txt"))
{
name = Path.GetFileNameWithoutExtension(s);
Match match = Regex.Match(name, pattern );
if (match.Success)
{
dts.Variables["User::FileNo"].Value = int.Parse(match.Value)+1;
}
}
Now once you get the value use it in your file expression in the connection manager
#[User::FilePath] +#[User::FileName]
+"_{"+ (DT_STR,10,1252) #[User::FileNo] + "}T1.txt"