I am create eclipse RCP application and use SWT table and i am trying to ascending descending column value but not working in column shell value is not change so please help me.
my column value (cell value) is combo box , how to sort column combo value in my table.
public static void main(String[] args) {
int size = 5;
Random random = new Random();
final int[][] data = new int[size][];
for (int i = 0; i < data.length; i++) {
data[i] = new int[] { i, random.nextInt() };
}
// create a virtual table to display data
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Table table = new Table(shell, SWT.VIRTUAL);
table.setHeaderVisible(true);
table.setLinesVisible(true);
table.setItemCount(size);
final TableColumn column1 = new TableColumn(table, SWT.NONE);
column1.setText("Key");
column1.setWidth(200);
final TableColumn column2 = new TableColumn(table, SWT.NONE);
column2.setText("Value");
column2.setWidth(200);
table.addListener(SWT.SetData, new Listener() {
public void handleEvent(Event e) {
TableEditor fd_editor = new TableEditor(table);
fd_editor.grabHorizontal = true;
CCombo combo = new CCombo(table, SWT.CHECK);
combo.add("ABC");
combo.add("XYZ");
combo.add("PQR");
combo.add("BABA");
combo.add("PAVAN");
combo.add("RAJA");
combo.select(1);
TableItem item = (TableItem) e.item;
int index = table.indexOf(item);
int[] datum = data[index];
item.setText(0, Integer.toString(datum[0]));
fd_editor.setEditor(combo, item, 1);
}
});
// Add sort indicator and sort data when column selected
Listener sortListener = new Listener() {
public void handleEvent(Event e) {
// determine new sort column and direction
TableColumn sortColumn = table.getSortColumn();
TableColumn currentColumn = (TableColumn) e.widget;
int dir = table.getSortDirection();
if (sortColumn == currentColumn) {
dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
} else {
table.setSortColumn(currentColumn);
dir = SWT.UP;
}
// sort the data based on column and direction
final int index = currentColumn == column1 ? 0 : 1;
final int direction = dir;
Arrays.sort(data, new Comparator() {
public int compare(Object arg0, Object arg1) {
int[] a = (int[]) arg0;
int[] b = (int[]) arg1;
if (a[index] == b[index])
return 0;
if (direction == SWT.UP) {
return a[index] < b[index] ? -1 : 1;
}
return a[index] < b[index] ? 1 : -1;
}
});
// update data displayed in table
table.setSortDirection(dir);
table.clearAll();
}
};
column1.addListener(SWT.Selection, sortListener);
column2.addListener(SWT.Selection, sortListener);
table.setSortColumn(column1);
table.setSortColumn(column2);
table.setSortDirection(SWT.DOWN);
shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 500);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
Related
We tried of using TimerPickerDialog with Number Picker in Xamarin android. Since we have time interval of 15mins
In Android 10 - getMinute() is returning Null
var classForid = Java.Lang.Class.ForName("com.android.internal.R$id");
var timePickerField = classForid.GetField("timePicker");
[![timePicker][1]][1] = (TimePicker)FindViewById(timePickerField.GetInt(null));
var field = classForid.GetField("minute");
NumberPicker minuteSpinner = (NumberPicker)timePicker
.FindViewById(field.GetInt(null));
minuteSpinner.MinValue = 0;
minuteSpinner.MaxValue = (60 / TimePickerInterval) - 1;
List<string> displayedValues = new List<string>();
for (int i = 0; i < 60; i += TimePickerInterval)
{
displayedValues.Add(i.ToString());
}
minuteSpinner.SetDisplayedValues(displayedValues.ToArray());
We need to get the Minute picker. Screenshot:
Try to create a custom TimePickerDialog ,here is a simple sample,you could check it:
create CustomTimePickerDialog :
public class CustomTimePickerDialog : TimePickerDialog
{
private int _interval = 1;
public CustomTimePickerDialog(Context context, EventHandler<TimeSetEventArgs> callBack, int hourOfDay, int minute, bool is24HourView, int interval)
: base(context, ThemeHoloLight, (sender, e) =>
{
callBack(sender, new TimeSetEventArgs(e.HourOfDay, e.Minute * interval));
}, hourOfDay, minute / interval, is24HourView)
{
_interval = interval;
FixSpinner(context, hourOfDay, minute, is24HourView);
}
protected CustomTimePickerDialog(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void SetView(Android.Views.View view)
{
base.SetView(view);
}
void SetupMinutePicker(Android.Views.View view)
{
var numberPicker = FindMinuteNumberPicker(view as ViewGroup);
if (numberPicker != null)
{
int i = _interval;
List<string> values = new List<string>();
values.Add("00");
while (i < 60)
{
if (i < 10)
values.Add("0" + i);
else
values.Add(i.ToString());
i += _interval;
}
numberPicker.MinValue = 0;
numberPicker.MaxValue = values.Count - 1;
numberPicker.SetDisplayedValues(values.ToArray());
}
}
protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
GetButton((int)DialogButtonType.Negative).Visibility = Android.Views.ViewStates.Gone;
this.SetCanceledOnTouchOutside(false);
}
private NumberPicker FindMinuteNumberPicker(ViewGroup viewGroup)
{
for (var i = 0; i < viewGroup.ChildCount; i++)
{
var child = viewGroup.GetChildAt(i);
var numberPicker = child as NumberPicker;
if (numberPicker != null)
{
if (numberPicker.MaxValue == 59)
{
return numberPicker;
}
}
var childViewGroup = child as ViewGroup;
if (childViewGroup != null)
{
var childResult = FindMinuteNumberPicker(childViewGroup);
if (childResult != null)
return childResult;
}
}
return null;
}
private void FixSpinner(Context context, int hourOfDay, int minute, bool is24HourView)
{
try
{
// Get the theme's android:timePickerMode
int MODE_SPINNER = 1;
var styleableClass = Java.Lang.Class.ForName("com.android.internal.R$styleable");
var timePickerStyleableField = styleableClass.GetField("TimePicker");
int[] timePickerStyleable = (int[])timePickerStyleableField.Get(null);
var a = context.ObtainStyledAttributes(null, timePickerStyleable, Android.Resource.Attribute.TimePickerStyle, 0);
var timePickerModeStyleableField = styleableClass.GetField("TimePicker_timePickerMode");
int timePickerModeStyleable = timePickerModeStyleableField.GetInt(null);
int mode = a.GetInt(timePickerModeStyleable, MODE_SPINNER);
a.Recycle();
Android.Widget.TimePicker timePicker = (Android.Widget.TimePicker)findField(Java.Lang.Class.FromType(typeof(TimePickerDialog)), Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), "mTimePicker").Get(this);
var delegateClass = Java.Lang.Class.ForName("android.widget.TimePicker$TimePickerDelegate");
var delegateField = findField(Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), delegateClass, "mDelegate");
var delegatee = delegateField.Get(timePicker);
Java.Lang.Class spinnerDelegateClass;
if (Build.VERSION.SdkInt != BuildVersionCodes.Lollipop)
{
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerSpinnerDelegate");
}
else
{
// TimePickerSpinnerDelegate was initially misnamed TimePickerClockDelegate in API 21!
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerClockDelegate");
}
// In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
if (delegatee.Class != spinnerDelegateClass)
{
delegateField.Set(timePicker, null); // throw out the TimePickerClockDelegate!
timePicker.RemoveAllViews(); // remove the TimePickerClockDelegate views
var spinnerDelegateConstructor = spinnerDelegateClass.GetConstructors()[0];
spinnerDelegateConstructor.Accessible = true;
// Instantiate a TimePickerSpinnerDelegate
delegatee = spinnerDelegateConstructor.NewInstance(timePicker, context, null, Android.Resource.Attribute.TimePickerStyle, 0);
delegateField.Set(timePicker, delegatee); // set the TimePicker.mDelegate to the spinner delegate
// Set up the TimePicker again, with the TimePickerSpinnerDelegate
timePicker.SetIs24HourView(Java.Lang.Boolean.ValueOf(is24HourView));
timePicker.Hour = hourOfDay;
timePicker.Minute = minute;
timePicker.SetOnTimeChangedListener(this);
}
// set interval
SetupMinutePicker(timePicker);
}
catch (Exception e)
{
throw new Java.Lang.RuntimeException(e.ToString());
}
}
private static Java.Lang.Reflect.Field findField(Java.Lang.Class objectClass, Java.Lang.Class fieldClass, String expectedName)
{
try
{
var field = objectClass.GetDeclaredField(expectedName);
field.Accessible = true;
return field;
}
catch (Java.Lang.NoSuchFieldException e) { } // ignore
// search for it if it wasn't found under the expected ivar name
foreach (var searchField in objectClass.GetDeclaredFields())
{
if (Java.Lang.Class.FromType(searchField.GetType()) == fieldClass)
{
searchField.Accessible = true;
return searchField;
}
}
return null;
}
}
call like this:
CustomTimePickerDialog timePickerDlg = new CustomTimePickerDialog(this, new EventHandler<TimePickerDialog.TimeSetEventArgs>((o,e)=> { }),
hourOfDay, minute, true,15);// the 15 is the minute interval
timePickerDlg.Show();
I have a set of items that I would like to bucket into N different buckets. Each item has a property associated with it (size) and I would like the sum of this property in each bucket to be roughly equal. What is the best way to determine this? Note the range of the size on the items is fairly large, in the data set I'm using the smallest size is 1 and the largest is 325,220.
Example:
Item A - size 5
Item B - size 10
Item C - size 8
Item D - size 16
Item E - size 7
If I wanted to group these into 3 buckets I would want
Bucket 1: A, B
Bucket 2: C, E
Bucket 3: D
I ended up implementing the complete greedy algorithm described in the paper linked by Joe Farrel. The full C# code I used is below:
public class Item
{
public int Id { get; }
public int Size { get; }
public Item(int id, int size)
{
Id = id;
size = size;
}
}
public class Partition
{
public int Index { get; }
public ImmutableList<Item> Items { get; } = ImmutableList<Item>.Empty;
public int Sum { get; }
public Partition(int index)
{
Index = index;
}
private Partition(int index, ImmutableList<Item> items, int sum)
{
Index = index;
Item = items;
Sum = sum;
}
public Partition Add(Item item) => new Partition(Index, Items.Add(item), Sum + item.Size);
public static double AverageDifference(ImmutableList<Partition> partitions)
{
var differences = new List<int>();
for (var i = 0; i < partitions.Count; i++)
{
var partition = partitions[i];
var otherPartitions = partitions.RemoveAt(i);
foreach (var otherPartition in otherPartitions)
{
differences.Add(Math.Abs(partition.Sum - otherPartition.Sum));
}
}
return differences.Average();
}
}
public class Node
{
public Item Item { get; set; }
public int Partition { get; set; }
public Node[] Children { get; set; }
}
private (Node tree, int totalSum) InitTree(IEnumerable<Item> items)
{
var root = new Node();
var totalSum = 0;
Node[] previousLevel = {root};
foreach (var item in items.OrderByDescending(i => i.Size))
{
totalSum += item.Size;
var currentLevel = new Node[_numPartitions];
for (var i = 0; i < _numPartitions; i++)
{
currentLevel[i] = new Node
{
Item = item,
Partition = i
};
}
foreach (var node in previousLevel)
{
node.Children = currentLevel;
}
previousLevel = currentLevel;
}
return (root, totalSum);
}
private ImmutableList<Partition> GetPartitions(Node tree, int totalSum)
{
var partitions = ImmutableList<Partition>.Empty;
for (var i = 0; i < _numPartitions; i++)
{
partitions = partitions.Add(new Partition(i));
}
return TraverseTree(tree, partitions, totalSum, double.MaxValue, ImmutableList<Partition>.Empty);
}
private ImmutableList<Partition> TraverseTree(Node node, ImmutableList<Partition> partitions, int totalSum, double bestDifference, ImmutableList<Partition> bestPartitions)
{
var currentPartitions = partitions;
if (node.Item != null) // skip root
{
// place item into its partition
var updatedPartition = currentPartitions[node.Partition].Add(node.Item);
currentPartitions = currentPartitions.SetItem(node.Partition, updatedPartition);
}
// if this is a leaf, partition is complete
if (node.Children == null)
{
return currentPartitions;
}
// terminate path if partition is sufficiently bad
var largestSum = currentPartitions.Max(p => p.Sum);
if (largestSum - (totalSum - largestSum) / (_numPartitions - 1) >= bestDifference)
{
return null;
}
// contintue to traverse tree in ascending partition size order
foreach (var partition in currentPartitions.OrderBy(p => p.Sum))
{
var nextNode = node.Children[partition.Index];
var nextPartitions = TraverseTree(nextNode, currentPartitions, totalSum, bestDifference, bestPartitions);
if (nextPartitions == null) // path was terminated
{
continue;
}
// if we hit a perfect parition set, return it
var nextDifference = Partition.AverageDifference(nextPartitions);
if (nextDifference <= 1)
{
return nextPartitions;
}
// hold on to the best partition
if (nextDifference < bestDifference)
{
bestDifference = nextDifference;
bestPartitions = nextPartitions;
}
}
return bestPartitions;
}
_numPartitions = 4
var items = GetItems()
var (tree, totalSum) = InitTree(items);
var partitions = GetPartitions(tree, totalSum);
My answer to this question on laying out pictures might be able to be adapted.
Pictures with height become items with size. Columns per page becomes buckets.
The algorithm has three parts: first-fit; greedy-swapping; and reverse sorting, some may be of more use than others with your data.
Here is my for loop, is my for loop wrong? I have not been doing loops for a very long time so I am still a beginner and I would really appreciate if someone could take a look at my problem.
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
tab.setCustomView(mSectionsPagerAdapter.getTabView(i));
}else{
System.out.println("ERROR---TAB IS NULL---ERROR");
}
}
and here is my Count Method and Char
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
// return tabTitles[position];
// getDrawable(int i) is deprecated, use getDrawable(int i, Theme theme) for min SDK >=21
// or ContextCompat.getDrawable(Context context, int id) if you want support for older versions.
// Drawable image = context.getResources().getDrawable(iconIds[position], context.getTheme());
// Drawable image = context.getResources().getDrawable(imageResId[position]);
Drawable image = ContextCompat.getDrawable(MainActivity.this, imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
I am using RadControls for WinForms 2011 Q3
The datasource for a RadGridView is dynamically generated based on users' input/selection
Everytime when a datasource is generated, I will call SetDatasource2KeyValuesGrid()
What I expect to see is columns generated and values filled in gridview.
However what I see is columns generated but no value filled even though the number of rows in gridview match the number of items in its datasource(keyValuesList)
I must have missed something simple. Please help. thanks
Edit:
I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
Just wonder if there's a better way. thanks
private void CreateTableSetDatasource(List<FeedKeyValueOneSet>) keyValueList)
{
if(keyValueList==null) return;
var table = new DataTable();
table.Columns.Add("Check");
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
table.Columns.Add(oneKey.key);
}
break;
}
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
var numOfCol = oneset.Length + 1;
var obj = new object[numOfCol];
obj[0] = "false";
int idx = 1;
foreach (var oneKey in oneset)
{
obj[idx] = oneKey.value;
idx++;
}
table.Rows.Add(obj);
}
radGridKeyValues.DataSource = table;
}
private void SetDatasource2KeyValuesGrid()
{
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Clear();
radGridKeyValues.AutoGenerateColumns = false;
radGridKeyValues.EnableFiltering = false;
radGridKeyValues.ShowFilteringRow = false;
radGridKeyValues.ShowHeaderCellButtons = false;
radGridKeyValues.AllowDragToGroup = false;
radGridKeyValues.AllowAddNewRow = false;
radGridKeyValues.EnableGrouping = false;
var keyValueList = (List<FeedKeyValueOneSet>)TimeSeries.FeedValuesCache[m_strFeedName + "_KEYVALUES"];
if(keyValueList==null) return;
GridViewDataColumn checkBoxColumn = new GridViewCheckBoxColumn("columnState", "columnState");
checkBoxColumn.HeaderText = string.Empty;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(checkBoxColumn);
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
var textboxCol = new GridViewTextBoxColumn(oneKey.key, oneKey.key);
textboxCol.Width = 150;
textboxCol.ReadOnly = true;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(textboxCol);
}
break;
}
radGridKeyValues.DataSource = keyValueList;
}
public class FeedKeyValueOneSet
{
public FeedFieldValues[] KeyValueOneSet;
}
public class FeedFieldValues
{
public string key { get; set; }
public string value { get; set; }
}
I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
see code in edit to the question
Please help me, how I can find the highest number in each column and format it to make it Bold.
Please use this approch.
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
string[] numericColumns = { "OrderID", "Freight", "Freight1", "Freight2" };
foreach (string uniqueName in numericColumns)
{
int index = -1;
decimal maxNumber = decimal.MinValue;
foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
{
decimal currentNumber = decimal.Parse(dataItem[uniqueName].Text);
if (currentNumber > maxNumber)
{
maxNumber = currentNumber;
index = dataItem.ItemIndex;
}
}
if (index >= 0)
{
GridTableCell cell = (RadGrid1.Items[index] as GridDataItem)[uniqueName] as GridTableCell;
cell.BackColor = System.Drawing.Color.LightBlue;
}
}
}
Hope this will work for you.