unable to send a combination of keybord commands in watir - cucumber

I have a step definition:
Then (/^I send '(.?*)' keys$/) do |key|
$browser.send_keys key
end
I pass :shift,:tab in my feature file. This doesn't work for me.
But when I have a step definition
Then (/^I send keys$/) do
key =:shift,:tab
$browser.send_keys key
end
and hard code the value, it works fine. What might be the issue?

Problem
The problem is that when Cucumber gives you the key (in the first step definition), it is a string with value ':shift,:tab'. Watir just sees this as text and therefore types each of those characters (rather than interpreting the special keys).
In contrast, the second step definition the key is an array containing 2 symbols.
You need to take the string from the Cucumber step and manipulate it to be symbols.
Solution
Depending on the different sequence of keys you need to send, the following step definition might be sufficient:
Then (/^I send '(.?*)' keys$/) do |key|
key_sequence = key.split(',').map do |key|
if key[0] == ':'
key[1..-1].to_sym
else
key
end
end
$browser.send_keys key_sequence
end
This step will:
Take the string ':shift,:tab' (from the step)
Split the string on commas, which is assumed to separate the keys
If the key starts with a colon, assume it is a special character and convert it to a symbol.
If the key does not start with a colon, assume it is plain text and leave it as-is.
Send the mapped keys to the send_keys method.

Related

substitue string by index without using regular expressions

It should be very easy, but I am looking for an efficient way to perform it.
I know that I could split the string into two parts and insert the new value, but I have tried to substitute each line between the indexes 22-26 as follows:
line.replace(line[22:26],new_value)
The Problem
However, that function substitutes everything in the line that is similar to the pattern in line[22:26].
In the example below, I want to replace the marked number 1 with number 17:
Here are the results. Note the replacement of 1 with 17 in several places:
Thus I don't understand the behavior of replace command. Is there a simple explanation of what I'm doing wrong?
Why I don't want RE
The values between index 22-26 are not unified in form.
Note: I am using python 3.5 on Unix/Linux machines.
str.replace replaces 1 sub-string pattern with another everywhere in the string.
e.g.
'ab cd ab ab'.replace('ab', 'xy')
# produces output 'xy cd xy xy'
similarly,
mystr = 'ab cd ab ab'
mystr.replace(mystr[0:2], 'xy')
# also produces output 'xy cd xy xy'
what you could do instead, to replace just the characters in position 22-26
line = line[0:22] + new_value + line[26:]
Also, looking at your data, it seems to me to be a fixed-width text file. While my suggestion will work, a more robust way to process this data would be to read it & separate the different fields in the record first, before processing the data.
If you have access to the pandas library, it provides a useful function just for reading fixed-width files

Why does cookie-signature in nodejs/express compare signatures using sha1-hashing?

I was just looking into the implementation of the cryptograhic signing extension for express which allows creation of signed cookies.
The mac in the signing function is calculated as described here:
create an instance of SHA256
hash the data value
create a base64 encoded digest
remove trailing equal characters ('=')
The result is a concatenation of the original value and the calculated mac.
On verification of the signature the value is signed again. But then not the signatures are tested on equality, but the overall strings consisting of the original value and the appended mac are compared:
return sha1(mac) == sha1(val) ? str : false;
Here "mac" contains the original value concatenated with a freshly calculated mac, "val" contains the input string as passed to the verification method (consisting of the original value concatenated with a former mac) and "str" is the signed value itself.
See: https://github.com/tj/node-cookie-signature/blob/master/index.js
I would have expected that only the macs would be compared. But this is not the case. Why have the authors chosen this way of implementing the verification? What is the reason for this? And especially: Why don't they compare char by char but a hash of sha1?
The implementation's sign function returns the value concatenated with '.' and HMAC of the value converted to Base64 without the trailing '=' (if any).
The implementation's unsign function does the same with the value part of the given input (up to the '.') and checks if the whole input equals the output of the sign function.
And as to comparing using hash values I the authors were trying to fend off timing attack, whereby an attacker would observe the time it took to check for equality character by character and determine by minute changes between two tries at what character the check failed, and thereafter try to guess on character by character basis the MAC value for the arbitary value part. By comparing using sha1 digest code takes constant time depending only on the given whole input length.
More interesting side note is the removal of padding '=' from Base64 encoded MACs, I have no idea why would they do that as there is URL safe variant of Base64.

