Wondering if anyone can assist
I am utilizing some code from RIAForge which integrates with the Last.fm api...
One of the methods outputs as a struct, but I would like to modify the code so it outputs as an array, am unsure of how to do this..
Currently the code is like this
<cfscript>
var args = StructNew();
var returnStruct = StructNew();
var results = "";
var i = 0;
args['playlistURL'] = arguments.playlistURL;
results = super.callMethod('playlist.fetch', args).playlist;
returnStruct['title'] = results[':title'];
returnStruct['annotation'] = results[':annotation'];
returnStruct['creator'] = results[':creator'];
returnStruct['date'] = results[':date'];
if(StructKeyExists(results, ':trackList') AND StructKeyExists(results[':trackList'], ':track')){
results = super.ensureArray(results[':trackList'][':track']);
returnStruct['tracks'] = QueryNew('album,creator,duration,identifier,image,info,title');
for(i=1; i LTE ArrayLen(results); i=i+1){
QueryAddRow(returnStruct.tracks);
QuerySetCell(returnStruct.tracks, 'album', results[i].album);
QuerySetCell(returnStruct.tracks, 'creator', results[i].creator);
QuerySetCell(returnStruct.tracks, 'duration', results[i].duration);
QuerySetCell(returnStruct.tracks, 'identifier', results[i].identifier);
QuerySetCell(returnStruct.tracks, 'image', results[i].image);
QuerySetCell(returnStruct.tracks, 'info', results[i].info);
QuerySetCell(returnStruct.tracks, 'title', results[i].title);
}
}
return returnStruct;
Am just wondering if there is a coldfusion method that allows me to convert the returnStruct into a query..
Many thanks
In CF 10 and Railo 4, you can use the QueryNew() function if you have an array of structs that you want to convert to a query.
Usage: QueryNew(columnList, columnTypeList, arrayOfStructs)
CFLIB.org is your friend
QueryToArrayOfStructures
You'll need to do it by hand by looping over your results and placing in an Array of Arrays. If, you want to convert your struct to a query there are functions at http://www.cflib.org that are ready to go.
var returnArray = []; /* or arrayNew(1) if not on Railo or CF9 */
/* ACF9 or Railo Style */
arrayAppend(returnArray, [results[':title'],results[':annotation'],results[':creator'],results[':date'] ]);
/* ACF8 and earlier */
arrayAppend( returnArray, arrayNew(1) ]);
arrayAppend( returnArray[ arrayLen(returnArray) ], results[':title'] ]);
arrayAppend( returnArray[ arrayLen(returnArray) ], results[':annotation'] ]);
Related
var users = [
{id :3,name : adel,description: agent},{ id :4,name : anu,description: Manager,},
{id:5,name:arun,description:poen}
]
here i want to save each json object save in separate variable ,so i can acess it easily, how to do that
for (int i =0; i<users.length;i++)
{
var descrip = users[i]['description'];
}
when i using this above loop method ,the variable saves only the last data in the list , im new to flutter , anyone know how to save this data to variable ,please help me
final List<String> description = new [];
for(int i = 1;i < users.length; i++){
description.add(users[i]['description']);
}
As Belle Zaid said you declared your variable descrip inside your loop and overwrite it on each step. That's the reason why you only get your last value. First you need to declare a List outside of the for loop and inside the loop you add each value to the list.
final List<String> descrip = [];
for(int i = 0;i < users.length; i++){
descrip.add(users[i]['description']);
}
Try this
List<Map<String, dynamic>> usersJson = [
{'id': 3, 'name': 'adel', 'description': 'agent'},
{ 'id': 4, 'name': 'anu', 'description': 'Manager',},
{'id': 5, 'name': 'arun', 'description': 'poen'}
];
List<String> descriptions = [];
for (int i =0; i<users.length;i++)
{
descriptions.add(users[i]['description']);
}
I have a cfc where i need t return the headers for the jqgrid for binding dynamically
i am trying to query the data like this:
colNames: ['ID', 'Institution Name', 'Display Name', 'Short Name', 'Board of Education', 'Scheme Name','Subscription Date'],
colModel: [
{ name: 'institutionid', sortable: true, },
{ name: 'institutionname', sortable: true },
{ name: 'displayname', sortable: true },
{ name: 'shortname' ,sortable: true},
{ name: 'supportedfield', sortable: true },
{ name: 'schemename', sortable: true },
{ name: 'subscriptionto', sortable: true}
]
i can easily get the colNames, but for colmodal how can i bring the elements of sort: true for all by default and format should be like arrayofstructs
Thanks
Query try
<cffunction name="headers" localmode="modern" access="remote" returnformat="json" hint="Handles the Functionality of returning the Table Headers">
<cfset columnsInfos = {}>
<cfset returnArray = []>
<cfset cList = QueryExecute("select top 1 * from mytable").columnList>
<cfset cListQueryObj = QueryNew(cList)>
<cfdump var="#cListQueryObj#" abort>
<cfset colNames = ListtoArray(cList)>
<cfloop query="#cListQueryObj#">
<cfset rowStruct = {}>
<cfloop list="#cList#" index="colname">
<cfset "rowStruct['#colname#']" = cListQueryObj[colname]>
</cfloop>
<cfset arrayAppend(returnArray,rowStruct)>
<cfdump var="#rowStruct#">
</cfloop>
<cfset columnsInfos["colModel"] = returnArray>
<cfset columnsInfos["colNames"] = colNames>
<cfreturn columnsInfos>
</cffunction>
Serializing a query object won't return the expected result. Since you are using the built-in returnFormat="json", the easiest (and probably only) approach is working with an array of structs, just like your JS example shows:
<cffunction name="headers" localmode="modern" access="public" returnformat="json" hint="Handles the Functionality of returning the Table Headers">
<!--- best practise: declare the returned scheme --->
<cfset result = {
"colNames": [],
"colModel": []
}>
<!--- get your table's columns (mockup) --->
<cfset columnList = "institutionid,institutionname,displayname,shortname,supportedfield,schemename,subscriptionto">
<!--- use the column names from your query? --->
<cfset result["colNames"] = listToArray(columnList)>
<!--- add an entry with "name" and "sortable" for every column --->
<cfloop list="#columnList#" index="columnName">
<cfset result["colModel"].add({
"name": columnName,
"sortable": true
})>
</cfloop>
<cfreturn result>
</cffunction>
Note that we are not calling serializeJSON on the result, because returnFormat="json" will already do that for us. Regarding your colNames: Your JS example uses mapped column names, not dynamic ones as shown in your code and the code above. You might want to make them either static or map them yourself.
I like Alex's approach, but I like cfscript better. I also like localized variables.
<cfscript>
/**
* #hint Handles the Functionality of returning the Table Headers
* #output false
* #returnFormat JSON
*/
public any function headers() {
// best practise: declare the returned scheme
var result = {
"colNames": [],
"colModel": []
};
// get your table's columns (mockup)
var columnList = "institutionid,institutionname,displayname,shortname,supportedfield,schemename,subscriptionto";
// use the column names from your query?
result.colNames = listToArray(columnList);
// add an entry with "name" and "sortable" for every column
for (var columnName in columnList) {
result.colModel.add({
"name": columnName,
"sortable": true
});
}
return result;
}
writedump(headers);
writedump(headers());
</cfscript>
Function signature
Function results
Also see
JSON response using cfscript function
I would like to pass two parameters to a SELECT query for one scenario in a vtiger custom function. Like below ..
function start_date($projectid, $stage){
$adb = PearDatabase::getInstance();
$stage = "Stage-0";
$data = $adb->pquery("SELECT startdate FROM vtiger_projecttask WHERE projectid = ?", array($projectid), array($stage);
$num_rows = $adb->num_rows($data);
for($i=0; $i<$num_rows; $i++) {
$col3[$i] = $adb->query_result($data, $i,'startdate');
}
}
But it is not allowing me to execute this type of query. How can i form a query with two parameters in vtiger?
Thanks and Regards.
Please try this code as below. This will work.
function start_date($projectid, $stage){
$adb = PearDatabase::getInstance();
$stage = "Stage-0";
$data = $adb->pquery("SELECT startdate FROM vtiger_projecttask WHERE projectid = ? and stage = ?", array($projectid,$stage));
$num_rows = $adb->num_rows($data);
for($i=0; $i<$num_rows; $i++) {
$col3[$i] = $adb->query_result($data, $i,'startdate');
}
}
I'm noticing significant code duplication while building my first Meteor project, and I'm wondering if there's a way to DRY it up.
My database model has stores, each of which have a number of products, and a field with the amount currently in inventory.
var store_id = Store.insert({name: 'Store 1', max_items: 50});
var p1 = Product.insert({name: 'General', store_id: store_id, item_count: 20});
var p2 = Product.insert({name: 'Special', store_id: store_id, item_count: 10});
I have a template to display a store, and statistics on how many products and items it has.
<template name="store">
<div class="store">
<b>{{name}}</b>
<p>Current items: {{current_items}}</p>
<p>Maximum # of items allowed in inventory: {{max_items}}</p>
<p>% Full: {{percent_full}}%</p>
</div>
</template>
Calculating the number of current items seems fairly straightforward, I pull all the products, sum the item counts (using d3), return the result.
Template.store.current_items = function () {
var store_id = this._id;
var items = Product.find({store_id: store_id}).fetch();
if ( items.length > 0 ) {
var item_cnt = d3.sum(_.pluck(items, 'item_count'));
return item_cnt;
}
else {
return 'N/A';
}
};
To calculate a percentage comparing the total # of allowed items, and the current items, it seems like I have to reduplicate everything. Is there a better way to do this?
Template.store.percent_full = function () {
var store_id = this._id;
var items = Product.find({store_id: store_id}).fetch();
if ( items.length > 0 ) {
var item_cnt = d3.sum(_.pluck(items, 'item_count'));
return item_cnt / max_items * 100;
}
else {
return 'N/A';
}
};
Extract the duplicated logic to a separate function and just call it appropriately from different helpers. This is not really different from DRYing any other JS code.
I am returning data to the chart using JSON.
I've managed to format the date for the x-axiz of the Line Chart, using;
var options = {
hAxis: {
format: ' dd MMM yy'
},
}
But I need help doing the same for a Table Chart where one of the columns should be of date format.
At the moment it is displaying "/Date(1372761341103)/"
How do I format this option?
As I understand it, the "options" variable setting is not available for the Table Chart.
Also, when I add my columns, setting my 'Date' column's data type to 'date' doesn't work...no chart is returned.
This is my code currently:
function drawChart3() {
$.get('/MyMall/GetAdRunData', {},
function (data) {
/* Add data */
var tdata = new google.visualization.DataTable()
tdata.addColumn('number', 'Id');
tdata.addColumn('string','Date');
tdata.addColumn('number', 'Opens');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Id, data[i].Date, data[i].Opens]);
}
/* Draw chart */
var chart = new google.visualization.Table(document.getElementById('chart_adRun'));
//var formatter = new google.visualization.ColorFormat();
//var monthYearFormatter = new google.visualization.DateFormat({ pattern: "MMM yyyy" });
monthYearFormatter.format(tdata, 0);
formatter.addRange(-1, 1, 'white', 'orange');
formatter.addRange(0, 2, 'red', '#33ff33');
formatter.addRange(1, 10, 'red', 'pink');
formatter.format(tdata, 1); // Apply formatter to second column
chart.draw(tdata, { allowHtml: true, showRowNumber: false });
}
)
}
I solved it this way...
for (var i = 0; i < data.length; i++) {
var date = new Date(parseInt(data[i].Date.substr(6)));
tdata.addRow([data[i].Id, date, data[i].Opens]);
}