This hopefully is an easy questions.
I'm using Highcharts through chartit in Django and can get most of my graphs to work (temp and time). I'm now trying to graph the values ON and OFF over time. It seems that highcharts can't interpret the strings in the Y Axis (ON and OFF). Is there a way to get it to use those values?
I've tried using something like this in the chart_option section.
'yAxis': {
'categories': ['ON', 'OFF'],
'title': {'text': 'Status'}}
Many thanks!
Point's y coordinate in series' data must be a number, so you would have to process your data to have it in required format. It would be for the best to do this server side and provide proper data for JS, but if that is not possible then you could process data in JS.
$(function() {
var data = ['ON', 'OFF', 'OFF', 'ON'],
processedData = [];
Highcharts.each(data, function(point) {
processedData.push(point === 'ON' ? 1 : 0);
});
$('#container').highcharts({
'yAxis': {
'categories': ['ON', 'OFF'],
'title': {
'text': 'Status'
}
},
series: [{
data: processedData
}]
});
});
Example: http://jsfiddle.net/ptu6qhjy/
Related
I have 3 selectable item on my UI.
I created these with ListViewBuilder. My goal is upload the selectedItem's to Firebase. Anyway, in example;
List<Map<String?, dynamic>> selectedItems = List.empty(growable: true);
List is gonna be like this right before uploading Firebase:
List selectedItems = [
{
'title': selectedItem[index].title,
'price': selectedItem[index].price,
},
];
This has to be my selectedItems list.
And I upload this list as Map like this:
Map<String, dynamic> updatedData = {'items': selectedItems};
This has to be like this in order to Firebase design.
First of all when the user has clicked to item I want to check selectedItems list.
Here is my code but it doesn't work at all:
if (selectedServices.contains(
[{
'title': selectedItem[index].title,
'price': selectedItem[index].price,
}])
The problem is right up here. After this check (also it's always passing because not working) I try to remove same items from selectedItems with this code:
selectedServices.removeWhere((item) => mapEquals(
item,
({
'title': selectedItem[index].title,
'price': selectedItem[index].price,
})));
But it doesn't work too because of the check always passing false. After these steps, my onPressed function working just on this else code bloc.
else
{
selectedServices.addAll([{
selectedItem[index].title:
selectedItem[index].price
}
]);}
A little summary;
.contains method not working like this. If there is another way to set list of maps, just let me learn that. This is important for me but I can't figure it out last few days.
And lastly, can you explain answer how it works for Dart ?
Edit: Focus of the question changed, so this answer now tries to achieve a contains like functionality for lists with complex items.
For a custom equality check a similar functionality to contains can be achieved via any:
import 'package:collection/equality.dart';
void main() {
final map1 = {
'title': 'item1',
'price': 12.34,
};
final map2 = {
'title': 'item2',
'price': 3.45,
};
final list = [map1, map2];
final test1 = list.any((item)=>MapEquality().equals(item, {
'title': 'item1',
'price': 12.34,
}));
print(test1);
final test2 = list.any((item)=>MapEquality().equals(item, {
'title': 'item3',
'price': 14.34,
}));
print(test2);
}
print is:
true
false
you could run into precision issues with doubles, though, or if you are using complex key-value pairs in your maps.
Don't you try to check if array contains other array in this code:
if (selectedServices.contains(
[{
'title': selectedItem[index].title,
'price': selectedItem[index].price,
}])
?
Try to check with one item in parameter-list:
if (selectedServices.contains(
{'title': selectedItem[index].title}
))
I wanted to create a graph which contains a Time Cartesian axis. The docs tell me that I need to use an adapter for a type: 'time' axis. I chose chartjs-adapter-date-fns, and imported it using the following cdn:
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
Now the docs tell me an object must be passed as the adapters.date property of an axis id. But which class/object should I put there? I'm stuck here. Can anyone point me in the right direction?
I'm using ChartJS 3.4.1 and Chartisan.
x: {
adapters: {
date: {
// Adapter object here.
}
},
type: 'time',
time: {
unit: 'day'
},
},
Many thanks in advance!
The documentation for chartjs-adapter-date-fns states:
date-fns requires a date-fns locale object to be tagged on to each format() call, which requires the locale to be explicitly set via the adapters.date option
And gives the following example:
// import date-fns locale:
import {de} from 'date-fns/locale';
// scale options:
{
adapters: {
date: {
locale: de
}
}
}
Hopefully not too late, but just in case: I grappled with this, too, and in the end found that you can simply feed chartjs with time scale integers as x values. Convert your timestamps to seconds since the epoch and multiply by 1000, because js uses milliseconds whereas unix uses seconds.
My code is in python, so I convert the timestamp string to milliseconds since the epoch, fist:
# get data from backend
hist = self.backend_get(f"/{name}/history")
# convert format for chart, filter out None
data_l = [{'x' : 1000*int(datetime.fromisoformat(d['timestamp']).strftime('%s')),
'y' : d['value']} for d in hist if d['value'] is not None]
label = "<insert your label>"
Now construct the data
data = {
'type': 'line',
'data': {
'labels': [],
'datasets': [{
'label': label,
'data': data_l,
}]
},
'options': {
'scales': {
'x': {
'type': 'time',
'time': {'unit': 'day'},
},
},
},
}
Finally insert the charts js and canvas into the html:
html_s += '''
<div>
<canvas id="myChart" class="history_canvas"></canvas>
</div>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx,
'''
html_s += f'{data}'
html_s += '''
);
</script>
<h3>Raw data</h3>
'''
PS I think this only works in Unix because of the epoch.
Nevermind, just adding the cdn was sufficient. The problem was that the labels weren't in date format but in relative time instead ("2 hours ago" instead of 20-07-2021)
I'm going to put an item in two dynamodb tables. This is my request params of BatchWriteItem operation.
RequestItems: {
first_table: [{
PutRequest: {
Item: {
employee_id: '123',
company_id: '123',
job_position: 'manager'
}
}
}],
second_table: [{
PutRequest: {
Item: {
facility_id: '123',
company_id: '123',
job_position: 'manager'
}
}
}]
},
ReturnConsumedCapacity: "TOTAL"
My item is updated succefully but I get this response -
UnprocessedItems: {}
How can I get response with updated data? Thanks
Its not possible to get a response containing the items you have put using BatchWriteItem. PutItem can return overwritten values, but not new ones.
You might consider:
1) Using the data you already have. Afterall, you know the items have been written and you already have them.
2) If you want some statistics on your batchwrite you could use
"ReturnItemCollectionMetrics": "SIZE"
3) Query for the items after you have written them.
I'am writing an application for budget management and i am using angular-chart.js.
i want to use a dataset to override the initial data(mainly to add new data to the graph and give diffrent color for each bar,label etc.)and set label and colors according to the value of the data.
currently,i tried to do that hard coded but only the first value is being override.
here is the code i am using :
angular.module("app2", ["chart.js"]).controller("MixedChartCtrl",
function($scope) {
$scope.colors = ['#45b7cd', '#ff6384', '#ff8e72'];
$scope.labels = ['', ''];
$scope.data = [65, 11];
$scope.datasetOverride = [
{
label: 'Override Series A',
borderWidth: 1,
type: 'bar',
data: [345]
},
{
label: "Bar chart1",
borderWidth: 1,
type: 'bar',
data: [45]
}
];
});
Hoping that yourquestion is, you want a fill color/label/something to each individual data (for each bar).
Above (your) code snippet is used when you have two data sets.
All these dataset properties will accept String when the same property value has to set for all data, and they will also accept Array[String] - when you want to set different property values for different data in the same dataset. (like below).
$scope.data = [65,11];
$scope.datasetOverride = [
{
label: ['something', 'otherthing'],
borderWidth: [1,2],
backgroundColor: ['#FF4242','#2291ff']
}
]
so now I understood that you might be adding dynamically data.
so you have to push data into DATASET something like this:
$scope.data.push(345);
So if you want to set different properties for these you need to push the properties (arrays).
$scope.datasetOverride[0][label].push('someother thing');
$scope.datasetOverride[0][borderWidth].push(2);
$scope.datesetOverride[0][backgroundColor].push('#46bfb8');
This will add a bar with new color/label/etc beside the previous bars.
I hope I understood your question and this will help.
I'm trying to generate a jqgrid which populates from a JSON feed, being output from a django backend.
The python handling the request is as follows:
from django.http import HttpResponse
from django.utils import simplejson
def json_test(request):
results = {'total':'1',
'page':'1',
'records':'2',
'rows':[{'id':'1','field1':'blah','field2':'bleh'},
{'id':'2','field1':'bloo','field2':'blum'}]}
json = simplejson.dumps(results)
return HttpResponse(json, mimetype='application/json')
So going to http://127.0.0.1:8000/json_test/ returns the following:
{"records": "2", "total": "1", "rows": [{"field2": "bleh", "field1": "blah", "id": "1"}, {"field2": "blum", "field1": "bloo", "id": "2"}], "page": "1"}
The jquery code is as follows:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'http://127.0.0.1:8000/json_test/',
datatype: 'json',
mtype: 'GET',
colNames:['field1','field2'],
colModel :[
{name:'field1', width:55},
{name:'field2', width:90},
],
pager: '#pager',
rowNum:10,
rowList:[10,20],
sortname: 'field1',
sortorder: 'desc',
viewrecords: true,
caption: 'Test Grid'
});
});
</script>
On loading the page, the grid renders correctly, and it briefly displays 'loading data', but it then displays no rows.
Any ideas where I've gone wrong? I've tried to strip this back to as simple a case as possible to determine the cause.
According to the jqGrid Documentation, by default the grid expects JSON data in the following format:
{
total: "xxx",
page: "yyy",
records: "zzz",
rows : [
{id:"1", cell:["cell11", "cell12", "cell13"]},
{id:"2", cell:["cell21", "cell22", "cell23"]},
...
]
}
So basically it looks like you need to set an ID for each of your columns. If this is not feasible you would need to specify your own jsonReader.
Additionally, having your total/page/records sections out-of-order might cause problems - if you still have trouble after adding the ID's then this would be the next thing to look at.
Solved - I put the html page inside the django app, so that the jqgrid url became just url:'/json_test/' and then it worked. Must be something harcoded into jqgrid that only permits local urls?
try this...
loadError: function(xhr,status,error){alert(status+" "+error);}