When I run the program in debug mode, I receive this error.
Debug Assertion Failed!
Program: ...
File: f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\winhand.cpp
Line: 139
...
And it comes from the following code.
CObject* CHandleMap::FromHandle(HANDLE h)
{
ASSERT(m_pClass != NULL);
ASSERT(m_nHandles == 1 || m_nHandles == 2);
if (h == NULL)
return NULL;
CObject* pObject = LookupPermanent(h);
if (pObject != NULL)
return pObject; // return permanent one
else if ((pObject = LookupTemporary(h)) != NULL)
{
HANDLE* ph = (HANDLE*)((BYTE*)pObject + m_nOffset);
ASSERT(ph[0] == h || ph[0] == NULL);
But I am not able to tell what error it is and how to fix.
I have the following call within "CMyDialog::OnInitDialog()" which causes the failure.
BOOL CMyDialog::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
set_font_weight(IDC_STATIC1_LABEL, FW_BOLD | FW_BLACK);
SetDlgItemText(IDC_STATIC1, L"");
Is it a problem doing these within OnInitDialog? Most specifically, it is "set_font_weight" that causes problem (GetFont()).
void CMyDialog::set_font_weight(int nID, LONG weight)
{
CWnd *pwnd = GetDlgItem(nID);
CFont *pfont = pwnd->GetFont();
LOGFONT lf;
pfont->GetLogFont(&lf);
lf.lfWeight = weight;
pfont->CreateFontIndirect(&lf);
pwnd->SetFont(pfont);
}
Related
I wanted to execute the DeepLearning example by using H2O. But it went wrong when running "DeepLearningV3 dlBody = h2o.train_deeplearning(dlParams);"
The error message:
Illegal argument for field:
hidden of schema:
DeepLearningParametersV3:
cannot convert ""200"" to type int
This is my code, I used the default value of dlParam except "responseColumn". After it went wrong, I added one line to set value of "hidden", but the results didn't change.
private void DL() throws IOException {
//H2O start
String url = "http://localhost:54321/";
H2oApi h2o = new H2oApi(url);
//STEP 0: init a session
String sessionId = h2o.newSession().sessionKey;
//STEP 1: import raw file
String path = "hdfs://kbmst:9000/user/spark/datasets/iris.csv";
ImportFilesV3 importBody = h2o.importFiles(path, null);
System.out.println("import: " + importBody);
//STEP 2: parse setup
ParseSetupV3 parseSetupParams = new ParseSetupV3();
parseSetupParams.sourceFrames = H2oApi.stringArrayToKeyArray(importBody.destinationFrames, FrameKeyV3.class);
ParseSetupV3 parseSetupBody = h2o.guessParseSetup(parseSetupParams);
System.out.println("parseSetupBody: " + parseSetupBody);
//STEP 3: parse into columnar Frame
ParseV3 parseParams = new ParseV3();
H2oApi.copyFields(parseParams, parseSetupBody);
parseParams.destinationFrame = H2oApi.stringToFrameKey("iris.hex");
parseParams.blocking = true;
ParseV3 parseBody = h2o.parse(parseParams);
System.out.println("parseBody: " + parseBody);
//STEP 4: Split into test and train datasets
String tmpVec = "tmp_" + UUID.randomUUID().toString();
String splitExpr =
"(, " +
" (tmp= " + tmpVec + " (h2o.runif iris.hex 906317))" +
" (assign train " +
" (rows iris.hex (<= " + tmpVec + " 0.75)))" +
" (assign test " +
" (rows iris.hex (> " + tmpVec + " 0.75)))" +
" (rm " + tmpVec + "))";
RapidsSchemaV3 rapidsParams = new RapidsSchemaV3();
rapidsParams.sessionId = sessionId;
rapidsParams.ast = splitExpr;
h2o.rapidsExec(rapidsParams);
// STEP 5: Train the model
// (NOTE: step 4 is polling, which we don't require because we specified blocking for the parse above)
DeepLearningParametersV3 dlParams = new DeepLearningParametersV3();
dlParams.trainingFrame = H2oApi.stringToFrameKey("train");
dlParams.validationFrame = H2oApi.stringToFrameKey("test");
dlParams.hidden=new int[]{200,200};
ColSpecifierV3 responseColumn = new ColSpecifierV3();
responseColumn.columnName = "class";
dlParams.responseColumn = responseColumn;
System.out.println("About to train DL. . .");
DeepLearningV3 dlBody = h2o.train_deeplearning(dlParams);
System.out.println("dlBody: " + dlBody);
// STEP 6: poll for completion
JobV3 job = h2o.waitForJobCompletion(dlBody.job.key);
System.out.println("DL build done.");
// STEP 7: fetch the model
ModelKeyV3 model_key = (ModelKeyV3)job.dest;
ModelsV3 models = h2o.model(model_key);
System.out.println("models: " + models);
DeepLearningModelV3 model = (DeepLearningModelV3)models.models[0];
System.out.println("new DL model: " + model);
// STEP 8: predict!
ModelMetricsListSchemaV3 predict_params = new ModelMetricsListSchemaV3();
predict_params.model = model_key;
predict_params.frame = dlParams.trainingFrame;
predict_params.predictionsFrame = H2oApi.stringToFrameKey("predictions");
ModelMetricsListSchemaV3 predictions = h2o.predict(predict_params);
System.out.println("predictions: " + predictions);
// STEP 9: end the session
h2o.endSession();
}
I found the relative source code, but I can't understand why it goes wrong.
This is the definition of hidden.
public class DeepLearningParametersV3 extends ModelParametersSchemaV3 {{
/**
* Hidden layer sizes (e.g. [100, 100]).
*/
public int[] hidden;
//other params
}
And this is the code where the error message showed.It was the line String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName();
static <E> Object parse(String field_name, String s, Class fclz, boolean required, Class schemaClass) {
if (fclz.isPrimitive() || String.class.equals(fclz)) {
try {
return parsePrimitve(s, fclz);
} catch (NumberFormatException ne) {
String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName();
throw new H2OIllegalArgumentException(msg);
}
}
// An array?
if (fclz.isArray()) {
// Get component type
Class<E> afclz = (Class<E>) fclz.getComponentType();
// Result
E[] a = null;
// Handle simple case with null-array
if (s.equals("null") || s.length() == 0) return null;
// Handling of "auto-parseable" cases
if (AutoParseable.class.isAssignableFrom(afclz))
return gson.fromJson(s, fclz);
// Splitted values
String[] splits; // "".split(",") => {""} so handle the empty case explicitly
if (s.startsWith("[") && s.endsWith("]") ) { // It looks like an array
read(s, 0, '[', fclz);
read(s, s.length() - 1, ']', fclz);
String inside = s.substring(1, s.length() - 1).trim();
if (inside.length() == 0)
splits = new String[]{};
else
splits = splitArgs(inside);
} else { // Lets try to parse single value as an array!
// See PUBDEV-1955
splits = new String[] { s.trim() };
}
// Can't cast an int[] to an Object[]. Sigh.
if (afclz == int.class) { // TODO: other primitive types. . .
a = (E[]) Array.newInstance(Integer.class, splits.length);
} else if (afclz == double.class) {
a = (E[]) Array.newInstance(Double.class, splits.length);
} else if (afclz == float.class) {
a = (E[]) Array.newInstance(Float.class, splits.length);
} else {
// Fails with primitive classes; need the wrapper class. Thanks, Java.
a = (E[]) Array.newInstance(afclz, splits.length);
}
for (int i = 0; i < splits.length; i++) {
if (String.class == afclz || KeyV3.class.isAssignableFrom(afclz)) {
// strip quotes off string values inside array
String stripped = splits[i].trim();
if ("null".equals(stripped.toLowerCase()) || "na".equals(stripped.toLowerCase())) {
a[i] = null;
continue;
}
// Quotes are now optional because standard clients will send arrays of length one as just strings.
if (stripped.startsWith("\"") && stripped.endsWith("\"")) {
stripped = stripped.substring(1, stripped.length() - 1);
}
a[i] = (E) parse(field_name, stripped, afclz, required, schemaClass);
} else {
a[i] = (E) parse(field_name, splits[i].trim(), afclz, required, schemaClass);
}
}
return a;
}
// Are we parsing an object from a string? NOTE: we might want to make this check more restrictive.
if (! fclz.isAssignableFrom(Schema.class) && s != null && s.startsWith("{") && s.endsWith("}")) {
return gson.fromJson(s, fclz);
}
if (fclz.equals(Key.class))
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else
return Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s); // If the key name is in an array we need to trim surrounding quotes.
if (KeyV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
if (!required && (s == null || s.length() == 0)) return null;
return KeyV3.make(fclz, Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s)); // If the key name is in an array we need to trim surrounding quotes.
}
if (Enum.class.isAssignableFrom(fclz)) {
return EnumUtils.valueOf(fclz, s);
}
// TODO: these can be refactored into a single case using the facilities in Schema:
if (FrameV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isFrame()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Frame", v.get().getClass());
return new FrameV3((Frame) v.get()); // TODO: version!
}
}
if (JobV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isJob()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Job", v.get().getClass());
return new JobV3().fillFromImpl((Job) v.get()); // TODO: version!
}
}
// TODO: for now handle the case where we're only passing the name through; later we need to handle the case
// where the frame name is also specified.
if (FrameV3.ColSpecifierV3.class.isAssignableFrom(fclz)) {
return new FrameV3.ColSpecifierV3(s);
}
if (ModelSchemaV3.class.isAssignableFrom(fclz))
throw H2O.fail("Can't yet take ModelSchemaV3 as input.");
/*
if( (s==null || s.length()==0) && required ) throw new IllegalArgumentException("Missing key");
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (! v.isModel()) throw new IllegalArgumentException("Model argument points to a non-model object.");
return v.get();
}
*/
throw H2O.fail("Unimplemented schema fill from " + fclz.getSimpleName());
} // parse()
It looks like this could be a bug. A jira ticket has been created for this issue, you can track it here: https://0xdata.atlassian.net/browse/PUBDEV-5454?filter=-1.
I would like to decrease the height of the edit box associated with a CMFCToolbarEditBoxButton on a CMFCToolBar.
I have been able to change successfully the height of a combo box associated with CMFCToolbarComboBoxButton by changing the font size after the ReplaceButton step in OnToolbarReset.
This approach doesn't work for CMFCToolbarEditBoxButton. (see CGuiEditBox section in the following code.)
The first code is from OnToolbarSet. I assign a font to the edit box. I even tried making the size of the font very small. It had no effect.
Next I tried to change the rectangle associated with the edit box in the toolbar's AdjustLocations method. That approach also was unsuccessful.
LRESULT CMainFrame::OnToolbarReset(WPARAM wp, LPARAM)
{
UINT uiToolBarId = (UINT)wp;
switch (uiToolBarId)
{
case IDR_TOPTOOLBAR_REG:
{
CZoomCombo ZoomCombo;
ZoomCombo.EnableWindow(TRUE);
ZoomCombo.SetDropDownHeight(300);
ZoomCombo.SetCenterVert(TRUE);
ZoomCombo.AddItem(_T(".5x"));
ZoomCombo.AddItem(_T("1x"));
ZoomCombo.AddItem(_T("2x"));
ZoomCombo.AddItem(_T("3x"));
ZoomCombo.AddItem(_T("4x"));
ZoomCombo.AddItem(_T("5x"));
ZoomCombo.AddItem(_T("6x"));
ZoomCombo.AddItem(_T("7x"));
ZoomCombo.AddItem(_T("8x"));
ZoomCombo.AddItem(_T("9x"));
ZoomCombo.AddItem(_T("10x"));
m_wndTopToolBar.ReplaceButton(IDC_ZOOMCOMBO_DUMMY, ZoomCombo);
do
{
CMFCToolBarButton* pButton = NULL;
int nZoomIndex = m_wndTopToolBar.CommandToIndex(IDC_ZOOMCOMBO);
if (nZoomIndex == -1)
break;
pButton = m_wndTopToolBar.GetButton(nZoomIndex);
if (pButton == NULL)
break;
ASSERT(pButton->IsKindOf(RUNTIME_CLASS(CMFCToolBarComboBoxButton)));
CMFCToolBarComboBoxButton* pComboButton = (CMFCToolBarComboBoxButton*)pButton;
CComboBox* pCbo = pComboButton->GetComboBox();
CEdit* pEdit = pComboButton->GetEditCtrl();
if (pCbo == NULL || pEdit == NULL)
break;
pCbo->SetFont(&m_ToolBarBtnFont);
pEdit->SetFont(&m_ToolBarBtnFont);
m_wndTopToolBar.InvalidateButton(nZoomIndex);
int nSel = GetZoomComboIndex(m_Zoom);
if (nSel >= 0)
{
pCbo->SetCurSel(nSel);
CString str;
pCbo->GetWindowText(str);
pComboButton->SetText(str);
}
} while (false);
//
CGuiEditBox GuiEditBox;
GuiEditBox.EnableWindow(TRUE);
m_wndTopToolBar.ReplaceButton(IDC_GUIEDITBOX_DUMMY, GuiEditBox);
do
{
CMFCToolBarButton* pButton = NULL;
int nGuiIndex = m_wndTopToolBar.CommandToIndex(IDC_GUIEDITBOX);
if (nGuiIndex == -1)
break;
pButton = m_wndTopToolBar.GetButton(nGuiIndex);
if (pButton == NULL)
break;
ASSERT(pButton->IsKindOf(RUNTIME_CLASS(CMFCToolBarEditBoxButton)));
CMFCToolBarEditBoxButton* pEditBoxButton = (CMFCToolBarEditBoxButton*)pButton;
CEdit* pEdit = pEditBoxButton->GetEditBox();
if (pEdit == NULL)
break;
pEdit->SetFont(&m_ToolBarBtnFont); // height of this font is much less than default
//CFont* pFont = pEdit->GetFont();
//LOGFONT lf;
//pFont->GetLogFont(&lf); // confirmed that font has been changed
m_wndTopToolBar.InvalidateButton(nGuiIndex);
} while (false);
}
break;
}
return 0;
}
//
void CMFCToolBarEx::AdjustLocations()
{
CMFCToolBar::AdjustLocations();
if (GetSafeHwnd())
{
CMFCToolBarButton* pButton = NULL;
int nGuiIndex = CommandToIndex(IDC_GUIEDITBOX);
if (nGuiIndex != -1)
{
pButton = GetButton(nGuiIndex);
if (pButton)
{
ASSERT(pButton->IsKindOf(RUNTIME_CLASS(CMFCToolBarEditBoxButton)));
CMFCToolBarEditBoxButton* pEditBoxButton = (CMFCToolBarEditBoxButton*)pButton;
CEdit* pEdit = pEditBoxButton->GetEditBox();
if (pEdit != NULL)
{
CRect rPos;
pEdit->GetRect(&rPos);
rPos.DeflateRect(0, 4);
pEdit->SetRect(rPos);
}
}
}
}
}
I investigated the source code for afxtoolbareditboxbutton.cpp and saw that the height of the edit box is being set in the OnMove method by the following line
int cy = GetGlobalData()->GetTextHeight();
I changed that line in a subclass of CMFCToolBarEditBoxButton to resolve my problem.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import static java.lang.Math.pow;
public class InfixExpressionEvaluator {
// Tokenizer to break up our input into tokens
StreamTokenizer tokenizer;
// Stacks for operators (for converting to postfix) and operands (for
// evaluating)
StackInterface<Character> operatorStack;
StackInterface<Double> operandStack;
//counts brackets
int Bracket1=0, Bracket2=0, count = 0;
/**
* Initializes the evaluator to read an infix expression from an input
* stream.
* #param input the input stream from which to read the expression
*/
public InfixExpressionEvaluator(InputStream input) {
// Initialize the tokenizer to read from the given InputStream
tokenizer = new StreamTokenizer(new BufferedReader(
new InputStreamReader(input)));
// StreamTokenizer likes to consider - and / to have special
meaning.
// Tell it that these are regular characters, so that they can be
parsed
// as operators
tokenizer.ordinaryChar('-');
tokenizer.ordinaryChar('/');
// Allow the tokenizer to recognize end-of-line, which marks the
end of
// the expression
tokenizer.eolIsSignificant(true);
// Initialize the stacks
operatorStack = new ArrayStack<Character>();
operandStack = new ArrayStack<Double>();
}
/**
* Parses and evaluates the expression read from the provided input
stream,
* then returns the resulting value
* #return the value of the infix expression that was parsed
*/
public Double evaluate() throws ExpressionError {
// Get the first token. If an IO exception occurs, replace it with
a
// runtime exception, causing an immediate crash.
try {
tokenizer.nextToken();
} catch (IOException e) {
throw new RuntimeException(e);
}
boolean preNum = false, preOp = false;
boolean preOpenbracket = false, preClosebracket = false;
int Bracket1 = 0, Bracket2 = 0, count = 0;
// Continue processing tokens until we find end-of-line
while (tokenizer.ttype != StreamTokenizer.TT_EOL) {
// Consider possible token type
switch (tokenizer.ttype) {
case StreamTokenizer.TT_NUMBER:
// Expression error handling
if ((preNum == true) && (count > 0)) {
throw new ExpressionError("Two operands in a row");
}
if ((preClosebracket == true) && (count > 0)) {
throw new ExpressionError("A close bracket cannot
be followed by a number");
}
// If the token is a number, process it as a double-
valued
// operand
processOperand((double) tokenizer.nval);
preOp = false;
preNum = true;
preOpenbracket = false;
preClosebracket = false;
break;
case '+':
case '-':
case '*':
case '/':
case '^':
// check for errror in input
if (count == 0) {
throw new ExpressionError("Leading off with
operator is illegal");
}
if ((preOp == true) && (count > 0)) {
throw new ExpressionError("Two operators in a
row");
}
if ((preOpenbracket == true) && (count > 0)) {
throw new ExpressionError("An open bracket cannot
be followed by an operator");
}
// If the token is any of the above characters, process
it
// is an operator
processOperator((char) tokenizer.ttype);
preOp = true;
preNum = false;
preOpenbracket = false;
preClosebracket = false;
break;
case '(':
case '[':
// Expression error handling
if ((preNum == true) && (count > 0)) {
throw new ExpressionError("An open bracket cannot
be preceded by a number");
}
// If the token is open bracket, process it as such.
Forms
// of bracket are interchangeable but must nest
properly.
processOpenBracket((char) tokenizer.ttype);
preOp = false;
preNum = false;
preOpenbracket = true;
preClosebracket = false;
Bracket1++;
break;
case ')':
case ']':
// Expression error handling
if ((preOp == true) && (count > 0)) {
throw new ExpressionError("A close bracket cannot
be preceded by a operator");
}
// If the token is close bracket, process it as such.
Forms
// of bracket are interchangeable but must nest
properly.
processCloseBracket((char) tokenizer.ttype);
preOp = false;
preNum = false;
preOpenbracket = false;
preClosebracket = true;
Bracket2++;
break;
case StreamTokenizer.TT_WORD:
// If the token is a "word", throw an expression error
throw new ExpressionError("Unrecognized token: "
+ tokenizer.sval);
default:
// If the token is any other type or value, throw an
// expression error
throw new ExpressionError("Unrecognized token: "
+ String.valueOf((char) tokenizer.ttype));
}
count++;
// Read the next token, again converting any potential IO
exception
try {
tokenizer.nextToken();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// Almost done now, but we may have to process remaining operators
in
// the operators stack
processRemainingOperators();
if (Bracket1 != Bracket2) {
throw new ExpressionError("\nNot the same number of bracket");
}
// Return the result of the evaluation -
return operandStack.pop();
}
void processOperand(double operand) {
//push operand
operandStack.push(operand);
}
void processOperator(char operator) {
// Precedence order: ^*/ level 2, +- level 1, ( and [ has lowest
level 0
while (!operatorStack.isEmpty() && hasPrecedence(operator,
operatorStack.peek())) {
// perform step 1a,1b,1c,1d
operandStack.push(applyOp(operatorStack.pop(),
operandStack.pop(), operandStack.pop()));
}
// Step 2: thisOp has more precedence than one on top of
operatorStack, push it
operatorStack.push(operator);
}
// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')' || op2 == '[' || op2 == ']')
return false;
if ((op1 == '*' || op1 == '/' || op1 == '^') && (op2 == '+' || op2
== '-'))
return false;
else
return true;
}
void processOpenBracket(char openBracket) {
operatorStack.push(openBracket);
}
void processCloseBracket(char closeBracket) {
//Declare variables
char operator='0';
double a=0, b=0, c=0;
boolean correct = true;
//check for error before loop
if (operatorStack.isEmpty()) {
throw new ExpressionError("Brackets/parenthasis are uneven");
}
if (operatorStack.peek()== '(' || operatorStack.peek()=='[') {
throw new ExpressionError("There was an empty set of brackets
or unneeded use of brackets");
}
if (operandStack.isEmpty()) {
throw new ExpressionError("Too many operators");
}
//loop through stacks and pop off operators and operands
while (correct) {
operator = operatorStack.pop();
b = operandStack.pop();
a = operandStack.pop();
//check to see if next one is bracket
if (operatorStack.peek() == '(' || operatorStack.peek() == '[')
{
correct = false;
}
}
//check for errors
if (closeBracket == ')' && !operatorStack.isEmpty() &&
operatorStack.peek() != '(') {
throw new ExpressionError("Parenthesis do not match");
}
if (closeBracket == ']' && !operatorStack.isEmpty() &&
operatorStack.peek() != '[') {
throw new ExpressionError("Brackets do not match");
}
//calculate result and push it onto the stack, pop off bracket
c = applyOp(operator, b, a);
operandStack.push(c);
operatorStack.pop();
}
public static double applyOp(char op, double b, double a)
{
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '^':
return pow(a,b);
case '/':
//check for division by zero
if (b == 0)
throw new ExpressionError("No division by zero");
return a / b;
}
return 0;
}
/**
* This method is called when the evaluator encounters the end of an
* expression. It manipulates operatorStack and/or operandStack to
process
* the operators that remain on the stack, according to the Infix-to-
Postfix
* and Postfix-evaluation algorithms.
*/
void processRemainingOperators() {
//error check
double a;
if (!operatorStack.isEmpty()) {
if (operatorStack.peek()=='(' || operatorStack.peek()=='[') {
throw new ExpressionError("Uneven number of parenthesis");
}
//check for expression ending with operator
a=operandStack.pop();
if (operandStack.isEmpty()) {
throw new ExpressionError("You can not end with an
operator");
}
operandStack.push(a);
}
//process the remaining operators and answer is placed in the stack
alone
while (!operatorStack.isEmpty()) {
operandStack.push(applyOp(operatorStack.pop(),
operandStack.pop(), operandStack.pop()));
}
}
/**
* Creates an InfixExpressionEvaluator object to read from System.in,
then
* evaluates its input and prints the result.
* #param args not used
*/
public static void main(String[] args) {
System.out.println("\nInfix expression:");
InfixExpressionEvaluator evaluator =
new InfixExpressionEvaluator(System.in);
Double value = null;
try {
value = evaluator.evaluate();
} catch (ExpressionError e) {
System.out.println("ExpressionError: " + e.getMessage());
}
if (value != null) {
System.out.println(value);
} else {
System.out.println("Evaluator returned null");
}
}
}
So for this program we're supposed to use implement two stacks to do simple arithmetic. If entered correctly, the program works, but when I try to do error catching it doesn't work. I tried using counter variables for counting number of parenthesis, brackets but it didn't work. Here are some cases that didn't work:
2^(2+3*4)
2*14.5+6/5-(5*8-5/9)
10000 * [1+.20/12]^(12*4)
(4+3*2 (error catch here. program should report error because there
is no closed parenthesis)
and many more... any ideas?
I am getting this error in unity:
5.50f3
Assets/Scripts/BaseClient/client.c s(14701,12): error CS0136: A local variable named 'text' cannot be declared in this scope because it would give a different meaning to 'text', which is already used in a 'child' scope to denote something else
Here is snippet of code:
case 126:
//String text = inStream.readString();
int frame = inStream.method435();
if (text.StartsWith("www."))
{
//openURL(text);
pktType = -1; return true;
}
if(text != null && frame != null)
{
updateStrings(text, frame);
sendFrame126(text, frame);
}
if (frame >= 18144 && frame <= 18244)
{
//clanList[frame - 18144] = text;
}
pktType = -1; return true;
The error is simply letting you know that you are reusing the same name for two variables:
int myVar = 0; // this one is global to the class
void Start()
{
int myVar = 20; // local variable, same name => problem
}
other case is within statement
if(condA)
{
int myResult = MethodA();
}
else
{
int myResult = MethodB();
}
This is likely what you are facing. Either give a different name in each subsection or get the variable out:
int myResult = -1;
if(condA)
{
myResult = MethodA();
}
else
{
myResult = MethodB();
}
This is likely what you are facing. Either give a different name in each
I have this condition
if(Model.Bids != null && Model.Bids.Items != null && Model.Bids.Items.Count > 0)
{
...
}
Problem is, I think this is ugly. I could write a function that encapsulates this but I wonder if there is something else that would help me write something like just the important bits below without having to do the null checks. If not then this would be a handy language extension.
if(Model.Bids.Items.Count > 0)
{
...
}
For c# this two options achieve sort of what you want but I wouldn't put this in my software quickly.
Also I doubt this gets more readable or better understandable. There is one other option but that requires you to refactor you Model class chain. If you implement a NullObject for the type in Bids and the type in Item you can do if(Model.Bids.Items.Count > 0) because all types will not be null but have an implementation that handles the Empty state (much like String.Empty)
helpers
/* take a func, wrap in a try/catch, invoke compare */
bool tc(Func<bool> comp )
{
try
{
return comp.Invoke();
}
catch (Exception)
{
return false;
}
}
/* helper for f */
T1 f1<T,T1>(T root, Func<T, T1> p1) where T:class
{
T1 res = default(T1);
if (root != null)
{
res = p1.Invoke(root);
}
return res;
}
/* take a chain of funcs and a comp if the last
in the chain is still not null call comp (expand if needed) */
bool f<T,T1,T2,TL>( T root, Func<T,T1> p1, Func<T1,T2> p2, Func<T2,TL> plast,
Func<TL, bool> comp) where T:class where T1:class where T2:class
{
var allbutLast = f1(f1(root, p1), p2);
return allbutLast != null && comp(plast.Invoke(allbutLast));
}
Usage
var m = new Model();
if (f(m, p => p.Bids, p => p.Items, p => p.Count, p => p > 0))
{
Debug.WriteLine("f");
}
if (tc(() => m.Bids.Items.Count > 0))
{
Debug.WriteLine("tc ");
}
if (m.Bids != null && m.Bids.Items != null && m.Bids.Items.Count > 0)
{
Debug.WriteLine("plain");
}