GWT-Charts ColumnFunction not working? - gwt

I just want to make sure I'm not doing something wrong before I file a bug/start digging in GWT-Charts code...
Trying to style a LineChart:
DataViewColumn ret = DataViewColumn.create(new ColumnFunction() {
#Override
public Object calc(DataTable dataTable, int row) {
if (dataTable.isValueNull(i, dataColumn)
|| dataTable.getValueNumber(i, dataColumn) < value) {
return "color: red";
}
return "color: green";
}
}, ColumnType.STRING);
ret.setRole(RoleType.STYLE);
(I had to add RoleType.STYLE myself, custom-built 0.9.11-SNAPSHOT off Master)
But adding that column results in (using new JSONObject(columns)):
{
"0":{"sourceColumn":0},
"1":{"sourceColumn":1, "label":"Data"},
"2":{"calc":{}, "type":"string", "role":"style"}
}
Note the empty set for "calc"?
I tried just doing a ColumnFunction for Data (returning a flat value) in case the "style" Role required more than just adding to the RoleType Enum, and that also doesn't seem to be getting passed through.
The JSNI in DataViewColumn.setCalc(ColumnFunction) seems to be right to me, so I'm not sure where the issue lies...
UPDATE:
Putting debugging statements in the ColumnFunction showed it to be running, but the output didn't seem to be getting used.
Turns out that DataViewColumn.setCalc was missing the return statement in its JSNI wrapper.

DataViewColumn.setCalc:
/**
* Sets a function that will be called for each row in the column to calculate a value for that cell.
*
* #param columnFunction a function for calculating each row value
*/
public final native void setCalc(ColumnFunction columnFunction) /*-{
this.calc = function(dataTable, row) {
columnFunction.#com.googlecode.gwt.charts.client.ColumnFunction::calc(Lcom/googlecode/gwt/charts/client/DataTable;I) (dataTable, row);
};
}-*/;
Was not returning the value calculated by the function, just calculating it.
Adding "return" to the line in the innermost block fixes the issue.

Related

GetKeyDown always returning true resulting stackoverflow

I am wrapping up GetKeyDown into a function as below:
class PlayerInputHandler{
public static bool TestPInput()
{
bool k = GetKeyDown(KeyCode.P);
return k;
}
}
and calling in a update function as
void HandleTestInput()
{
if (PlayerInputHandler.TestPInput())
{
Debug.Log("Pressed p");
HandleTestInput();
}
}
In my Update as:
void Update()
{
HandleTestInput();
}
Q1. How is this going into an infinite Loop ?
as I have strictly given the condition
if (PlayerInputHandler.TestPInput())
Also how can this always return true ?
as on the next call, it should be rechecking the input right?
Input.GetKeyDown
Returns true during the frame the user starts pressing down the key identified by the key KeyCode enum parameter.
This means as long as you are in the same frame this still returns true!
Your issue has little to do with the input itself but rather the fact that HandleTestInput is calling HandleTestInput and between these two calls no frame passes
=> There is no way that GetKeyDown returns a different value within the same frame.
This is not really an infinite loop though, but rather will throw a StackOverflowException after enough recursion.
If you rather actually wanted to do something while the key stays pressed you rather want to use Input.GetKey
Returns true while the user holds down the key identified by the key KeyCode enum parameter.
like e.g.
class PlayerInputHandler
{
public static bool TestPInput()
{
return GetKey(KeyCode.P);
}
}
and then
private void HandleTestInput()
{
if(PlayerInputHandler.TestPInput())
{
// In general do NOT log something every frame!
Debug.Log("p is pressed");
}
}

What Is the Proper Way to Handle Calculated Properties in an Object?

