obtain demographic data with google analytics api - analytics

im trying to obtain some demographic data from the google analytics api, my intention is to integrate this on a cms to generate reports, etc... is this possible?
if it is, is there someone who knows a tutorial or something? i have used the examples provided and i get some sessions that have been in the last 7 day period. But nothing besides that. If that is not possible, what kind of things i can obtain with this api?
here is what i have tried:
function getResults(&$analytics, $profileId) {
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
thanks in advance.

You can obtain everything that's listed in the Dimensions and Metrics Reference. This includes ga:userAgeBracket and ga:userGender for demographic information.
To include additional metrics (numerical data) you put it as a parameter where you now have ga:sessions (separate multiple metrics with a comma). You need at least one metric for a query to work.
To add dimensions (i.e. categorical data) you need to pass an options array to your query that has a key/value pair for dimensions. This may also include additional options like filters or sort options, see the example here..
$optParams = array(
'dimensions' => 'ga:userAgeBracket,ga:userGender'
);
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions',
$optParams
);
This for version 3 of the API. If you are just getting started an have no legacy code to maintain you might as well start with there current version (v4).

To be able to get age and gender informations from analytics, you should Enable Demographics and Interests reports on your GA account.
doc : https://support.google.com/analytics/answer/2819948

Related

WordPress : make categories automatically match according to external API Value

I'm managing a company website, where we have to display our products. We however do not want to handle the admin edit for this CPT, nor offer the ability to access to the form. But we have to read some product data form the admin edit page. All has to be created or updated via our CRM platform automatically.
For this matter, I already setup a CPT (wprc_pr) and registered 6 custom hierarchical terms: 1 generic for the types (wprc_pr_type) and 5 targeting each types available: wprc_pr_rb, wprc_pr_sp, wprc_pr_pe, wprc_pr_ce and wprc_pr_pr. All those taxonomies are required for filtering purposes (was the old way of working, maybe not the best, opened to suggestions here). We happen to come out with archive pages links looking like site.tld/generic/specific-parent/specific-child/ which is what is desired here.
I have a internal tool, nodeJS based, to batch create products from our CRM. The job is simple: get all products not yet pushed to the website, format a new post, push it to the WP REST API, wait for response, updated CRM data in consequence, and proceed to next product. Handle about 1600 products today on trialn each gone fine
The issue for now is that in order for me to put the correct terms to the new post, I have to compute for each product the generic type and specific type children.
I handled that by creating 6 files, one for each taxonomy. Each file is basically a giant JS object with the id from the CRM as a key, and the term id as a value. My script handles the category assertion like that:
wp_taxonomy = [jsTaxonomyMapper[crm_id1][crm_id2]] // or [] if not found
I have to say it is working pretty well, and that I could stop here. But I will have to take that computing to the wp_after_insert_post hook, in order to reaffect the post to the desired category on updated if something changed on the CRM.
Not quite difficult, but if I happen to add category on the CRM, I'll have to manually edit my mappers to add the new terms, and believe me that's a hassle.
Not waiting for a full solution here, but a way to work the thing. Maybe a way to computed those mappers and store their values in the options table maybe, or have a mapper class, I don't know at all.
Additional information:
Data from the CRM comes as integers (ids corresponding to a label) and the mappers today consist of 6 arrays (nested or not), about 600 total entries.
If you have something for me, or even suggestions to simplify the process, I'll go with it.
Thanks.
EDIT :
Went with another approach, see comment below.

SuiteCommerce Advanced - Show a custom record on the PDP

I am looking to create a feature whereby a User can download any available documents related to the item from a tab on the PDP.
So far I have created a custom record called Documentation (customrecord_documentation) containing the following fields:
Related item : custrecord_documentation_related_item
Type : custrecord_documentation_type
Document : custrecord_documentation_document
Description : custrecord_documentation_description
Related Item ID : custrecord_documentation_related_item_id
The functionality works fine on the backend of NetSuite where I can assign documents to an Inventory item. The stumbling block is trying to fetch the data to the front end of the SCA webstore.
Any help on the above would be much appreciated.
I've come at this a number of ways.
One way is to create a Suitelet that returns JSON of the document names and urls. The urls can be the real Netsuite urls or they can be the urls of your suitelet where you set up the suitelet to return the doc when accessed with action=doc&id=_docid_ query params.
Add a target <div id="relatedDocs"></div> to the item_details.tpl
In your ItemDetailsView's init_Plugins add
$.getJSON('app/site/hosting/scriptlet.nl...?action=availabledoc').
then(function(data){
var asHtml = format(data); //however you like
$("#relatedDocs").html(asHtml);
});
You can also go the whole module route. If you created a third party module DocsView then you would add DocsView as a child view to ItemDetailsView.
That's a little more involved so try the option above first to see if it fits your needs. The nice thing is you can just about ignore Backbone with this approach. You can make this a little more portable by using a service.ss instead of the suitelet. You can create your own ssp app for the function so you don't have to deal with SCAs url structure.
It's been a while, but you should be able to access the JSON data from within the related Backbone View class. From there, within the return context, output the value you're wanting to the PDP. Hopefully you're extending the original class and not overwriting / altering the core code :P.
The model associated with the PDP should hold all the JSON data you're looking for. Model.get('...') sort of syntax.
I'd recommend against Suitelets for this, as that's extra execution time, and is a bit slower.
I'm sure you know, but you need to set the documents to be available as public as well.
Hope this helps, thanks.

how to query watson discovery api?

