Using Karate, I need to extract the url from tag (href). I have tried this using Javascript directly in browser:
document.querySelector('a[rel="noopener"]').href
It works in browser fine, I receive whole url address ("https://XXXXXXXX"). Then I wanted to place it to Karate using:
* def emailLink =
"""
function(){
var link = document.querySelector('a[rel="noopener"]').href;
return link;
}
"""
* print emailLink()
But it does not work. The variable = "". I need to receive the href value.
Have you any Idea how to solve this?
Thank you!
The function you are writing will not work, and please read this to understand why: https://github.com/intuit/karate/tree/master/karate-core#karate-vs-the-browser
So make this change (and also note how Karate does document.querySelector() for you):
* def linkElement = locate('a[rel="noopener"]')
* def linkValue = linkElement.attribute('href')
Note that for the second line this should also work:
* def linkValue = linkElement.script('_.href')
Or even this:
* def linkValue = linkElement.property('href')
Start getting used to the Element abstraction in Karate. It can be very useful: https://github.com/intuit/karate/tree/master/karate-core#chaining
I have just been reading https://intuit.github.io/karate/ and for just JavaScript you don't need the multi-line doc string.
* def greeter = function(title, name) { return 'hello ' + title + ' ' + name }
Try without the """ on either side of the function """.
Related
I want iterate over a list of string, output the string as plain text in jupyter lab then interactively highlight a substring to get easily the start index of the substring and the length. The goal is to do a quick annotation of text and get the coordinates of the substring.
Is it easy or even possible to do something like this with jupyter notebook (lab)? If then How?
I had a look at ipywidgets but couldn't find something for this use case.
Here's an example with the RangeSlider:
import ipywidgets
input_string = 'averylongstring'
widg = ipywidgets.IntRangeSlider(
value = [0, len(input_string)],
min=0, max=len(input_string)
)
output_widg = ipywidgets.Text()
display(widg)
display(output_widg)
def chomp_string(widg):
start,end = tuple(widg['new'])
output_widg.value = input_string[start: end]
widg.observe(chomp_string, names='value')
You can implement this using jp_proxy_widgets. See the following screenshot:
Note that there are warnings about compatibility for selection protocols -- I only tested this on Chrome on a Mac. Also I don't know why the indices are off by one
(select_callback(startOffset+1, endOffset+1);)
Please see https://github.com/AaronWatters/jp_proxy_widget for more information
Edit: Here is the pastable text as requested:
import jp_proxy_widget
select_widget = jp_proxy_widget.JSProxyWidget()
txt = """
Never gonna give you up.
Never gonna let you down.
Never gonna run around and
desert you.
"""
selected_text = None
def select_callback(startOffset, endOffset):
global selected_text
selected_text = txt[startOffset: endOffset]
print ("Selected", startOffset, endOffset, repr(selected_text))
select_widget.js_init("""
// (Javascript) Add a text area.
element.empty()
$("<h3>please select text:</h3>").appendTo(element);
var textarea = $('<textarea cols="50" rows="5">' + txt + "</textarea>").appendTo(element);
// Attach a select handler that calls back to select_callback.
var select_handler = function(event) {;
var target = event.target;
var startOffset = target.selectionStart;
var endOffset = target.selectionEnd;
select_callback(startOffset+1, endOffset+1);
};
textarea[0].addEventListener('select', select_handler);
""", txt=txt, select_callback=select_callback)
# display the widget
select_widget.debugging_display()
I'm trying to replicate what was done in this answer for java selenium in RSelenium: https://stackoverflow.com/a/27611777/7837376
I'd love to be able to do something like this:
#replicating simple RSelenium process getting all //a elements
library(RSelenium)
#start remDr etc. etc.
all_a <- remDr$findElements(using='xpath','//a')
selected_a <- all_a[[10]]
Ideally then I could generate the xpath of the selected_a element using the made up function below:
#desired function
getElementXPATH(selected_a)
I understand that quite a few different XPATH's could be specified for the same element, I'm just looking for a unique xpath identifier for the element, so any unique xpath to the element will suffice!
Thanks!
Personally, I am not a big fan absolute xpath. However, you can get the absolute xpath using javascript rather having the function in your language, which will ran faster and it's easy to port.
Here is the javascript.
// this function will return the absolute xpath of any given element
jsFunction = """window.getAbsoluteXpath =function(el){
// initialize the variables
aPath ="";
// iterate until the tag name is 'HTML'
while (el.tagName!='HTML'){
// get parent node
pEle=el.parentNode;
// check if there are more than 1 nodes with the same tagname under the parent
if(pEle.querySelectorAll(el.tagName).length>1){
//now findout the index of the current child
cIndex = 0;
pEle.querySelectorAll(el.tagName).forEach(function(cEle){
cIndex= cIndex+1;
// check if iterating ChildNode is equal to current ChildNode
if(cEle === el){
// set the aPath using index
aPath = el.tagName + "[" + cIndex + "]" + "/" +aPath;
}
})
}else{
// simply add the tagName when there is only one child with the tag name
aPath = el.tagName + "/" +aPath;
}
// set parent node as current element
el=el.parentNode;
}
// append HTML to the absolute xpath generated
return "//HTML/"+aPath.substring(0,aPath.length-1);
};"""
Now you can call this method in your javascript and pass element that you are interested in getting the absolute xpath.
Let's try to get the absolute xpath of in stackoverflow.
Note: Did not tested the below code logic due to lack of environment on my machine.
# run the javascript in browser so that you can call the function anytime in your script
remDr %>% executeScript(jsFunction, args = list())
# get stackoverflow `Achievements` link element
webElem <- remDr %>% findElement("css", "a.-link.js-achievements-button")
# # get the absolute xpath of Stackoverflow `Achievements`
remDr %>% executeScript("return getAbsoluteXpath(arguments[0])", args = list(webElem))
Screenshot: Ran the javascript in chrome browser console for evidence
Please try the below logic
function absolutePath(element) {
if (element.tagName.toLowerCase() == 'html')
return '/html[1]';
if (element === document.body)
return '/html[1]/body[1]';
var ix = 0;
var siblings = element.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
var sibling = siblings[i];
if (sibling === element)
return absolutePath(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
if (sibling.nodeType === 1 && sibling.tagName.toLowerCase() === element.tagName.toLowerCase())
ix++;
}}
I did try the solution provided by supputuri, but it doesnt work on all cases.
Example: Try the function provided by #suppututri on https://www.amazon.in/ , and try to find the absolute xpath for
var element=document.querySelector('#nav-xshop > a:nth-child(2)');
getAbsoluteXpath(element);
The incorrect xpath shown in the console would be: "//HTML/BODY/DIV[1]/HEADER/DIV[1]/DIV[68]/DIV[9]/DIV[1]/DIV/A[1]"
I'm pretty new to Rails and trying some basic stuff like conditional classes.
On the 'show' view I have an element that changes styling depending on the stock availability, but also the text changes accordingly.
People keep saying the controller should be as small as possible, but placing this conditional in the view also feels dirty. Is this really the best way?
Current controller:
def show
#tyre = Tyres::Tyre.find_by_id(params[:id])
if #tyre.in_stock
#availability = I18n.t("products.filter.other.in_stock")
#availability_class = 'i-check-circle color--success'
else
#availability = I18n.t("products.filter.other.not_in_stock")
#availability_class = 'i-cross-circle color--important'
end
end
Edit:
Controller:
def show
#tyre = Tyres::Tyre.find_by_id(params[:id])
if #tyre.in_stock
#availability_append = ".in_stock"
else
#availability_append = ".not_in_stock"
end
#availability = I18n.t("products.filter.other#{#availability_append}")
end
View:
.xs-12.description__status
%i{class: (#tyre.in_stock? ? 'i-check-circle color--success' : 'i-cross-circle color--important')}
= #availability
You can clean your controller tyres_controller.rb (i suppose) method,
def show
#tyre = Tyre.find(params[:id]) # I believe you have a model named 'tyre'
end
Then, there will be a file named tyres_helper.rb in your myproject/app/helpers/. Put the following code there,
def tyre_availability(tyre) # it'll return an array with two values, first one is class name, second one is localized value
if tyre.in_stock
return 'i-check-circle color--success', I18n.t("products.filter.other.in_stock")
else
return 'i-cross-circle color--important', I18n.t("products.filter.other.not_in_stock")
end
end
and, in the view you can use,
.xs-12.description__status
%i{:class => tyre_availability(#tyre)[0]}
= tyre_availability(#tyre)[1]
Can any one help me to get full category path from a given keyword. I am giving one example as below,
Example:
Category 1----> Keyword 1 -----> Keyword 11,
say from metadata i got the value "Keyword 11", but i need whole path i.e. /Category 1/ Keyword 1/Keyword 11.
Can anyone help me how to achieve this in Template Building Block using c#.
Maybe you can try and play with one of the following:
keyword.ParentKeywords recursively to create the path you are looking for.
OrganizationalItem oi = keyword.OrganizationalItem; // to get all the organizational items
keyword.OwningRepository
Hope that helps!
Below code should help you to get the path.
bool isRecursive = false;
KeywordField kwdField = (KeywordField)metaFields["kwdField"];
Keyword curKwd = new Keyword(kwdField.Value.Id, engine.GetSession());
string kwdPath = curKwd.Title;
while (!isRecursive) {
if (curKwd.ParentKeywords.Count > 0){
foreach (Keyword kwd in curKwd.ParentKeywords) {
kwdPath = kwd.Title + "/" + kwdPath;
}
curKwd = curKwd.ParentKeywords[0];
} else {
isRecursive = true;
}
}
kwdPath = curKwd.OrganizationalItem.Title + "/" + kwdPath;
I want to know the contents of a Map while debugging a c++ program.
I am using command line dbx.
I have pointer to the map.
Is there a way in which i can get the data printed.
--
Edit:
p *dataMap will give me this::
p *dataMap
*dataMap = {
__t = {
__buffer_size = 32U
__buffer_list = {
__data_ = 0x3ba2b8
}
__free_list = (nil)
__next_avail = 0x474660
__last = 0x474840
__header = 0x3b97b8
__node_count = 76U
__insert_always = false
__key_compare = {
/* try using "print -r" to see any inherited members */
}
}
}
Thanks
Alok Kr.
you need to write a ksh function to pretty print map, here is an example :
put following line in .dbxrc
source /ksh_STL_map
in dbx, use ppp to call ksh function that define in ksh_STL_map:
(dbx) ppp k
k = 2 elems {343, 0x301f8; 565, 0x30208}
I tried to post content of ksh_STL_map here, but this editor format will mess up the content, it's better that you post your email, then I can send ksh_STL_map directly to you.