From what I can tell, there are two main ways to accomplish this:
Option 1: Calculate each property "on demand" via their getter method (e.g.
getTotal()).
Option 2: Populate all calculated properties on construction and any time a public property changes by using a
generic calculate() method.
I created two examples using a simple insurance policy object. Each class initializes with a few properties like premiumRateBase, brokerFee, termYears, effectiveDate, and agentCommissionRate. The calculated columns would be things like the prorated premiumRate, total, or agentCommission.
Here's an example of option 1:
component {
// public properties (getters + setters)
property name="premiumRateBase";
property name="brokerFee";
property name="effectiveDate";
property name="termYears";
property name="agentCommissionRate";
function init(
required numeric premiumRateBase,
required numeric brokerFee,
required date effectiveDate,
required numeric termYears,
required numeric agentCommissionRate
) {
// setters
...
return this;
}
function getExpirationDate() {
return dateAdd( 'yyyy', effectiveDate, termYears );
}
function getPremiumRate() {
// run proration and calcuation determination
// based on premiumRateBase, getExpirationDate(), and maybe a few other methods
...
return premiumRate;
}
function getTotal() {
return getPremiumRate() + brokerFee;
}
function getAgentCommission() {
return getPremiumRate() * agentCommissionRate
}
function getAgentCompensation() {
return getAgentCommission() + brokerFee
}
}
In the above example, the calculations are run any time you call a method like getTotal(). The advantage of this approach is that the code is pretty straightforward. The disadvantage of this approach is that if needed to run getTotal(), getAgentCommission() and then getAgentCompensation(), you wind up running a lot of redundant math. For this example, it wouldn't equate to much additional processing time, but in a more complex example, I could see this adding up.
Here's an example of option 2:
component {
// public properties (getters + setters)
property name="premiumRateBase";
property name="brokerFee";
property name="effectiveDate";
property name="termYears";
property name="agentCommissionRate";
function init(
required numeric premiumRateBase,
required numeric brokerFee,
required date effectiveDate,
required numeric termYears,
required numeric agentCommissionRate
) {
// setters
...
// run the calculation
calculate();
return this;
}
// primary calculation method which sets all private properties
function calculate() {
variables.expirationDate = calculateExpirationDate();
variables.premiumRate = calculatePremiumRate();
variables.total = calculateTotal();
variables.agentCommission = calculateAgentCommission();
}
/***************************
Public Getters
***************************/
function getExpirationDate() {
return expirationDate;
}
function getPremiumRate() {
return premiumRate;
}
function getTotal() {
return total;
}
function getAgentCommission() {
return agentCommission;
}
/***************************
Private Calculations
***************************/
private function calculateExpirationDate() {
return dateAdd( 'yyyy', effectiveDate, termYears );
}
private function calculatePremiumRate() {
// run proration and calcuation determination
// based on premiumRateBase, expirationDate and maybe a few other variables
...
return premiumRate;
}
private function calculateTotal() {
return premiumRate + brokerFee;
}
private function calculateAgentCommission() {
return premiumRate * agentCommissionRate;
}
private function calculateAgentCompensation() {
return agentCommission + brokerFee;
}
}
In the second example, we only run a generic calculate() method after the constructor method init() fires. I didn't include this, but you would also need to run calculate() again if you ever update any of the public properties through their setter methods. The advantage of this approach is that the calculation math only occurs when the properties change. The downside is that the code seems a little more convoluted and harder to read.
What is the best-practices or proper approach to solving this type of problem?
It is a common dilemma and ultimately it resolves to the cost of recalculating the property every time. If it is cheap, I would always prefer getter approach.
Another dimension to think about is staleness of calculated property. Option #2 performs calculation only upon initialisation and possibly the properties involved in calculation may change afterwards. The calculated metric will be stale now. You can fix it by recalculating metrics on modification. This will further increase the complexity of code. If this modification isn't well encapsulated, recalculation responsibility will be shared with caller too!
In summary, for cheap calculations I would prefer option #1 and for complex calculations, I would first encapsulate modifications to ensure recalculation on each update.

TextCellEditor with autocomplete in Eclipse SWT/JFace?