need guidance with basic function creation in MATLAB

I have to write a MATLAB function with the following description:
function counts = letterStatistics(filename, allowedChar, N)
This function is supposed to open a text file specified by filename and read its entire contents. The contents will be parsed such that any character that isn’t in allowedChar is removed. Finally it will return a count of all N-symbol combinations in the parsed text. This function should be stored in a file name “letterStatistics.m” and I made a list of some commands and things of how the function should be organized according to my professors' lecture notes:
Begin the function by setting the default value of N to 1 in case:
a. The user specifies a 0 or negative value of N.
b. The user doesn’t pass the argument N into the function, i.e., counts = letterStatistics(filename, allowedChar)
Using the fopen function, open the file filename for reading in text mode.
Using the function fscanf, read in all the contents of the opened file into a string variable.
I know there exists a MATLAB function to turn all letters in a string to lower case. Since my analysis will disregard case, I have to use this function on the string of text.
Parse this string variable as follows (use logical indexing or regular expressions – do not use for loops):
a. We want to remove all newline characters without this occurring:
e.g.
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
In my younger and more vulnerableyears my father gave me some advicethat I’ve been turning over in my mindever since.
Replace all newline characters (special character \n) with a single space: ' '.
b. We will treat hyphenated words as two separate words, hence do the same for hyphens '-'.
c. Remove any character that is not in allowedChar. Hint: use regexprep with an empty string '' as an argument for replace.
d. Any sequence of two or more blank spaces should be replaced by a single blank space.
Use the provided permsRep function, to create a matrix of all possible N-symbol combinations of the symbols in allowedChar.
Using the strfind function, count all the N-symbol combinations in the parsed text into an array counts. Do not loop through each character in your parsed text as you would in a C program.
Close the opened file using fclose.
HERE IS MY QUESTION: so as you can see i have made this list of what the function is, what it should do, and using which commands (fclose etc.). the trouble is that I'm aware that closing the file involves use of 'fclose' but other than that I'm not sure how to execute #8. Same goes for the whole function creation. I have a vague idea of how to create a function using what commands but I'm unable to produce the actual code.. how should I begin? Any guidance/hints would seriously be appreciated because I'm having programmers' block and am unable to start!
I think that you are new to matlab, so the documentation may be complicated. The root of the problem is the basic understanding of file I/O (input/output) I guess. So the thing is that when you open the file using fopen, matlab returns a pointer to that file, which is generally called a file ID. When you call fclose you want matlab to understand that you want to close that file. So what you have to do is to use fclose with the correct file ID.
fid = open('test.txt');
fprintf(fid,'This is a test.\n');
fclose(fid);
fid = 0; % Optional, this will make it clear that the file is not open,
% but it is not necessary since matlab will send a not open message anyway
Regarding the function creation the syntax is something like this:
function out = myFcn(x,y)
z = x*y;
fprintf('z=%.0f\n',z); % Print value of z in the command window
out = z>0;
This is a function that checks if two numbers are positive and returns true they are. If not it returns false. This may not be the best way to do this test, but it works as example I guess.
Please comment if this is not what you want to know.

Azure Table Storage RowKey restricted Character Patterns?

