Rails Ransack, initialize from front end as an array - reactjs

In the React front end, the ransack parameter is initialized like so:
const statusFilter = 'ransack[status_in]=incomplete';
In the backend, I've got
#params["ransack"]&.each do |filter, value|
so that the first line produces
filter = "status_in"
value = "incomplete"
Everywhere else in the app after initializing, the status_in parameter is used as an array, so that multiple statuses can be selected. So I would like to always treat this parameter as an array, not a string, if possible.
My desired output:
value = ["incomplete"]
I've tried
const statusFilter = "ransack[status_in]=['incomplete']";
But that results in
value = "['incomplete']"
I could probably just check whether the type is a string on the first usage, and then convert it to an array. Something like:
value = [value] if value.class == String
But it seems like there should be a way to accomplish this by slightly changing the front so that I don't need to add another line in the back.

Related

How to store array values in an environment variable in Postman

I am using a postman to automate apis.
Now I am using following request , lets say :-
{
"customerId": "{{currentClientId}}"
}
Where clientid is a dynamic variable whose value is substituted dynamically as 1 , 2, 3,4 so on..
I call this request multiple times using setNextRequest call in this eg lets say 10.This is being done using a counter variable. I am initialising the counter in my previous request to 0 and using for loop with value as counter as 10 calling the request 10 times.There is no response in body just successful http code 204.
I want to store all these clientids coming in request into an environment Client array variable so I wrote a following pre-request script:-
counter = pm.environment.get("counter");
ClientArray = pm.environment.get("ClientArray");
ClientArray.push(pm.environment.get("currentClientId"));
pm.environment.set("ClientArray",ClientArray);
In Test Script, wrote following code :-
counter = pm.environment.get("counter");
if(counter<=10) {
console.log("hi");
postman.setNextRequest("Request");
counter++;
pm.environment.set("counter",counter);
console.log("Counter",counter);
}
The above scipts is throwing
TypeError | ClientArray.push is not a function.
Could someone please advice how to achieve this.
When you retrieve a value from an environment variable like you're doing:
ClientArray = pm.environment.get("ClientArray");
You're not getting an array, you're getting a string which is why you're getting that error. You need to treat the variable like a string, append the currentClientId much like you do for the counter. Something like:
var currentClientIds = pm.environment.get("ClientArray");
currentClientIds = currentClientIds + "," + currentClientId
When you're done appending i.e. out of your loop simply take the string and convert it to an array:
var currentClientIds = pm.environment.get("ClientArray");
var idsArr = curentClientIds.split(',');

Ordering when using scala.collection.Searching

I have an Array of [Long, Q] and would like to make a binary search on it. I tried below :
import scala.collection.Searching._
class Q (val b:Double, val a:Double)
val myArray = Array(5L -> new Q(1,2), 6L-> new Q(6,9), 7L-> new Q(7,6))
val i = myArray.search(6L).insertionPoint
but had this error
No implicit Ordering defined for Any
Unspecified value parameter ord.
I understand that I need to specify an odering rule for this collection Array[(Long,Q)] but can't figure this out myself.
Please help
Signature of search is search[B >: A](elem: B)(implicit ord: Ordering[B]). You've got an array of type [Long, Q]. So in order for the compiler to infer Ordering correctly, you'd have to invoke search like that:
myArray.search(6L-> q/*Q(6,9)*/)(Ordering.by(_._1)) //ordering by the first value in a tuple.
and what you're doing is: myArray.search(6L). If I understand correctly what you're trying to do, it's probably to find both value and position in the array.
You could solve it by using two separate data structures:
keys could be stored in the array, like this:
val myArray = Array(5L, 6L, 7L).toList
myArray.search(6L).insertionPoint
and if you'd need values, you could use map which would work as a dictionary:
val dictionary = Map(
5L -> new Q(1,2),
6L-> new Q(6,9),
7L-> new Q(7,6)
)
EDIT:
Actually, I noticed something like that would work:
val dummy = new Q(0,0) //any instance of Q
myArray.search(6L-> dummy)(Ordering.by(_._1)).insertionPoint //1
It works since for lookup of the insertion point Ordering is used and no equality test is performed.

Best way to find needed element in array of objects