I'd like a TextCellEditor with the standard auto-complete behaviour, that that any user nowadays expects when typing inside an input cell with a list of suggested strings. For a good working example of what I'm after, in Javascript, see this jQuery autocomplete widget.
I couldn't find a good example.
I only found (aside from some tiny variations) this TextCellEditorWithContentProposal snippet. But that leaves a lot to be desired:
It lists all the words, irrespective of the "partial word" typed in the cell (no partial matching)
When the desired word is selected, it is appended to the partial word, instead of replacing it
The interaction is ugly and non-intuitive. For example, one would expect the
Escape key to tear off the list of suggestions; again, see the Javascript example; here, it also removes the typed letters.
It looks strange to me that such an standard and useful component is not available. Or perhaps it is available? Can someone point to me to a more apt snippet or example?
The example you are linking to is a code snippet intended to showcase the API and guide you toward customizing the control to your preference.
Some of your complaints are either invalid or can easily be fixed using public API.
Let's go through them in detail.
All proposals are listed, irrespective of typed text
Note that in the snippet an org.eclipse.jface.fieldassist.SimpleContentProposalProvider is used:
IContentProposalProvider contentProposalProvider = new SimpleContentProposalProvider(new String[] { "red",
"green", "blue" });
cellEditor = new TextCellEditorWithContentProposal(viewer.getTable(), contentProposalProvider, null, null);
As suggested in its javadoc it is:
designed to map a static list of Strings to content proposals
To enable a simple filtering of the contents for the snippet, you could call: contentProposalProvider.setFiltering(true);
For anything more complex you will have to replace this with your own implementation of org.eclipse.jface.fieldassist.IContentProposalProvider.
Selection is appended to cell contents, instead of replacing it
The content proposal behavior is defined in the org.eclipse.jface.fieldassist.ContentProposalAdapter. Again a simple method call to org.eclipse.jface.fieldassist.ContentProposalAdapter.setProposalAcceptanceStyle(int) will achieve your target behavior:
contentProposalAdapter = new ContentProposalAdapter(text, new TextContentAdapter(), contentProposalProvider, keyStroke, autoActivationCharacters);
contentProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
Cancelling the proposal should not remove typed content
This is hard to do using just the API, since the ContentProposalAdapter does only propagate the key strokes to the opened ContentProposalPopup without storing them.
You would have to subclass ContentProposalAdapter, in order to have access to ContentProposalAdapter.ContentProposalPopup.filterText.
Most of the functionality in this snippet with sensible defaults can also be obtained in a more simple way by using an org.eclipse.jface.fieldassist.AutoCompleteField.
Here is a snippet showing you a simple implementation. You have to customize it but it give you the way.
Note, this is not a generic copy/paste of the documentation or an explanation about the doc.
String[] contentProposals = {"text", "test", "generated"};
// simple content provider based on string array
SimpleContentProposalProvider provider = new SimpleContentProposalProvider(contentProposals);
// enable filtering or disabled it if you are using your own implementation
provider.setFiltering(false);
// content adapter with no keywords and caracters filtering
ContentProposalAdapter adapter = new ContentProposalAdapter(yourcontrolswt, new TextContentAdapter(), provider, null, null);
// you should not replace text content, you will to it bellow
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_IGNORE);
// now just put your implementation
adapter.addContentProposalListener(new IContentProposalListener() {
#Override
public void proposalAccepted(IContentProposal proposal) {
if(proposal != null && StringUtils.isNotBlank(proposal.getContent())){
// you need filter with blank spaces
String contentTextField = getFilterControl().getText();
String[] currentWords = getFilterControl().getText().split(" ");
StringBuilder textToDisplay = new StringBuilder();
if(currentWords.length > 1) {
// delete and replace last word
String lastWord = currentWords[currentWords.length-1];
textToDisplay.append(contentTextField.substring(0, contentTextField.length()-1-lastWord.length()));
textToDisplay.append(" ");
}
// add current proposal to control text content
textToDisplay.append(proposal.getContent());
yourcontrolswt.setText(textToDisplay.toString());
}
}
});
If you want more you can also have your own content proposal provider If you need a particular object instead of string or something like.
public class SubstringMatchContentProposalProvider implements IContentProposalProvider {
private List<String> proposals = Collections.emptyList();
#Override
public IContentProposal[] getProposals(String contents, int position) {
if (position == 0) {
return null;
}
String[] allWords = contents.split(" ");
// no words available
if(allWords.length == 0 || StringUtils.isBlank(allWords[allWords.length-1]))
return null;
// auto completion on last word found
String lastWordFound = allWords[allWords.length-1];
Pattern pattern = Pattern.compile(lastWordFound,
Pattern.LITERAL | Pattern.CASE_INSENSITIVE /*| Pattern.UNICODE_CASE*/); // this should be not used for better performances
IContentProposal[] filteredProposals = proposals.stream()
.filter(proposal -> proposal.length() >= lastWordFound.length() && pattern.matcher(proposal).find())
.map(ContentProposal::new).toArray(IContentProposal[]::new);
// no result
return filteredProposals.length == 0 ? null : filteredProposals;
}
public void setProposals(List<String> proposals) {
this.proposals = proposals;
}
}

