exctract substring from a large string under certain conditions in painless - elasticsearch

In painless I would like to create a script which reads a keyword field called 'objldn' and extracts only five consecutive characters sometimes present in a precise position. Infact, in the keyword field 'objldn' there are a large variety of long strings among which there are some of them with a third underscore. After the third underscore, if it is present, I can fetch the consecutive 5 chars.
Whith the following lines of code I implement what I want:
def LU = doc['objldn'].value.splitOnToken('_');
return LU[3].substring(0, 5);
But the system returnes an error message "out of bounds":
Request error: array_index_out_of_bounds_exception, Index 3 out of
bounds for length 3 in "def LU =
doc['objldn'].value.splitOnToken('_'); ..." (Painless script)
error executing runtime field or scripted field on index pattern
return LU[3].substring(0, 5);
^---- HERE
may be it is due to the fact that many strings do not have the third underscore or do not even have one and therefore I need to implement firstly a IF statement which evaluates if a third underscore is in the string and only if it is present it proceeds to execute splitOnToken()... but I am not able to do it correctly. Can you help me to add the IF statement in the script please?

Why not simply checking the length of the LU array?
def LU = doc['objldn'].value.splitOnToken('_');
return LU.length >= 4 ? LU[3].substring(0, 5) : null;

Related

If results are not >= "Number" then show blank