I am experimenting IBM watsons' Discovery API to get data insights. I want to query using multiple filters. I am using python to accomplish the task. I have tried this for now, but this is not working.
qopts = {'filter':[{'enriched_text.entities.text:Recurrent Neural
Networks,Machine Learning classifiers'}]}
my_query = discovery.query(env_id, coll_id, qopts)
with only single entity : 'recurrent Neural Networks' through the discovery UI and through my python query, I get 3 documents from the collection.
but with two entities, 'Recurrent Neural Networks,Machine Learning classifiers', in the UI I get 2 documents but through my code, I get 2 documents.
Below is then right format which works for me. with multiple concept and keyword filters, I get a total of 2 search results, which match with the UI query
qopts = {'filter':{'enriched_text.concepts.text:"Neural network",enriched_text.keywords.text:"Neural Network",enriched_text.keywords.text:"generative conversational models"'}}
with only entity I get 3 match results
qopts = {'filter':{'enriched_text.concepts.text:"Neural network"'}}
in this example I am querying the documents with concept 'Neural network' , keywords 'Neural Network' and 'generative conversational models'
Inside Watson discovery documentation, inside the UI you'll use (according to the documentation):
But obviously, without the ! operator inside the second text.
and I think inside your code you need to use , between the values.
Not sure because I don't use the enriched_text.entities.textinside my filter, just the Strings.
One possible reference for another example to test:
filter=field1:some value,field2:another value
Official reference documentation: here.

Watson RnR - Creating Ranker using REST API

I am trying out to create an Ranker using the REST API after successfully Adding documents to the collection.
Do I need to use train.py. If so then whats the use of create Ranker API. Also while trying to create RANKER, can you please tell me where do I need to specify cluster id and collection name. Do I need to specify it in metadata.json file.
Any help would be highly appreciated.
See here for an overview of the methods available for training a ranker: https://www.ibm.com/watson/developercloud/doc/retrieve-rank/training_data.html#methods. Using the REST API directly is described under the 'Manually training a ranker' section and is intended for advanced users that might be appending additional columns to the feature vectors that are generated automatically when you use train.py.
The create Ranker REST API call does not take 'cluster id' and 'collection names' as input parameters. It assumes that you've already used the /fcselect REST API call (which does take 'cluster id' and 'collection id') to pre-generate feature vectors similar to what train.py is doing internally. Again, in the advanced use case, you might take these feature vectors and then augment them using some other custom features as described in this blog post: https://medium.com/machine-learning-with-ibm-watson/developing-with-ibm-watson-retrieve-and-rank-part-3-custom-features-826fe88a5c63#.unfm2ocik

CakePHP 3.0: How Can I Organize These Model Functions

I am working on a CakePHP3 application that will be used to display information about which products our suppliers are currently offering.
** Different Vendors provide their product lists in different ways, CSV, JSON, or by way of a web scrape **
I have 2 models that I have created:
Vendors - This references a specific Vendor that we use.
VendorProducts - This references all the products that all of our vendors offer.
I would like to be able to call something like:
$vendor->getAvailableProducts()
and have it either get the CSV and parse it, grab the JSON, or scrape the suppliers website and use this to populate the VendorProducts table in the database with products from this supplier.
I understand the idea behind Fat Models and Skinny Controllers, however I'm having a bit of difficulty implementing this feature.
I would like to provide the following functionality.
The Vendor's getAvailableProducts() function can be called via the web interface AND/OR a cakephp shell script that could be run in a cron job.
As some functionality (like scraping the website) takes a considerable amount of time, I would like to be able to see the progress of this function in the view,
eg: X/Y Products Updated from {Supplier}.
This can be broken down into the following questions:
1. Which file should my "getAvailableProducts()" function go in?
2. As each $vendor has a unique updateProducts() function, how would the correct function be called from $vendor->getAvailableProducts()
// something like this?
public function getAvailableProducts() {
if($vendor->name == "SupplierA") {
getProductsFromSupplierA();
}
if($vendor->name == "SupplierB") {
getProductsFromSupplierB();
}
..., etc.
}
3. How can the progress of this function be returned to a View?
Don't use table classes for that create a new namespace within the model layer or in the app itself:
src/Vendor
src/Model/Vendor
Have a factory that constructs and returns you the Vendor classes:
$vendorA = VendorFactory::get('SupplierA');
$vendorB = VendorFactory::get('SupplierB');
Each vendor class must implement a method fetchProducts(), use an interface or an abstract base class for that.
The method should return a normalized array that can be used to turn the products in entities:
$this->newEntities(VendorFactory::get('SupplierA')->fetchProducts());
You'll have a hard time determining the progress if there is no way to know the total amount of records. Which is likely when you scrape the website. Same issue applies when the API doesn't tell you the total amount of records per JSON data set. If you're able to get that total count somehow you can do this:
$this->newEntities(VendorFactory::get('SupplierA')->fetchProducts([
'limit' => 50,
'offset' => 0
]);
And implement pagination for the vendor which you can then use to run over all the records in a while() loop in chunks of X records. If you trigger that via shell you can create a "job" for that and update the progress after each chunk. There are multiple existing solutions for this kind of task already out there. Finally use Comet or Websockets to get the status updated on your website. Or the old way: Trigger an AJAX request every X seconds to check the status.
There is a lot more that could be said, but this is actually already a very broad question, there is very likely not enough detail to cover all cases. Also it might be possible (I'm pretty sure) there are different ways to solve this.

Resources