How chrome.usb.bulkTransfer read from DigitalPersona fingerprint reader? - usb

I tried to read fingerprint from the DigitalPersona fingerprint reader.
Followed the api app_usb#bulk_transfers, I wrote the code:
//ignore the findDevice() part
var transferInfo = {
"direction": "in",
"endpoint": 3, //don't know where to find device protocol, 3 is a random number.
"length": 318
}
chrome.usb.bulkTransfer(connectionHandle, transferInfo, function(event){
console.log("got " + event.data.byteLength + " bytes");
});
but my result is "got 0 bytes". Why?

To get the correct endpoint, you should call the chrome.usb.getConfiguration function.
The result will be an object with a property called interfaces.
If you enumerate the interfaces found, you'll find for each one a property called endpoints, which enumerates the available ones.
Choose the endpoint according to the communication channel you want:
in / out
bulk / interrupt / ...
Then, fetch its address property to populate the GenericTransferInfo endpoint attribute for the bulkTransfer function call.
var transferInfo = {
"direction": "in",
"endpoint": 132, //value of "address" for the bulkTransfer/in endpoint
"length": 318
}

Related

set pagesize limit for Getrequest using Java in Rally rest API

THe question i have is i am trying to get all the userstories related to a release, i created a query request for type release and got the ref to workproduct.
so i got something like this from the query response "https://rally1.rallydev.com/slm/webservice/v2.0/Release/12345678/WorkProducts"
Now I am use this in my GET REQUEST to get all the user stories related to the Release.
The response is giving only 20 user stories since the default page size is 20.
Is there a way to increase the page size for get request.
the code is something like this :
QueryRequest iterationRequest = new QueryRequest("release");
iterationRequest.setFetch(new Fetch("Name", "Workspace", "WorkProducts","Feature"));
iterationRequest.setWorkspace("/workspace/12345678");
iterationRequest.setProject("/project/4567890");
iterationRequest.setPageSize(200);
iterationRequest.setQueryFilter(new QueryFilter("Name", "=", Release));
QueryResponse iterationQueryResponse = restApi.query(iterationRequest);
JsonArray iterationQueryResults = iterationQueryResponse.getResults();
JsonElement iterationQueryElement = iterationQueryResults.get(0);
JsonObject iterationQueryObject = iterationQueryElement.getAsJsonObject();
JsonObject workprodobj = iterationQueryObject.get("WorkProducts").getAsJsonObject();
String workprodref = workprodobj.get("_ref").getAsString();
System.out.println("workprodref :" + workprodref);
GetRequest getRequest = new GetRequest(workprodref);
getRequest.setFetch(new Fetch("FormattedID"));
GetResponse getResponse = restApi.get(getRequest);
The response output is like this
{"QueryResult": {"_rallyAPIMajor": "2", "_rallyAPIMinor": "0", "Errors": [], "TotalResultCount": 120, "StartIndex": 1, "PageSize": 20,
"Results": [{"_rallyAPIMajor": "2","_rallyAPIMinor": "0","_ref": "https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement/123456789",
"_refObjectUUID": "xxxxxx",
"_objectVersion": "1",
"_refObjectName": "obj name removed masked",
"FormattedID": "US123456",
"DirectChildrenCount": 0,
} .....
Can we change the page size from 20 to 200 for a getrequest??
GetRequest extends Request which has method addParam(String, String) which can be used to pass get parameters into the encoded URL, such as setting page size.
getRequest.addParam("pagesize", "200")
ref: https://github.com/RallyTools/RallyRestToolkitForJava/blob/542afa16ea44c9c64cebb0299500dcbbb50b6d7d/src/main/java/com/rallydev/rest/request/Request.java#L54

Is there any way to keep the session open after alexa timer api goes off?

I would like to know if there are any possible ways or tricks where we can leave the session open for the user's input after the timer goes off because the timer API doc doesn't cover it.
timer_request_1 = {
"duration": "PT15S",
"timerLabel": "Change name",
"creationBehavior": {
"displayExperience": {
"visibility": "VISIBLE"
}
},
"triggeringBehavior": {
"operation": {
"type": "ANNOUNCE",
"textToAnnounce": [
{
"locale": "en-US",
"text": "Would you like to proceed with the x task?"
}
]
},
"notificationConfig": {
"playAudible": False
}
}
}
REQUIRED_PERMISSIONS = ["alexa::alerts:timers:skill:readwrite"]
class TimerIntentHandler(AbstractRequestHandler):
def can_handle(self, handler_input):
return ask_utils.is_intent_name("TimerIntent")(handler_input)
def handle(self, handler_input):
permissions = handler_input.request_envelope.context.system.user.permissions
if not (permissions and permissions.consent_token):
return (
handler_input.response_builder
.speak("Please give permissions to set timers using the alexa app.")
.set_card(
AskForPermissionsConsentCard(permissions=REQUIRED_PERMISSIONS)
)
.response
)
timer_service = handler_input.service_client_factory.get_timer_management_service()
timer_response = timer_service.create_timer(timer_request)
if str(timer_response.status) == "Status.ON":
session_attr = handler_input.attributes_manager.session_attributes
if not session_attr:
session_attr['lastTimerId'] = timer_response.id
speech_text = 'Your 40 minutes timer has started!.'
return (
handler_input.response_builder
.speak(speech_text)
.response
.ask("Would you like to proceed x task?")
)
else:
speech_text = 'Timer did not start'
return (
handler_input.response_builder
.speak(speech_text)
.response
)
I tried by adding a return .ask() but I got 'Response' object has no attribute 'ask' error.
Looking forward to hearing your thoughts :)
You use response to get the response from response_builder so you should place all speak, ask etc. builder methods before response.
One way to keep the session alive is to not send "shouldEndSession". This will not let the session close. But this will not be approved if you go for certification.

Unable to find the duplicate elements from API response

We were testing an API and recently got an issue, some of the customers cannot log in to the website.
We found the issue and it is because of Duplicate keys in the API response, it is giving response even if the API contains the duplicate key.
So tests are not helping for the duplicate key conditions,So can anyone please help me or guide how I can find whether there is a duplicate element in the API response.
Tool: postman
Below is the sample API output,
In the below JSON output from API we can find there are duplicates for "operatingSystem",like this duplicate key is coming for different elements.
Since there is no way to debug the API for a while due to some reasons,so need to find out these duplicate cases.
Any idea or suggestions will be much appreciated.Thanks in advance.
JSON
eg: {
"code": 2,
"deviceId": "ID",
"deviceName": "Test",
"platform": "x64",
"operatingSystem": "test",
"operatingSystem": "test",
"gde": 000,
"productVersion": "0.0",
"build": "00000",
"receipt": null
}
How could we handle such a situation. Do we have any method to automate/test this case?
Here's something you can try although it's a bit convoluted. pm.response.json() will normalize the response and remove any duplicates i.e. you won't be able to detect any. So what you can do is take the response in text then manipulate it into a list and look for duplicates there. I used a map object so that if the map already contains a given key then set a flag and fail the test.
This is not thoroughly tested but it should give you an idea or at least a starting point to tackle the problem:
var jsonBody = pm.response.text();
var str = jsonBody.substring(1, jsonBody.length-1);
var keyArr = str.split(",");
var keyMap = {};
var foundDups = false;
for (var i = 0; i < keyArr.length; i++) {
var key = keyArr[i].split(":")[0];
if(!(key in keyMap)) {
keyMap[key] = key;
console.log("added key " + key);
}
else {
console.log("found duplicate: " + key);
foundDups = true;
break;
}
}
pm.test("Look for dups", function() {
pm.expect(foundDups).to.eql(false);
});

Karate - how to access an array element by UUID during a 'retry until' statement

I have an endpoint which returns this JSON response:
{
"jobs": [
{
"name": "job1",
"id": "d6bd9aa1-0708-436a-81fd-cf22d5042689",
"status": "pending"
},
{
"name": "job2",
"id": "4fdaf09f-51de-4246-88fd-08d4daef6c3e",
"status": "pending"
}
]
I would like to repeatedly GET call this endpoint until the job I care about ("job2") has a "status" of "completed", but I'd like to check this by using a UUID stored in a variable from a previous call.
i.e. by doing something like this:
#NB: code for previous API call is executed
* def uuidVar = response.jobRef
#NB: uuidVar equates to '4fdaf09f-51de-4246-88fd-08d4daef6c3e' for this scenario
* configure retry = { count: 5, interval: 10000 }
Given path /blah
And retry until response.jobs[?(#.id==uuidVar)].status == 'completed'
When method GET
Could anyone suggest the correct syntax for the retry until?
I've tried referencing the fantastic Karate docs & examples (in particular, js-arrays.feature) and some questions on SO (including this one: Karate framework retry until not working as expected) but sadly I haven't been able to get this working.
I also tried using karate.match here as suggested in the link above, but no cigar.
Apologies in advance if I am missing something obvious.
First I recommend you read this answer on Stack Overflow, it is linked from the readme actually, and is intended to be the definitive reference. Let me know if it needs to be improved: https://stackoverflow.com/a/55823180/143475
Short answer, you can't use JsonPath in the retry until expression, it has to be pure JavaScript.
While you can use karate.jsonPath() to bridge the worlds of JsonPath and JS, JsonPath can get very hard to write and comprehend. Which is why I recommend using karate.filter() to do the same thing, but break down the steps into simple, readable chunks. Here is what you can try in a fresh Scenario:. Hint, this is a good way to troubleshoot your code without making any "real" requests.
* def getStatus = function(id){ var temp = karate.filter(response.jobs, function(x){ return x.id == id }); return temp[0].status }
* def response =
"""
{
"jobs": [
{
"name": "job1",
"id": "d6bd9aa1-0708-436a-81fd-cf22d5042689",
"status": "pending"
},
{
"name": "job2",
"id": "4fdaf09f-51de-4246-88fd-08d4daef6c3e",
"status": "pending"
}
]
}
"""
* def selected = '4fdaf09f-51de-4246-88fd-08d4daef6c3e'
* print getStatus(selected)
So if you have getStatus defined up-front, you can do this:
* retry until getStatus(selected) == 'completed'
Note you can use multiple lines for a JS function if you don't like squeezing it all into one line, or even read it from a file.

How to pass same parameter with different value

I am trying the following API using Alamofire, but this API has multiple "to" fields. I tried to pass an array of "to" emails as parameters. It shows no error but did not send to all emails. API is correct, I tested that from terminal. Any suggestions will be cordially welcomed.
http -a email:pass -f POST 'sampleUrl' from="email#email.com" to="ongkur.cse#gmail.com" to="emailgmail#email.com" subject="test_sub" bodyText="testing hello"
I am giving my code:
class func sendMessage(message:MessageModel, delegate:RestAPIManagerDelegate?) {
let urlString = "http://localhost:8080/app/user/messages"
var parameters = [String:AnyObject]()
parameters = [
"from": message.messageFrom.emailAddress
]
var array = [String]()
for to in message.messageTO {
array.append(to)
}
parameters["to"] = array
for cc in message.messageCC {
parameters["cc"] = cc.emailAddress;
}
for bcc in message.messageBCC {
parameters["bcc"] = bcc.emailAddress;
}
parameters["subject"] = message.messageSubject;
parameters["bodyText"] = message.bodyText;
Alamofire.request(.POST, urlString, parameters: parameters)
.authenticate(user: MessageManager.sharedInstance().primaryUserName, password: MessageManager.sharedInstance().primaryPassword)
.validate(statusCode: 200..<201)
.validate(contentType: ["application/json"])
.responseJSON {
(_, _, jsonData, error) in
if(error != nil) {
println("\n sendMessage attempt json response:")
println(error!)
delegate?.messageSent?(false)
return
}
println("Server response during message sending:\n")
let swiftyJSONData = JSON(jsonData!)
println(swiftyJSONData)
delegate?.messageSent?(true)
}
}
First of all if you created the API yourself you should consider changing the API to expect an array of 'to' receivers instead of multiple times the same parameter name.
As back2dos states it in this answer: https://stackoverflow.com/a/1898078/672989
Although POST may be having multiple values for the same key, I'd be cautious using it, since some servers can't even properly handle that, which is probably why this isn't supported ... if you convert "duplicate" parameters to a list, the whole thing might start to choke, if a parameter comes in only once, and suddendly you wind up having a string or something ...
And I think he's right.
In this case I guess this is not possible with Alamofire, just as it is not possible with AFNetworking: https://github.com/AFNetworking/AFNetworking/issues/21
Alamofire probably store's its POST parameter in a Dictionary which doesn't allow duplicate keys.