New to building Crystal Reports and SQL.
I'm trying to write a script to where if results is >= 12.1 then show result else show no results.
Same goes for the <=9.9.
Here is what I have so far:
if {Test.Name} = "xyz" and {TestResults.numresult}>= 12.1 then {TestResults.numresult} else "";
Below is an image showing the same results across the board. I just want the results to show when its <=9.9 or >=12.1.
Hope this make sense.
Your statement returns a number from one branch and a string from the other. It must return the same data type.
One option is to use a True/False expression in a Suppress expression.
Another option is to return a zero in the other branch and use number formatting to suppress if zero (it's a built-in option for numbers).
Another option is to modify your expression so it returns a string from both branches. For example:
if {Test.Name} = "xyz" and {TestResults.numresult}>= 12.1 then ToText({TestResults.numresult}, 1, ",") else "";
The 1 argument requests 1 decimal point. The "," argument requests a comma as thousands separator. You can adjust those to match your number formatting requirements.

How to write HQL expression in Hadoop to verify format of alphanumeric field in specific format such as X9999

How do I write HQL to determine if results from a field have 1st character as alpha and the following four are numeric. (i.e. - the format of the field is 'F5555', so I need to verify all the results returned from the query for this field are following the correct format.
You can try this:
select REGEXP_EXTRACT( 'd55555' , '^[A-Za-z ]?[0-9]{5}$', 0);
Now, in order to understand, please read this and see the next comments:
^ means the beginning of the string(in this mode we mark the beginning);
[A-Za-z] - means any letter: upper or lower case;
? - means that we want only 1 occurrence of the previous character class;
[0-9] - any digit from 0 to 9;
{5} - means that the previous character class ([0-9]) must appear 5 times exactly (no more, no less);
$ - end of the string;
Hope that you understood.

In TI-BASIC, how do I add a variable in the middle of a String?

I am wondering how to make something where if X=5 and Y=2, then have it output something like
Hello 2 World 5.
In Java I would do
String a = "Hello " + Y + " World " + X;
System.out.println(a);
So how would I do that in TI-BASIC?
You have two issues to work out, concatenating strings and converting integers to a string representation.
String concatenation is very straightforward and utilizes the + operator. In your example:
"Hello " + "World"
Will yield the string "Hello World'.
Converting numbers to strings is not as easy in TI-BASIC, but a method for doing so compatible with the TI-83+/84+ series is available here. The following code and explanation are quoted from the linked page:
:"?
:For(X,1,1+log(N
:sub("0123456789",ipart(10fpart(N10^(-X)))+1,1)+Ans
:End
:sub(Ans,1,length(Ans)-1?Str1
With our number stored in N, we loop through each digit of N and store
the numeric character to our string that is at the matching position
in our substring. You access the individual digit in the number by
using iPart(10fPart(A/10^(X, and then locate where it is in the string
"0123456789". The reason you need to add 1 is so that it works with
the 0 digit.
In order to construct a string with all of the digits of the number, we first create a dummy string. This is what the "? is used
for. Each time through the For( loop, we concatenate the string from
before (which is still stored in the Ans variable) to the next numeric
character that is found in N. Using Ans allows us to not have to use
another string variable, since Ans can act like a string and it gets
updated accordingly, and Ans is also faster than a string variable.
By the time we are done with the For( loop, all of our numeric characters are put together in Ans. However, because we stored a dummy
character to the string initially, we now need to remove it, which we
do by getting the substring from the first character to the second to
last character of the string. Finally, we store the string to a more
permanent variable (in this case, Str1) for future use.
Once converted to a string, you can simply use the + operator to concatenate your string literals with the converted number strings.
You should also take a look at a similar Stack Overflow question which addresses a similar issue.
For this issue you can use the toString( function which was introduced in version 5.2.0. This function translates a number to a string which you can use to display numbers and strings together easily. It would end up like this:
Disp "Hello "+toString(Y)+" World "+toString(X)
If you know the length of "Hello" and "World," then you can simply use Output() because Disp creates a new line after every statement.

Django alpha numeric validation in form fields

I want to perform a field validation,but the conditions are
1)The field should have 10 character.
2)off these 1st 5 character should be alphabets and next 5 character should be numeric digits
I performed validation for maximum length check,but rest of the thing how to perform.Is that can be done on a single "if" condition.
I am searching for the logic in google for performing that,but not got any idea.Can any one help me to perform the same.
forms.py for length check
def clean_bookref(self):
cd=self.cleaned_data
bookref=cd.get('bookref')
if len(bookref)<10 and re.match(r'[A-z0-9]+', bookref):
raise forms.ValidationError("Should be 10 digits")
return bookref
I am using this code to do but it is not working.
Thanks
Perhaps you could use something like his:
def clean_bookref(self):
cd=self.cleaned_data
bookref=cd.get('bookref')
if not re.match(r'^[A-Za-z]{5}[0-9]{5}$',bookref) :
raise forms.ValidationError("Should be of the form abcde12345")
return bookref

Double "gsub" Variable

Is it possible to use variables in both fields of the gsub method ?
I'm trying to get this piece of code work :
$I = 0
def random_image
$I.to_s
random = rand(1).to_s
logo = File.read('logo-standart.txt')
logo_aleatoire = logo.gsub(/#{$I}/, random)
File.open('logo-standart.txt', "w") {|file| File.puts logo_aleatoire}
$I.to_i
$I += 1
end
Thanks in advance !
filecontents = File.read('logo-standart.txt')
filecontents.gsub!(/\d+/){rand(100)}
File.open("logo-standart.txt","w"){|f| f << filecontents }
The magic line is the second line.
The gsub! function modifies the string in-place, unlike the gsub function, which would return a new string and leave the first string unmodified.
The single parameter that I passed to gsub! is the pattern to match. Here, the goal is to match any string of one or more digits -- this is the number that you're going to replace. There's no need to loop through all of the possible numbers running gsub on each one. You can even match numbers as high as a googol (or higher) without your program taking longer and longer to run.
The block that gsub! takes is evaluated each time the pattern matches to programmatically generate a replacement number. So each time, you get a different random number. This is different from the more usual form of gsub! that takes two parameters -- there the parameter is evaluated once before any pattern matching occurs, and all matches are replaced by the same string.
Note that the way this is structured, you get a new random number for each match. So if the number 307 appears twice, it turns into two different random numbers.
If you wanted to map 307 to the same random number each time, you could do the following:
filecontents = File.read('logo-standart.txt')
randomnumbers = Hash.new{|h,k| h[k]=rand(100)}
filecontents.gsub!(/\d+/){|match| randomnumbers[match]}
File.open("logo-standart.txt","w"){|f| f << filecontents }
Here, randomnumbers is a hash that lets you look up the numbers and find what random number they correspond to. The block passed when constructing the hash tells the hash what to do when it finds a number that it hasn't seen before -- in this case, generate a new random number, and remember what that random number the mapping. So gsub!'s block just asks the hash to map numbers for it, and randomnumbers takes care of generating a new random number when you encounter a new number from the original file.

Resources