What is context token in guava TypeToken explained? - guava

In the documentation:
resolveType is a powerful but complex query operation that can be used to "substitute" type arguments from the context token. For example,
So, what is context token? have something to do with TypeResolver??

The example that follows this sentence explains it:
TypeToken<Function<Integer, String>> funToken = new TypeToken<Function<Integer, String>>() {};
TypeToken<?> funResultToken = funToken.resolveType(Function.class.getTypeParameters()[1]));
// returns a TypeToken
In this example, the "context" token is funToken, i.e. the token on which resolveType() is called, and which thus provides the "context" of the query that resolveType() executes.

Related

What does `namespaceMappings` mean in Word.CustomXMLPart API

I have created a small snippet in Script Lab which basically:
Creates a custom XML:
<AP xmlns="accordproject.org">
<template xmlns="acceptance-of-delivery">
<shipper>Aman Sharma</shipper>
</template>
</AP>
Tries to query this xml by using the xPath /AP/template. I run this block of code:
await Word.run(async context => {
const customXmlParts = context.document.customXmlParts;
const AP = customXmlParts.getByNamespace("accordproject.org").getOnlyItemOrNullObject();
await context.sync();
const nodes = AP.query('/AP/template', {}); // how does this work?
await context.sync();
console.log(nodes);
})
Deletes the customXML.
The second argument of query API is namespaceMappings. I think I am passing that incorrectly and that's why I get this as ouput (empty object).
But when I pass * instead of /AP/template, I get the whole XML (while the second argument, namespaceMappings remain the same).
Where am I going wrong? Can anyone share some snippets to help me query customXML.
The short answer is that you can use
const nodes = AP.query("/n1:AP/n2:template", {n1:"accordproject.org", n2:"acceptance-of-delivery"});
I don't know JS/TS at all but I assume these are basically key-value pairs of some kind. You can also use
const nodes = AP.query("/n1:AP/n2:template", {"n1":"accordproject.org", "n2":"acceptance-of-delivery"});
if you prefer to think of the Namespace prefixes as strings.
(For anyoneunfamiliar, the "n1" and "n2" are just prefixes that you invent so you can reference the full Namespace URIs. They don't have anything to do with any prefixes you might have used in the piece of XML you are querying.)
I couldn't find documentation on this either and originally assumed you might need something more like { Prefix:"ns1", namespaceURI:"the namespace URI" }, but that's just because those are the property names used in the VBA model.

Play Framework request attributes with typed key

I seem to have issues accessing the attributes of the request attributes map in Play. Following the explanation offered by Play (Link), I should get the correct data from the attributes, but the Option is returned as None.
My structure is as follows. One controller (later injected named as "sec") has the typed attribute for shared access to it:
val AuthenticatedAsAttr: TypedKey[AuthenticatedEmail] = TypedKey("AuthenticatedAs")
The type AuthenticatedEmail is defined in the companion object of this controller as a case class:
case class AuthenticatedEmail(email: String)
The filter passes the attribute to the next request:
val attrs = requestHeader.attrs + TypedEntry[AuthenticatedEmail](sec.AuthenticatedAsAttr, AuthenticatedEmail(email))
nextFilter(requestHeader.withAttrs(attrs))
When trying to then access this attribute in another controller, the returned Option is None:
val auth = request.attrs.get(sec.AuthenticatedAsAttr)
I confirmed via println that the value is definitely in request.attrs but run out of options to debug the issue successfully. A fraction of the println output below.
(Request attrs,{HandlerDef -> HandlerDef(sun.misc .... ,POST, ... Cookies -> Container<Cookies(Cookie ... , AuthenticatedAs -> AuthenticatedEmail(a#test.de), ... })
My Scala version is 2.12.6, Play Framework version 2.6.18. Any help is highly appreciated.
It turns out that the TypedKey must be within an object, not an inject-able controller. So moving it to an object like the following resolves the issue:
object Attrs {
val AuthenticatedAsAttr: TypedKey[AuthenticatedEmail] = TypedKey("AuthenticatedAs")
}
The reason is the implementation of TypedKey (Link), which does not contain an equals method and therefore reverts to comparing memory references.

How to PUT (save) object to REST endpoint using Restangular

Given I have resource id and data as plain JSON, how do I save that JSON to /cars/123/ ???
There seem to be no clear explanation. I don't have restangular element.
restangularizeElement might be the option, but it lacks any meaningful documentation.
All I know is that I want to save {make: 'honda', color: 'now blue, was red'} for car_id == 123.
Thanks.
If you have plain object you cannot use Restangular save function to update (it will make put request as object has id) object.
Easiest way to achieve it construct your end point url then call put function...
Restangular.one('cars', 123).customPUT(carObject).then(function(response){
TO-DO
})
If you want to restangularized your plain object you can use this one...
Restangular.restangularizeElement(null,carObject, 'cars').put().then(function (response) {
TO-DO
})
The comman way should be like this. Whenever you get object from backend with get or getList your object will be Restangularized unless you do not choose to turn them plain object by calling .plain() method of Restangular response. Then you can safely call .save() and it will automatically will be put or post accordingly...
Here is what worked for me. Thanks to #wickY26:
updateGroup: function (group, id_optional) {
if (!group.hasOwnProperty('restangularCollection')) {
// safe to assume it is NOT restangular element; sadly instanceof won't work here
// since there is no element class
// need to restangularize
group = Restangular.restangularizeElement(null, group, ENDPOINT);
group.id = id_optional;
}
return group.put();
},

How to use variables in MongoDB Map-reduce map function

Given a document
{_id:110000, groupings:{A:'AV',B:'BV',C:'CV',D:'DV'},coin:{old:10,new:12}}
My specs call for the specification of attributes for mapping and aggregation at run time, as the groupings the user is interested in are not known up front, but specified by the user at runtime.
For example, one user would specify [A,B] which will cause mapping emissions of
emit( {A:this.groupings.A,B:this.groupings.B},this.coin )
while another would want to specify [A,C] which will cause mapping emissions of
emit( {A:this.groupings.A,C:this.groupings.C},this.coin )
B/c the mapper and reducer functions execute server side, and don't have access to client variables, I haven't been able to come up with a way to use a variable map key in the mapper function.
If I could reference a list of things to group by from the scope of the execution of the map function, this is all very straightforward. However, b/c the mapping function ends up getting these from a different scope, I don't know how to do this, or if it's even possible.
Before I start trying to dynamically build java script to execute through the driver, does anyone have a better suggestion? Maybe a 'group' function will handle this scenario better?
As pointed out by #Dave Griffith, you can use the scope parameter of the mapReduce function.
I struggled a bit to figure out how to properly pass it to the function because, as pointed out by others, the documentation is not very detailed. Finally, I realised that mapReduce is expecting 3 params:
map function
reduce function
object with one or more of the params defined in the doc
Eventually, I arrived at the following code in Javascript:
// I define a variable external to my map and to my reduce functions
var KEYS = {STATS: "stats"};
function m() {
// I use my global variable inside the map function
emit(KEYS.STATS, 1);
}
function r(key, values) {
// I use a helper function
return sumValues(values);
}
// Helper function in the global scope
function sumValues(values) {
var result = 0;
values.forEach(function(value) {
result += value;
});
return result;
}
db.something.mapReduce(
m,
r,
{
out: {inline: 1},
// I use the scope param to pass in my variables and functions
scope: {
KEYS: KEYS,
sumValues: sumValues // of course, you can pass function objects too
}
}
);
You can pass global, read-only data into map-reduce functions using the "scope" parameter on the map-reduce command. It's not very well documented, I'm afraid.

CodeIgniter: URIs and Forms

I'm implementing a search box using CodeIgniter, but I'm not sure about how I should pass the search parameters through. I have three parameters: the search string; product category; and the sort order. They're all optional. Currently, I'm sending the parameters through $_POST to a temporary method, which forwards the parameters to the regular URI form. This works fine. I'm using a weird URI format though:
http://site.com/products/search=computer,sort=price,cat=laptop
Does anyone have a better/cleaner format of passing stuff through?
I was thinking of passing it into the products method as arguments, but since the parameters are optional things would get messy. Should I suck it up, and just turn $_GET methods on? Thanks in advance!
Query Strings
You can enable query strings in CodeIgniter to allow a more standard search function.
Config.php
$config['enable_query_strings'] = FALSE;
Once enabled, you can accept the following in your app:
http://site.com/products/search?term=computer&sort=price&cat=laptop
The benefit here is that the user will find it easy to edit the URL to make a quick change to their search, and your search uses common search functionality.
The down side of this approach is that you are going against one of the design decisions of the CodeIgniter development team. However, my personal opinion is that this is OK provided that query strings are not used for the bulk of your content, only for special cases such as search queries.
A much better approach, and the method the CI developers intended, is to add all your search parameters to the URI instead of a query string like so:
http://site.com/products/search/term/computer/sort/price/cat/laptop
You would then parse all the URI segments from the 3rd segment ("term") forward into an array of key => value pairs with the uri_to_assoc($segment) function from the URI Class.
Class Products extends Controller {
...
// From your code I assume you are calling a search method.
function search()
{
// Get search parameters from URI.
// URI Class is initialized by the system automatically.
$data->search_params = $this->uri->uri_to_assoc(3);
...
}
...
}
This would give you easy access to all the search parameters and they could be in any order in the URI, just like a traditional query string.
$data->search_params would now contain an array of your URI segments:
Array
(
[term] => computer
[sort] => price
[cat] => laptop
)
Read more about the URI Class here: http://codeigniter.com/user_guide/libraries/uri.html
If you're using a fixed number of parameters, you can assign a default value to them and send it instead of not sending the parameter at all. For instance
http://site.com/products/search/all/somevalue/all
Next, in the controller you can ignore the parameter if (parameter == 'all'.)
Class Products extends Controller {
...
// From your code I assume that this your structure.
function index ($search = 'all', $sort = 'price', $cat = 'all')
{
if ('all' == $search)
{
// don't use this parameter
}
// or
if ('all' != $cat)
{
// use this parameter
}
...
}
...
}