I have array of objects of my class. My class have variable for name that is unique for every object created. Now, I want to find, say, object in array that has a name "test". I wanted to try something like creating second array with just names as elements and when I create new object in my first array to create object in second array so that they share index number. Something like this:
arrayOfObjects.push(new obj("test"));
arrayOfNames.push("test");
function findIndexNumberOf(name){
for(var i = 0; i < arrayOfNames.length; i++){
if(arrayOfNames[i] === name)
return i;
}
}
But I think that this is pretty robust solution so I'm wondering is there better/smarter/faster way of doing this.
If you want to find the index of an item, it's generally the easiest to use indexOf:
const haystack = ["this", "is", "a", "test"];
const needle = "this";
const result = haystack.indexOf(needle);
However, this will work with primitive types. Assuming you have an array of objects, comparing them will require a different approach. Here are some one-liners:
const haystack = [new String("this"), new String("is"), new String("a"), new String("test")];
const needle = "test";
const result1 = haystack.indexOf(haystack.filter(item => item == needle)[0]);
const result2 = haystack.indexOf(haystack.filter(item => item.toString() === needle.toString())[0]);
const result3 = haystack.map(item => item.toString()).indexOf(needle.toString());
const result4 = haystack.indexOf(haystack.find(item => item.toString() === needle.toString()));
result1 filters the haystack using the == operator, thus ignoring the fact that the compared values are actually different types. The first element of the filtered array is then fed to indexOf. This will allow you to use a primitive string as the needle and search through a haystack of objects.
result2 uses the same approach, but casts both compared values to a primitive string, making sure they're both of the same type. This will allow you to mix and match primitives and String objects liberally, both in the haystack and needle.
result3 maps all haystack values to primitive strings and then uses indexOf on that new array of primitives. I also added toString to the needle to ensure it's also a primitive. This works similar to your approach, but the mapping is run every time you search for a needle. This is probably suboptimal.
result4 uses Array.prototype.find to locate the target object on the haystack and then feeds the result to indexOf. This might be the fastest, but I have no empirical data to back this up.
Now, in case you wanted to find the actual item, not just its index, you're best off using Array.prototype.find:
const result = haystack.find(item => item == needle);
or, in case both are String objects:
const result = haystack.find(item => item.toString() === needle.toString());
You can use the find method of Arrays object:
const myObject = arr.find(o => o.name === 'the_name_you_search');

Scala Converting Each Array Element to String and Splitting

I have an array loaded in, and been playing around in the REPL but can't seem to get this to work.
My array looks like this:
record_id|string|FALSE|1|
offer_id|decimal|FALSE|1|1,1
decision_id|decimal|FALSE|1|1,1
offer_type_cd|integer|FALSE|1|1,1
promo_id|decimal|FALSE|1|1,1
pymt_method_type_cd|decimal|FALSE|1|1,1
cs_result_id|decimal|FALSE|1|1,1
cs_result_usage_type_cd|decimal|FALSE|1|1,1
rate_index_type_cd|decimal|FALSE|1|1,1
sub_product_id|decimal|FALSE|1|1,1
campaign_id|decimal|FALSE|1|1,1
When I run my command:
for(i <- 0 until schema.length){
val convert = schema(i).toString;
convert.split('|').drop(2);
println(convert);
}
It won't drop anything. It also is not splitting it on the |
Strings are immutable, and so split and drop don't mutate the string - they return a new one.
You need to capture the result in a new val
val split = convert.split('|').drop(2);
println(split.mkString(" "));
Consider also defining a lambda function for mapping each item in the array, where intermediate results are passed on with the function,
val res = schema.map(s => s.toString.split('|').drop(2))

get_by_id() not returning values

I am writing an application that shows the user a number of elements, where he has to select a few of them to process. When he does so, the application queries the DB for the rest of the data on these elements, and stacks them with their full data on the next page.
I made an HTML form loop with a checkbox next to each element, and then in Python I check for this checkbox's value to get the data.
Even when I'm just trying to query the data, ndb doesn't return anything.
pitemkeys are the ids for the elements to be queried. inpochecks is the checkbox variable.
preqitems is the dict to save the items after getting the data.
The next page queries nothing and is blank.
The comments are my original intended code, which produced lots of errors because of not querying anything.
request_code = self.request.get_all('rcode')
pitemkeys = self.request.get_all('pitemkey')
inpochecks = self.request.get_all('inpo')
preqitems = {}
#idx = 0
#for ix, pitemkey in enumerate(pitemkeys):
# if inpochecks[ix] == 'on':
# preqitems[idx] = Preqitems.get_by_id(pitemkey)
# preqitems[idx].rcode = request_code[ix]
# idx += 1
for ix, pitemkey in enumerate(pitemkeys):
preqitems[ix] = Preqitems.get_by_id(pitemkey)
#preqitems[ix].rcode = request_code[ix]
Update: When trying
preqitems = ndb.get_multi([ndb.Key(Preqitems, k) for k in pitemkeys])
preqitems returns a list full of None values, as if the db couldn't find data for these keys.. I checked the keys and for some reason they are in unicode format, could that be the reason? They look like so.
[u'T-SQ-00301-0002-0001', u'U-T-MT-00334-0007-0002', u'U-T-MT-00334-0008-0001']
Probably you need to do: int(pitemkey) or str(pitemkey), depending if you are using integer or string id

Resources