Entity Framework - Linq to Entities - strange issue with Anonymous function

Following is the code, I am trying:
public List<Movie> GetMovies()
{
Func<Movie, Movie> prepareMovieOutput =
(input) =>
{
input.DisplayHtmlContent = String.Empty;
return input;
};
var moviesOutput = from m in db.Movies.ToList()
select prepareMovieOutput(m);
return moviesOutput.ToList();
}
public List<Movie> SearchMovies(string searchTerm)
{
var moviesOutput = db.Movies.Where(m => m.Name.Contains(searchTerm)).ToList();
return moviesOutput.ToList();
}
The GetMovies function is working properly, as it returns List collection after clearing DisplayHtmlContent field, whereas, SearchMovies function is supposed to return Movie collection with DisplayHtmlContent field, but inspite of that it returns that field empty.
If I set DisplayHtmlContent to some fixed value (like, "ABC"),both GetMovies and SearchMovies return the list with all Movie having DisplayHtmlContent field as "ABC" value. I don't understand why the function defined in one method should affect the other one. and also how to fix this issue?
Ideally, I want GetMovies to hold all Movie with that particular field as empty string, and SearchMovies to hold all Movie with that field containing value.
Any help on this much appreciated.
this was due to the use of repository. I have removed it and it started working fine. with having EF 5, I didn't need to use repository

Zend Framework: is there a way to access the element name from within a custom validator?

I'm writing a custom validator that will validate against multiple other form element values. In my form, I call my custom validator like this:
$textFieldOne = new Zend_Form_Element_Text('textFieldOne');
$textFieldOne->setAllowEmpty(false)
->addValidator('OnlyOneHasValue', false, array(array('textFieldTwo', 'textFieldThree')));
My validator will check that only one of those three fields (textFieldOne, textFieldTwo, textFieldThree) has a value. I want to prevent a future developer from accidentally passing the same field twice.
$textFieldOne->addValidator('OnlyOneHasValue', false, array(array('textFieldOne', 'textFieldTwo', 'textFieldThree')));
So far, my validator works perfectly, except when I pass the same field name as the field that has the valiator set on it.
In my validator, you can see that I am checking that the value (of the element with the validator set on it). I'm also checking the values of the other fields that were passed to the validator.
public function isValid($value, $context = null) {
$this->_setValue($value);
$this->_context = $context;
if ($this->valueIsNotEmpty()) {
if ($this->numberOfFieldsWithAValue() == 0) {
return true;
}
$this->_error(self::MULTIPLE_VALUES);
return false;
}
if ($this->numberOfFieldsWithAValue() == 0) {
$this->_error(self::ALL_EMPTY);
return false;
}
if ($this->numberOfFieldsWithAValue() == 1) {
return true;
}
if ($this->numberOfFieldsWithAValue() > 1) {
$this->_error(self::MULTIPLE_VALUES);
return false;
}
}
private function valueIsNotEmpty() {
return Zend_Validate::is($this->_value, 'NotEmpty');
}
private function numberOfFieldsWithAValue() {
$fieldsWithValue = 0;
foreach ($this->_fieldsToMatch as $fieldName) {
if (isset($this->_context[$fieldName]) && Zend_Validate::is($this->_context[$fieldName], 'NotEmpty')) {
$fieldsWithValue++;
}
}
return $fieldsWithValue;
}
My solution is to either...
A. Let the developer figure out there is a certain way to do it.
B. Ignore $value, forcing you to pass all the elements (which isn't much different than the first option).
or C. (if possible) Find the name of the element that called my validator in the first place and ignore it from the list of $fieldsWithValue.
I don't think there is a way to apply a validator on a form without attaching it to an element, but that would be even better, if it were an option.
How can I solve this problem?
Normaly i'd advise against such things, but, in this case I believe a static member in your class would actually provide a good solution to this problem.
With a static member, you can set it to the value in the first time the isValid is called, and check against it in subsequent calls, thus giving you a mechanism for this.
You may want to set this up to use some array in the configuration options, so that you can namespace and allow multiple instances of the validator to exist happily alongside each other for different sets.
The only problem that you really have to decide how to overcome, is where you wish to display the error, as yes the form itself does not take validators. if you want all the duplicates after the first to display an error, it is not so much of a problem.