Videos sorted by relevance with more views than sorted by View count on YouTube - youtube-api

I'm trying to implement a search of the most popular videos by tag with Youtube API v3, and encountered a problem when videos sorted by Relevance have more views than those that were sorted by View count.
export const videoList = async (p = null, args: any): Promise<VideoItems | undefined> => {
try {
const {q, maxResults = 5} = args || {};
const youtube = google.youtube({auth: process.env.GOOGLE_CLIENT_API_KEY, version: 'v3'});
const resp: any = await youtube.search.list({
part: 'snippet',
order: 'relevance',
relevanceLanguage: 'en',
regionCode: 'us',
type: 'video',
q: `#${q}`,
maxResults
});
return {
items: resp?.data?.items?.map((item: VideoItem) => (
{id: item?.id?.videoId, title: item?.snippet?.title})
)
};
} catch (err) {
console.log(err);
}
This behavior is reproduced in a native YouTube search:
By relevance: https://www.youtube.com/results?search_query=%23Equality+of+triangles&sp=CAA%253D
By View count: https://www.youtube.com/results?search_query=%23Equality+of+triangles&sp=CAM%253D
Is there a better way to get the most popular videos by tag with high numbers of views other than order: 'relevance'?
Why do videos sorted by relevance have more views than those sorted by View count?

Related

How to define the data source for a DataTables column that is an element of an array?

This is in a C# ASP.NET MVC 5 web application. jQuery version 1.10.2. DataTables jQuery plugin version 1.10.21.
A page in the web application uses a DataTable. The DataTable is configured for server-side processing mode. So, when it receives a response from the server, the data for a row in the table is an object like the following example. (It is not proper JSON syntax; I am trying to represent what I see in the watch window of the browser's debugger.) i.e., each row has a string name, and an array of grade objects.
row: {...}
Id: 42
Name: "Fred"
Grades: (3) [...]
0: {...}
Id: 101
Name: "Quiz 1"
Value: "A"
1: {...}
Id: 102
Name: "Homework 2"
Value: "B"
2: {...}
Id: 103
Name: "Exam 3"
Value: "C"
length: 3
In the DataTable, I want 4 columns: one for the name, and 3 for the several grades, like the following example.
Name Quiz 1 Homework 2 Exam 3
=========================================
Fred A B C
My problem is that I cannot determine the correct notation for the data source for each of the grade columns, so that when a cell in such a column is rendered that the callback function receives an object that contains data about the grade. The following is what I have tried in the CSHTML file for the page. (I provide the number of grades to the page via a ViewBag property.)
...
<table id="gradebook-table" class="table">
...
</table>
...
<script>
$( document ).ready( onPageReady );
function onPageReady()
{
var options = {};
options.serverSide = true;
options.ajax =
{
'url': '#Url.Content( "~/gradebook/load" )',
'type': 'POST',
};
var c = 0;
options.columnDefs = [
{ targets: c++, data: "Id", visible: false, searchable: false },
{ targets: c++, data: "Name" },
];
for ( var i = 0; i < #ViewBag.GradeCount; i++ )
{
var def = {};
def.targets = c++;
def.data = "Grades[" + i + "]";
def.render = renderGradeCell;
options.columnDefs.push( def );
}
$( '#gradebook-table' ).DataTable( options );
}
function renderGradeCell( data, type, row, meta )
{
if ( type === 'display' )
{
// I expect data to be an object containing grade properties.
return '<span>' + data.Value + '</span>';
}
return data;
}
</script>
When the data source for a grade column is "Grades[" + i + "]", the data that the renderGradeCell() function is given is not an object that I expected, but a string like the following. It is just "[object Object]0" repeated for as many items as there are in the Grades array in the data for the whole row.
"[object Object]0[object Object]0[object Object]0"
I changed the data source for a grade column to just "Grades[]". But then, the data that the renderGradeCell() function is given is the entire Grades array for that row.
Any suggestions are appreciated. Thanks.

Google Docs API - adjust width of table column

I am able to create a table using the Google Docs Api. By default, each column is of equal width.
How is it possible to adjust the width of the columns using the Google Docs API?
I can see the updateTextStyle and updateParagraphStyle request types (batchUpdate methods) but there's currently no updateTable method, or any similar method that looks like it could do this. I'm using the reference documentation, here:
https://developers.google.com/docs/api/reference/rest/v1/documents/request
I'm using NodeJS / Javascript to interact with the API currently.
This is possible, in fact all the table operation that you can do on UI are possible.
1) Create table with following request:
def create_loc_table(doc_id, r, c, idx):
"""
r = number of rows,
c = number of columns,
idx = Start index where table needs to be created.
"""
request = [{
'insertTable': {
'rows': r,
'columns': c,
'location': {
'segmentId':'',
'index': idx
}
},
}
]
result = self.docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': request}).execute()
print('Result {0}'.format(json.dumps(result, indent=4)))
2) Modify/update the table:
def modify_table(self, t_idx):
"""
t_idx = Table start index.
"""
request = [{
'updateTableColumnProperties': {
'tableStartLocation': {'index': t_idx},
'columnIndices': [0],
'tableColumnProperties': {
'widthType': 'FIXED_WIDTH',
'width': {
'magnitude': 100,
'unit': 'PT'
}
},
'fields': '*'
}
}
]
result = self.docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': request}).execute()
print('Result {0}'.format(json.dumps(result, indent=4)))
3) Output would be