Are there restricted character patterns within Azure TableStorage RowKeys? I've not been able to find any documented via numerous searches. However, I'm getting behavior that implies such in some performance testing.
I've got some odd behavior with RowKeys consisting on random characters (the test driver does prevent the restricted characters (/ \ # ?) plus blocking single quotes from occurring in the RowKey). The result is I've got a RowKey that will insert fine into the table, but cannot be queried (the result is InvalidInput). For example:
RowKey: 9}5O0J=5Z,4,D,{!IKPE,~M]%54+9G0ZQ&G34!G+
Attempting to query by this RowKwy (equality) will result in an error (both within our app, using Azure Storage Explorer, and Cloud Storage Studio 2). I took a look at the request being sent via Fiddler:
GET /foo()?$filter=RowKey%20eq%20'9%7D5O0J=5Z,4,D,%7B!IKPE,~M%5D%54+9G0ZQ&G34!G+' HTTP/1.1
It appears the %54 in the RowKey is not escaped in the filter. Interestingly, I get similar behavior for batch requests to table storage with URIs in the batch XML that include this RowKey. I've also seen similar behavior for RowKeys with embedded double quotes, though I have not isolated that pattern yet.
Has anyone co me across this behavior? I can easily restrict additional characters from occurring in RowKeys, but would really like to know the 'rules'.
The following characters are not allowed in PartitionKey and RowKey fields:
The forward slash (/) character
The backslash (\) character
The number sign (#) character
The question mark (?) character
Further Reading: Azure Docs > Understanding the Table service data model
public static readonly Regex DisallowedCharsInTableKeys = new Regex(#"[\\\\#%+/?\u0000-\u001F\u007F-\u009F]");
Detection of Invalid Table Partition and Row Keys:
bool invalidKey = DisallowedCharsInTableKeys.IsMatch(tableKey);
Sanitizing the Invalid Partition or Row Key:
string sanitizedKey = DisallowedCharsInTableKeys.Replace(tableKey, disallowedCharReplacement);
At this stage you may also want to prefix the sanitized key (Partition Key or Row Key) with the hash of the original key to avoid false collisions of different invalid keys having the same sanitized value.
Do not use the string.GetHashCode() though since it may produce different hash code for the same string and shall not be used to identify uniqueness and shall not be persisted.
I use SHA256: https://msdn.microsoft.com/en-us/library/s02tk69a(v=vs.110).aspx
to create the byte array hash of the invalid key, convert the byte array to hex string and prefix the sanitized table key with that.
Also see related MSDN Documentation:
https://msdn.microsoft.com/en-us/library/azure/dd179338.aspx
Related Section from the link:
Characters Disallowed in Key Fields
The following characters are not allowed in values for the PartitionKey and RowKey properties:
The forward slash (/) character
The backslash (\) character
The number sign (#) character
The question mark (?) character
Control characters from U+0000 to U+001F, including:
The horizontal tab (\t) character
The linefeed (\n) character
The carriage return (\r) character
Control characters from U+007F to U+009F
Note that in addition to the mentioned chars in the MSDN article, I also added the % char to the pattern since I saw in a few places where people mention it being problematic. I guess some of this also depends on the language and the tech you are using to access the table storage.
If you detect additional problematic chars in your case, then you can add those to the regex pattern, nothing else needs to change.
I just found out (the hard way) that the '+' sign is allowed, but not possible to query in PartitionKey.
I found that in addition to the characters listed in Igorek's answer, these also can cause problems (e.g. inserts will fail):
|
[]
{}
<>
$^&
Tested with the Azure Node.js SDK.
I transform the key using this function:
private static string EncodeKey(string key)
{
return HttpUtility.UrlEncode(key);
}
This needs to be done for the insert and for the retrieve of course.

How can I pass a line of code as a string without replacing every quote with doublequotes? (VBScript in QTP)

I am attempting to create a VBScript function (within the context of QuickTest Pro 10) that is able to take in a line of code as a parameter, such as: JavaWindow("Export Control Notice").JavaButton("OK").Click
Problem is, when I try passing that line as a string, VBScript understandably chokes on the quotes. Here is the catch: I have many lines of code similar to the one above, so I would like to take the line of code and pass it as is. I don't want to go around doubling the quotes for these lines of code, let along for every new line that QTP records. (Find/Replace All can easily go out of control)
How can I pass the above line of code?
If turning it into a string is the way to go, how can I encode that line so VBscript doesn't choke on the quote marks?
Additionally, I haven't been able to find any way to change the delimiter to something other than quote marks to assign the line of code as a string. Finding a way to change the delimiter would probably solve this issue.
Alternately, I've also tried passing JavaWindow("Export Control Notice").JavaButton("OK") as an object into the function and that has worked. Unfortunately, there doesn't seem to be a way to turn that object back into a string in order to append ".Click" (or some other action stored as a string) back onto the end of it. Am I overlooking something?
Depending on how exactly you 'have' those lines of code (in your head, in a text document, ...) and whether you prefer to type or to program you can
put them into VBScript code using the proper escape (""):
Dim sCodeLine : sCodeLine = "JavaWindow(""Export Control Notice"").JavaButton(""OK"").Click"
WScript.Echo sCodeLine
JavaWindow("Export Control Notice").JavaButton("OK").Click
put them into VBScript code using a delimiter of your choice and Replace():
Dim sCodeLine : sCodeLine = "JavaWindow('Export Control Notice').JavaButton('OK').Click"
WScript.Echo Replace( sCodeLine, "'", """" )
JavaWindow("Export Control Notice").JavaButton("OK").Click
put them in an external file (.txt, .xls, .xml, ...) (resp. use the given document); load and parse the file into a suitable data structure (array, dictionary, ...). Use that collection to feed your function.
The way we eventually passed in QTP objects & actions into the function was to keep the QTP object as an object, then pass in the action as a string that a Select Case would sort through. We don't have that many actions, so a Select Case works well in this situation.
For example, here is the code for performing an action:
Before:
If existCheck JavaWindow("Certificate Management").JavaWindow("Import Key Store").JavaEdit("* Certificate Name").Exist(2) Then
existCheck JavaWindow("Certificate Management").JavaWindow("Import Key Store").JavaEdit("* Certificate Name").Set "Personal"
Reporter.ReportEvent micPass,"OK button clicked on Export Control Notice","Ok"
Else Reporter.ReportEvent micFail,"Export Control Notice is not found","Step Fail" End If
After:
existCheck JavaWindow("Certificate Management").JavaWindow("Import Key Store").JavaEdit("* Certificate Name"), "Set", "Personal", Null, 2, Null, Null
We are now have the action occupying only one line, which helps immensely for code readability, but also allows us to improve the error-checking / reporting function all in one place.
Here is the some of the error-checking function, minus the reporting portion.
The Function:
'existCheck provides error-checking by determining if the object exists right before we interact with it.
'Afterwards, it reports on the results. This function has parameters for:
'object: an object (such as a button or field)
'strAction: the action to perform on that object (such as "Click")
'strParameter1 (and two): the parameter that is passed when the action is performed
'intWait: the time in seconds to wait for the object to appear
'strPass: the string to report for a success. If not string is provided, a default one will be used.
'strFail: the string to report for a failure. If not string is provided, a default one will be used.
Function existCheck(object, strAction, strParameter1, strParameter2, intWait, strPass, strFail)
'Before we can perform any action, we must see if the object exists. This determines much of what we do next.
If object.Exist(intWait) Then
'Chooses the action to be performed on the object (and then performs it)
Select Case strAction
Case "Click"
object.Click
Case "Select"
object.Select strParameter1
Case "Press"
object.Press strParameter1
Case "Set"
object.Set strParameter1
Case "SetSecure"
object.SetSecure strParameter1
Case "Type"
object.Type strParameter1
Case "SelectCell"
object.SelectCell strParameter1, strParameter2
End Select
... and so on.

Resources