Google sheet api find by url

I`m working with google sheet api and Im trying to check if my table has duplicate data for url. I have a column on my table called 'url' that contains urls like 'https://www.youtube.com/' and im using npm i google-spreadsheet node api.
My table example:
id | url
1 | https://www.youtube.com/
I tried:
sheet.getRows({
offset: 0,
limit: 10,
query: "url = 'https://www.youtube.com/'"
}, function( err, rows ){
if(rows && rows.length > 0) {
console.log('found')
} else {
console.log('not found')
}
})
This url is on the table, If I do that above with ID = 1, it find`s it. So the problem is to find url because of its format. I also tried to encode the url with
encodeURIComponent
and didnt work.
How can I do this?
Thanks

Dynamic Filters for OData Read Based on Input

I have the requirement to send filter values via OData-service, to fill a table with relevant entries.
So basically there are input fields, where you can select e.g. "AA" (american airlines) for Carrier-ID.
So the filter values need to be created dynamically, regarding to the user input.
I tried following:
var aFilters = [
new sap.ui.model.Filter({
path: "Carrid",
operator: sap.ui.model.FilterOperator.EQ,
value1: "{selection>/Carrid}"
})
];
oModel.read("/SFLIGHTSSet",{
method: "GET",
filters: aFilters,
success: function(oData2, oResponse) {
var oJSONModel = new sap.ui.model.json.JSONModel();
oJSONModel.setData({
modelData: oData2.results
});
oTable.setModel(oJSONModel);
oTable.bindRows("/modelData");
},
error: function(oError) {
console.log("Error!");
}
});
But that doesn't work.
I receive in back-end following request:
"( Carrid eq '{selection>/Carrid}' )"
So the binding doesn't work in the filter-creation...
The binding is correct because I can use it the same way in a Label:
new sap.m.Label({
text: "{selection>/Carrid}"
});
I researched a lot and know that people have problems with it in XML views.. but couldn't find any solution for JS-Views.
I guess your problem is in the line
"{selection>/Carrid}"
Get the value of the User-Input from the Control somehow like this
var sCarrid= this.byId("MySelection").getBindingContext("selection").getProperty("Carrid");
and modify your Filter
var oFilters = [ new sap.ui.model.Filter("Carrid",
sap.ui.model.FilterOperator.EQ,
sCarrid) ];

How to get bar label in Google Timeline chart with Chartkick gem

I'm using chartkick gem to render a Google timeline graph. While this works very nicely out of the box, I read on the Google documentation, that I'm also able to include a bar label:
https://developers.google.com/chart/interactive/docs/gallery/timeline#labeling-the-bars
Is there an option to add that extra column to the datatable with the help of Chartkick?
I basically need this to be invoked before the Timeline is rendered:
dataTable.addColumn({ type: 'string', id: 'Name' });
Thanks
Code sample:
<%= timeline [
["Washington", "1789-04-29", "1797-03-03"],
["Adams", "1797-03-03", "1801-03-03"],
["Jefferson", "1801-03-03", "1809-03-03"]
] %>
This requires a change in the source, chartkick.js:
First, you need to add a line describing the new data column to the beginning of "this.renderTimeline" (i've called it Label):
...
var data = new google.visualization.DataTable();
data.addColumn({type: "string", id: "Label"});
data.addColumn({type: "string", id: "Name"});
data.addColumn({type: "date", id: "Start"});
data.addColumn({type: "date", id: "End"});
data.addRows(chart.data);
Second, you need to update the "processTime" function, by adding 1 to the array values (since we've increased the array size by 1):
function processTime(chart)
{
var i, data = chart.rawData;
for (i = 0; i < data.length; i++) {
data[i][2] = toDate(data[i][2]); // from data[i][1]
data[i][3] = toDate(data[i][3]); // from data[i][2]
}
return data;
}

Resources